diff --git a/CODEOWNERS b/CODEOWNERS index 9a557753d3206996fb43ed7fe73d482968fee112..7c6530eb16de9051510d7344025cf8b61c566c78 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -29,11 +29,22 @@ zh-cn/device-dev/quick-start/quickstart-lite-env-setup.md @li-yan339 @chenmudan zh-cn/device-dev/porting/porting-thirdparty-overview.md @Austin23 @chenmudan zh-cn/device-dev/porting/porting-thirdparty-makefile.md @Austin23 @chenmudan zh-cn/device-dev/porting/porting-thirdparty-cmake.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-mini-lite.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-standard-large.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guid.md @Austin23 @chenmudan -zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-all.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-coding-style-and-best-practice.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-kconfig-visual-config-guide.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-product.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-zh-cn/device-dev/subsystems/subsystem.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-component.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-module.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-chip_solution.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-feature.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-syscap.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-reference.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-reference.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-reference.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-reference.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-gn-hap-compilation-guide.md @Austin23 @chenmudan +zh-cn/device-dev/subsystems/subsys-build-FAQ.md @Austin23 @chenmudan zh-cn/device-dev/subsystems/subsys-remote-start.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-overview.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-graphics-container-guide.md @duangavin123_admin @@ -210,6 +221,7 @@ zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-display.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-effectKit.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang @@ -219,7 +231,7 @@ zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-camera.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-image.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-media.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-medialibrary.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-i18n.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-intl.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @HelloCrease @@ -305,6 +317,7 @@ zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-thermal.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-update.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-usb.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.mdd @ge-yafang zh-cn/application-dev/reference/apis/js-apis-vibrator.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-appAccount.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @zengyawen @@ -352,4 +365,7 @@ zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease zh-cn/application-dev/website.md @zengyawen zh-cn/application-dev/faqs/ @zengyawen -zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen \ No newline at end of file +zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @zengyawen +zh-cn/application-dev/reference/apis/Readme-CN.md @zengyawen \ No newline at end of file diff --git a/OAT.xml b/OAT.xml index 8cc884632d4a963fa921c5905cfbf96e7e22edb7..4edf72f5a3b3e03801bdab83dad547cd7c0c18ef 100644 --- a/OAT.xml +++ b/OAT.xml @@ -66,7 +66,7 @@ - + diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index 8e42633391269303e5e8d888561281f57d1718ae..f3fa0e7ac0e9b829f2418e4b1bf96001e66553d2 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -8,14 +8,14 @@ - Quick Start - Getting Started - [Preparations](quick-start/start-overview.md) - - [Getting Started with eTS in the Traditional Coding Approach](quick-start/start-with-ets.md) - - [Getting Started with eTS in the Low-Code Approach](quick-start/start-with-ets-low-code.md) - - [Getting Started with JavaScript in the Traditional Coding Approach](quick-start/start-with-js.md) - - [Getting Started with JavaScript in the Low-Code Approach](quick-start/start-with-js-low-code.md) + - [Getting Started with eTS in Stage Model](quick-start/start-with-ets-stage.md) + - [Getting Started with eTS in FA Model](quick-start/start-with-ets-fa.md) + - [Getting Started with JavaScript in FA Model](quick-start/start-with-js-fa.md) - Development Fundamentals - [Application Package Structure Configuration File (FA Model)](quick-start/package-structure.md) - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [SysCap](quick-start/syscap.md) + - [HarmonyAppProvision Configuration File](quick-start/app-provision-structure.md) - Development - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) @@ -37,12 +37,16 @@ - Tools - [DevEco Studio (OpenHarmony) User Guide](quick-start/deveco-studio-user-guide-for-openharmony.md) - Hands-On Tutorials - - [Samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) + - [Samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) - [Codelabs](https://gitee.com/openharmony/codelabs) - API References - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - APIs - [JS and TS APIs](reference/apis/Readme-EN.md) + - Native APIs + - [Standard Libraries](reference/native-lib/third_party_libc/musl.md) + - [Node_API](reference/native-lib/third_party_napi/napi.md) +- [FAQs](faqs/Readme-EN.md) - Contribution - [How to Contribute](../contribute/documentation-contribution.md) diff --git a/en/application-dev/ability/context-userguide.md b/en/application-dev/ability/context-userguide.md index ba95ade27a3c7cb846be2d254fd3b75d65dd8701..d3e681244166cafecff86575dd1850db4ebf7f90 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability/context-userguide.md @@ -7,9 +7,11 @@ 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). ![contextIntroduction](figures/contextIntroduction.png) diff --git a/en/application-dev/ability/figures/contextIntroduction.png b/en/application-dev/ability/figures/contextIntroduction.png index 9f49f270750549a5326724dc0db1560dbda07c44..7345a1a5a6a3471782e9399129c98f3d529bbfd5 100644 Binary files a/en/application-dev/ability/figures/contextIntroduction.png and b/en/application-dev/ability/figures/contextIntroduction.png differ diff --git a/en/application-dev/ability/figures/stage-call.png b/en/application-dev/ability/figures/stage-call.png index 28f2a0f7ea9d86fc81e0c1a37d556384b14a9bdd..4c0c0770a4dce6f275b0fc355f70c5dfca2adb17 100644 Binary files a/en/application-dev/ability/figures/stage-call.png and b/en/application-dev/ability/figures/stage-call.png differ diff --git a/en/application-dev/ability/stage-ability-continuation.md b/en/application-dev/ability/stage-ability-continuation.md index 6945f49db8ef05109452fc1b3dcad3dc1e5ddeca..701b730a833a7b97f00398746cddae4d2856a248 100644 --- a/en/application-dev/ability/stage-ability-continuation.md +++ b/en/application-dev/ability/stage-ability-continuation.md @@ -41,7 +41,7 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar "module": { "abilities": [ { - "continuable": true, + "continuable": true } ] } @@ -62,7 +62,7 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar "module": { "abilities": [ { - "launchType": "standard", + "launchType": "standard" } ] } @@ -76,7 +76,7 @@ The code snippets provided below are all from [Sample](https://gitee.com/openhar "module": { "abilities": [ { - "launchType": "singleton", + "launchType": "singleton" } ] } diff --git a/en/application-dev/ability/stage-call.md b/en/application-dev/ability/stage-call.md index 6b5823e76db2c95190111a55b9d2ef43ddd2d946..cad2aeddec2ae0782776009d4a8a9b092bace023 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability/stage-call.md @@ -1,43 +1,63 @@ # Ability Call Development ## When to Use -Ability call is an extension of the ability capabilities. It enables an ability to be invoked by external systems. In this way, the ability can be displayed as a UI page on the foreground and created and run on the background. You can use the **Call** APIs to implement data sharing between different abilities through inter-process communication (IPC). There are two roles in the ability call: caller and callee. The following scenarios are involved in the ability call development: -- Creating a callee -- Accessing the callee +Ability call is an extension of the ability capability. It enables an ability to be invoked by and communicate with external systems. The ability invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two abilities (caller ability and callee ability) through inter-process communication (IPC). -The following figure shows the ability call process. +The core API used for the ability call is `startAbilityByCall`, which differs from `startAbility` in the following ways: + - `startAbilityByCall` supports ability startup in the foreground and background, whereas `startAbility` supports ability startup in the foreground only. + - The caller ability can use the `Caller` object returned by `startAbilityByCall` to communicate with the callee ability, but `startAbility` does not provide the communication capability. +Ability call is usually used in the following scenarios: +- Communicating with the callee ability +- Starting the callee ability in the background + +**Table 1** Terms used in the ability call +|Term|Description| +|:------|:------| +|Caller ability|Ability that triggers the ability call.| +|Callee ability|Ability invoked by the ability call.| +|Caller |Object returned by `startAbilityByCall` and used by the caller ability to communicate with the callee ability.| +|Callee |Object held by the callee ability to communicate with the caller ability.| +|IPC |Inter-process communication.| + +The ability call process is as follows: + - The caller ability uses `startAbilityByCall` to obtain a `Caller` object and uses `call()` of the `Caller` object to send data to the callee ability. + - The callee ability, which holds a `Callee` object, uses `on()` of the `Callee` object to register a callback. This callback is invoked when the callee ability receives data from the caller ability. ![stage-call](figures/stage-call.png) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The startup mode of the callee must be **singleton**. -> Currently, only system applications and Service Extension abilities can use the **Call** APIs to access the callee. +> **NOTE**
+> The launch type of the callee ability must be `singleton`. +> Currently, only system applications can use the ability call. ## Available APIs The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller). -**Table 1** Ability call APIs +**Table 2** Ability call APIs |API|Description| |:------|:------| -|startAbilityByCall(want: Want): Promise\|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.| -|on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee registers a method.| -|off(method: string): void|Callback invoked when the callee deregisters a method.| -|call(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee.| -|callWithResult(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| -|release(): void|Releases the caller interface.| -|onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.| +|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).| +|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.| +|callWithResult(method: string, data: rpc.Sequenceable): Promise\|Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.| +|release(): void|Releases the `Caller` object.| +|onRelease(callback: OnReleaseCallBack): void|Callback invoked when the `Caller` object is released.| ## How to Develop -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. -### Creating a Callee -For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener. -1. Configure the ability startup mode. +The procedure for developing the ability call is as follows: +1. Create a callee ability. +2. Access the callee ability. +> **NOTE** +> +> The code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. +### Creating a Callee Ability +For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use `on()` to register a listener. When data does not need to be received, use `off()` to deregister the listener. +**1. Configure the ability launch type.** - Set the ability of the callee to **singleton** in the **module.json5** file. + Set `launchType` of the callee ability to `singleton` in the `module.json5` file. |JSON Field|Description| |:------|:------| -|"launchType"|Ability startup mode. Set this parameter to **singleton**.| +|"launchType"|Ability launch type. Set this parameter to `singleton`.| An example of the ability configuration is as follows: ```json @@ -51,13 +71,13 @@ An example of the ability configuration is as follows: "visible": true }] ``` -2. Import the **Ability** module. -``` +**2. Import the Ability module.** +```ts import Ability from '@ohos.application.Ability' ``` -3. Define the agreed sequenceable data. +**3. Define the agreed sequenceable data.** - The data formats sent and received by the caller and callee must be consistent. In the following example, the data consists of numbers and strings. The sample code snippet is as follows: + The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The code snippet is as follows: ```ts export default class MySequenceable { num: number = 0 @@ -81,23 +101,23 @@ export default class MySequenceable { } } ``` -4. Implement **Callee.on** and **Callee.off**. +**4. Implement `Callee.on` and `Callee.off`.** - The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows: + The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the `MSG_SEND_METHOD` listener is registered in `onCreate` of the ability and deregistered in `onDestroy`. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The code snippet is as follows: ```ts const TAG: string = '[CalleeAbility]' const MSG_SEND_METHOD: string = 'CallSendMsg' function sendMsgCallback(data) { - Logger.log(TAG, 'CalleeSortFunc called') + console.log('CalleeSortFunc called') - // Obtain the sequenceable data sent by the caller. + // Obtain the sequenceable data sent by the caller ability. let receivedData = new MySequenceable(0, '') data.readSequenceable(receivedData) - Logger.log(TAG, `receiveData[${receivedData.num}, ${receivedData.str}]`) + console.log(`receiveData[${receivedData.num}, ${receivedData.str}]`) // Process the data. - // Return the sequenceable data result to the caller. + // Return the sequenceable data result to the caller ability. return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) } @@ -106,7 +126,7 @@ export default class CalleeAbility extends Ability { try { this.callee.on(MSG_SEND_METHOD, sendMsgCallback) } catch (error) { - Logger.error(TAG, `${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) + console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) } } @@ -120,15 +140,27 @@ export default class CalleeAbility extends Ability { } ``` -### Accessing the Callee -1. Import the **Ability** module. -``` +### Accessing the Callee Ability +**1. Import the Ability module.** +```ts import Ability from '@ohos.application.Ability' ``` -2. Obtain the caller interface. +**2. Obtain the `Caller` object.** - The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller interface of the ability. The following example uses **this.context** to obtain the **context** attribute of the **Ability** instance, uses **startAbilityByCall** to start the callee, obtain the caller interface, and register the **onRelease** listener of the caller. You need to implement processing based on service requirements. The sample code snippet is as follows: + The `context` attribute of the ability implements `startAbilityByCall` to obtain the `Caller` object for communication. The following example uses `this.context` to obtain the `context` attribute of the ability, uses `startAbilityByCall` to start the callee ability, obtain the `Caller` object, and register the `onRelease` listener of the caller ability. You need to implement processing based on service requirements. The code snippet is as follows: ```ts +// Register the onRelease listener of the caller ability. +private regOnRelease(caller) { + try { + caller.onRelease((msg) => { + console.log(`caller onRelease is called ${msg}`) + }) + console.log('caller register OnRelease succeed') + } catch (error) { + console.log(`caller register OnRelease failed with ${error}`) + } +} + async onButtonGetCaller() { try { this.caller = await context.startAbilityByCall({ @@ -136,73 +168,74 @@ async onButtonGetCaller() { abilityName: 'CalleeAbility' }) if (this.caller === undefined) { - Logger.error(TAG, 'get caller failed') + console.log('get caller failed') return } - Logger.log(TAG, 'get caller success') + console.log('get caller success') this.regOnRelease(this.caller) } catch (error) { - Logger.error(TAG, `get caller failed with ${error}`) + console.log(`get caller failed with ${error}`) } -}.catch((error) => { - console.error(TAG + 'get caller failed with ' + error) -}) +} ``` - In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows: + In the cross-device scenario, you need to specify the ID of the peer device. The code snippet is as follows: ```ts -let TAG = '[MainAbility] ' -var caller = undefined -let context = this.context - -context.startAbilityByCall({ - deviceId: getRemoteDeviceId(), - bundleName: 'com.samples.CallApplication', - abilityName: 'CalleeAbility' -}).then((data) => { - if (data != null) { - caller = data - console.log(TAG + 'get remote caller success') - // Register the onRelease listener of the caller. - caller.onRelease((msg) => { - console.log(TAG + 'remote caller onRelease is called ' + msg) - }) - console.log(TAG + 'remote caller register OnRelease succeed') - } -}).catch((error) => { - console.error(TAG + 'get remote caller failed with ' + error) -}) +async onButtonGetRemoteCaller() { + var caller = undefined + var context = this.context + + context.startAbilityByCall({ + deviceId: getRemoteDeviceId(), + bundleName: 'com.samples.CallApplication', + abilityName: 'CalleeAbility' + }).then((data) => { + if (data != null) { + caller = data + console.log('get remote caller success') + // Register the onRelease listener of the caller ability. + caller.onRelease((msg) => { + console.log(`remote caller onRelease is called ${msg}`) + }) + console.log('remote caller register OnRelease succeed') + } + }).catch((error) => { + console.error(`get remote caller failed with ${error}`) + }) +} ``` - Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows: + Obtain the ID of the peer device from `DeviceManager`. Note that the `getTrustedDeviceListSync` API is open only to system applications. The code snippet is as follows: ```ts import deviceManager from '@ohos.distributedHardware.deviceManager'; var dmClass; function getRemoteDeviceId() { if (typeof dmClass === 'object' && dmClass != null) { - var list = dmClass.getTrustedDeviceListSync(); + var list = dmClass.getTrustedDeviceListSync() if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { - console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); - return; + console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null") + return } - console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); - return list[0].deviceId; + console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId) + return list[0].deviceId } else { - console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); + console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null") } } ``` - In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows: + In the cross-device scenario, your application must also apply for the data synchronization permission from end users. The code snippet is as follows: ```ts -let context = this.context -let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] -context.requestPermissionsFromUser(permissions).then((data) => { - console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) -}).catch((error) => { - console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) -}) +requestPermission() { + let context = this.context + let permissions: Array = ['ohos.permission.DISTRIBUTED_DATASYNC'] + context.requestPermissionsFromUser(permissions).then((data) => { + console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) + }).catch((error) => { + console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) + }) +} ``` -3. Send agreed sequenceable data. +**3. Send agreed sequenceable data.** - The sequenceable data can be sent to the callee with or without a return value. The method and sequenceable data must be consistent with those of the callee. The following example describes how to invoke the **Call** API to send data to the callee. The sample code snippet is as follows: + The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. The code snippet is as follows: ```ts const MSG_SEND_METHOD: string = 'CallSendMsg' async onButtonCall() { @@ -210,12 +243,12 @@ async onButtonCall() { let msg = new MySequenceable(1, 'origin_Msg') await this.caller.call(MSG_SEND_METHOD, msg) } catch (error) { - Logger.error(TAG, `caller call failed with ${error}`) + console.log(`caller call failed with ${error}`) } } ``` - In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows: + In the following, `CallWithResult` is used to send data `originMsg` to the callee ability and assign the data processed by the `CallSendMsg` method to `backMsg`. The code snippet is as follows: ```ts const MSG_SEND_METHOD: string = 'CallSendMsg' originMsg: string = '' @@ -224,26 +257,28 @@ async onButtonCallWithResult(originMsg, backMsg) { try { let msg = new MySequenceable(1, originMsg) const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg) - Logger.log(TAG, 'caller callWithResult succeed') + console.log('caller callWithResult succeed') let result = new MySequenceable(0, '') data.readSequenceable(result) backMsg(result.str) - Logger.log(TAG, `caller result is [${result.num}, ${result.str}]`) + console.log(`caller result is [${result.num}, ${result.str}]`) } catch (error) { - Logger.error(TAG, `caller callWithResult failed with ${error}`) + console.log(`caller callWithResult failed with ${error}`) } } ``` -4. Release the caller interface. +**4. Release the `Caller` object.** - When the caller interface is no longer required, call the **release** API to release it. The sample code snippet is as follows: + When the `Caller` object is no longer required, use `release()` to release it. The code snippet is as follows: ```ts -try { - this.caller.release() - this.caller = undefined - Logger.log(TAG, 'caller release succeed') -} catch (error) { - Logger.error(TAG, `caller release failed with ${error}`) +releaseCall() { + try { + this.caller.release() + this.caller = undefined + console.log('caller release succeed') + } catch (error) { + console.log(`caller release failed with ${error}`) + } } ``` diff --git a/en/application-dev/ability/wantagent.md b/en/application-dev/ability/wantagent.md index eacc92936960cca3bd022e6438a63c15a8f2688a..5a85bab15b8422aaabb0a173ad888126e08fc038 100644 --- a/en/application-dev/ability/wantagent.md +++ b/en/application-dev/ability/wantagent.md @@ -1,6 +1,8 @@ # WantAgent Development ## When to Use -The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. +The **WantAgent** class encapsulates want information that specifies a particular action, which can be starting an ability or publishing a common event. You can either call **wantAgent.trigger** to trigger a **WantAgent** directly or add a **WantAgent** to a notification so that it will be triggered when users tap the notification. + + ## Available APIs | API | Description| @@ -21,7 +23,7 @@ The **WantAgent** class encapsulates want information that specifies a particula ``` private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. - //wantAgentInfo + // wantAgentInfo var wantAgentInfo = { wants: [ { @@ -45,7 +47,7 @@ The **WantAgent** class encapsulates want information that specifies a particula ``` private wantAgentObj = null // Save the WantAgent object created. It will be used to complete the trigger operations. - //wantAgentInfo + // wantAgentInfo var wantAgentInfo = { wants: [ { diff --git a/en/application-dev/application-dev-guide-for-gitee.md b/en/application-dev/application-dev-guide-for-gitee.md index e60f2c01333c1bef7324b3ef6cfe2c83821a95cd..f074e1906535d708b193adea3b1ee3308fb0de4e 100644 --- a/en/application-dev/application-dev-guide-for-gitee.md +++ b/en/application-dev/application-dev-guide-for-gitee.md @@ -47,7 +47,7 @@ DevEco Studio is a high-performance integrated development environment (IDE) rec ### Hands-On Tutorials -To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) and [codelabs](https://gitee.com/openharmony/codelabs). +To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) and [codelabs](https://gitee.com/openharmony/codelabs). ### API References diff --git a/en/application-dev/application-dev-guide.md b/en/application-dev/application-dev-guide.md index 7065480d1c4a12bd0984f4916d678c1bed7a4997..2b22839820539e2919f1a705595a47cc491df8d0 100644 --- a/en/application-dev/application-dev-guide.md +++ b/en/application-dev/application-dev-guide.md @@ -47,7 +47,7 @@ DevEco Studio is a high-performance integrated development environment (IDE) rec ### Hands-On Tutorials -To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/app_samples/blob/master/README.md) and [codelabs](https://gitee.com/openharmony/codelabs). +To make you better understand how functions work together and jumpstart your application development projects, we provide stripped-down, real-world [samples](https://gitee.com/openharmony/applications_app_samples/blob/master/README.md) and [codelabs](https://gitee.com/openharmony/codelabs). ### API References diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index c8cb5c503329f6dc49c66fe457eb0aa8e6debf78..495f3b538b48b22d2d97f213d0e32189be799560 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share |query?(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>): void|Queries data from the database.| |delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void|Deletes data from the database.| -For more details, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md). +For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md). **Table 2** APIs of the data consumer @@ -25,11 +25,11 @@ For more details, see [DataShareExtensionAbility](../reference/apis/js-apis-appl | query(uri: string, predicates: DataSharePredicates, columns: Array<string>, callback: AsyncCallback<DataShareResultSet>): void | Queries data from the database. | | delete(uri: string, predicates: DataSharePredicates, callback: AsyncCallback<number>): void | Deletes one or more data records from the database.| -For more details, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md). +For more information, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md). ## When to Use -There are two roles in **DataShare**. +There are two roles in **DataShare**: - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data consumer: accesses the data provided by the provider using **DataShareHelper**. @@ -41,10 +41,10 @@ Examples are given below. 1. Import the dependencies. ```ts - import Extension from '@ohos.application.DataShareExtensionAbility' + import Extension from '@ohos.application.DataShareExtensionAbility'; import rdb from '@ohos.data.rdb'; - import fileIo from '@ohos.fileio' - import dataSharePredicates from '@ohos.data.dataSharePredicates' + import fileIo from '@ohos.fileio'; + import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` 2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API. @@ -80,7 +80,7 @@ Examples are given below. } // Override the query() API. - query(uri, predicates, columns, callback) { + query(uri, predicates, columns, callback) { if (predicates == null || predicates == undefined) { console.info('invalid predicates'); } @@ -144,48 +144,49 @@ Examples are given below. let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); ``` -2. Create a **DataShareHelper** instance. +3. Create a **DataShareHelper** instance. ```ts let dsHelper; let abilityContext; + export default class MainAbility extends Ability { onWindowStageCreate(windowStage) { abilityContext = this.context; - dataShare.createDataShareHelper(abilityContext, dseUri, (err,data)=>{ + dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{ dsHelper = data; }); } } ``` -3. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. +4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. ```ts // Construct a piece of data. - var valuesBucket = {"name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1,2,3])}; - var updateBucket = {"name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1,2,3])}; - let da = new dataSharePredicates.DataSharePredicates(); - var valArray =new Array("*"); + var valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; + var updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; + let da = new dataSharePredicates.DataSharePredicates(); + var valArray = new Array("*"); let people = new Array( - {"name": "LiSi", "age": 41, "Binary": ar}, - {"name": "WangWu", "age": 21, "Binary": arr}, - {"name": "ZhaoLiu", "age": 61, "Binary": arr}); + { "name": "LiSi", "age": 41, "Binary": ar }, + { "name": "WangWu", "age": 21, "Binary": arr }, + { "name": "ZhaoLiu", "age": 61, "Binary": arr }); // Insert a piece of data. - dsHelper.insert(dseUri, valuesBucket, (err,data) => { - console.log("dsHelper insert result: " + data); + dsHelper.insert(dseUri, valuesBucket, (err, data) => { + console.log("dsHelper insert result: " + data); }); // Delete data. - dsHelper.delete(dseUri, da, (err,data) => { - console.log("dsHelper delete result: " + data); + dsHelper.delete(dseUri, da, (err, data) => { + console.log("dsHelper delete result: " + data); }); // Update data. - dsHelper.update(dseUri, da, updateBucket, (err,data) => { - console.log("dsHelper update result: " + data); + dsHelper.update(dseUri, da, updateBucket, (err, data) => { + console.log("dsHelper update result: " + data); }); // Query data. - dsHelper.query(dseUri, da, valArray, (err,data) => { - console.log("dsHelper query result: " + data); + dsHelper.query(dseUri, da, valArray, (err, data) => { + console.log("dsHelper query result: " + data); }); ``` diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index eca90200a0d711c91f64643f453ff1d22a3a367f..ec77d5330b57751e36b3ba2d96b57028c340dd36 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -2,14 +2,13 @@ ## When to Use -Distributed data objects allow data traversing across devices to be processed like local variables by shielding complex data interaction between devices. For the devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other devices. The devices can listen for data changes and online and offline status changes of other devices. - -The distributed data objects support basic data types, such as number, string, and Boolean, as well as complex data types, such as array and nested basic types. +The **distributedDataObject** module provides APIs to implement data collaboration of the same application across multiple devices. In addition, the devices that form a Super Device can listen for object status and data changes with each other. +For example, when the data of a distributed data object is added, deleted, or modified for application A on device 1, application A on device 2 can obtain the updated data. In addition, device 2 can listen for data changes and online/offline of the data objects on device 1. ## Available APIs -For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md). +For details about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md). ### Creating a Distributed Data Object Instance @@ -17,53 +16,54 @@ Call **createDistributedObject()** to create a distributed data object instance. **Table 1** API for creating a distributed data object instance -| Package | API | Description | +| Package| API| Description| | -------- | -------- | -------- | -| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.
- **source**: attributes of the **distributedObject** set.
- **DistributedObject**: returns the distributed object created.| +| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.
- **source**: attributes of the distributed data object to set.
- **DistributedObject**: returns the distributed data object created. | ### Generating a Session ID Call **genSessionId()** to generate a session ID randomly. The generated session ID can be used to set the session ID of a distributed data object. **Table 2** API for generating a session ID randomly -| Package | API | Description | +| Package| API| Description| | -------- | -------- | -------- | | ohos.data.distributedDataObject| genSessionId(): string | Generates a session ID, which can be used as the session ID of a distributed data object.| -### Setting a SessionID for Distributed Data Objects +### Setting a Session ID for a Distributed Data Object Call **setSessionId()** to set a session ID for a distributed data object. The session ID is a unique identifier for one collaboration across devices. The distributed data objects to be synchronized must be associated with the same session ID. **Table 3** API for setting a session ID | Class| API| Description| | -------- | -------- | -------- | -| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.
**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| +| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for a distributed data object.
**sessionId**: session ID of a distributed data object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty. | ### Observing Data Changes -Call **on()** to subscribe to data changes of a distributed data object. In the case of data change, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes. +Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes. **Table 4** APIs for observing data changes of a distributed data object -| Class | API | Description | + +| Class| API| Description| | -------- | -------- | -------- | | DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array<string> }>): void | Subscribes to data changes.| -| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void | Unsubscribes from data changes.
**Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.| +| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array<string> }>): void | Unsubscribes from data changes.
**Callback**: callback to unregister. If this parameter is not specified, all data changes of this distributed data object will be unsubscribed from. | ### Observing Online or Offline Status Call **on()** to subscribe to status changes of a distributed data object. The status can be online or offline. When the status changes, a callback will be invoked to return the status. You can use **off()** to unsubscribe from the status changes. **Table 5** APIs for observing status changes of a distributed data object -| Class | API | Description | +| Class| API| Description| | -------- | -------- | -------- | | DistributedDataObject| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to the status changes of a distributed data object.| | DistributedDataObject| off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }>): void | Unsubscribes from status changes of a distributed data object.| -### Saving a Distributed Data Object and Revoking the Data Saving Operation +### Saving or Deleting a Distributed Data Object Call **save()** to save a distributed data object. When the application is active, the saved data will not be released. When the application exits and restarts, the data saved on the device will be restored. -Call **revokeSave()** to revoke a distributed data object that is no longer required. If the distributed data object is saved on the local device, **revokeSave()** will delete the data from all trusted devices. If the distributed data object is not saved on the local device, **revokeSave()** will delete the data from the local device. +Call **revokeSave()** to delete a distributed data object that is no longer required. If the distributed data object is saved on the local device, **revokeSave()** will delete the data from all trusted devices. If the distributed data object is not saved on the local device, **revokeSave()** will delete the data from the local device. The saved data will be released in the following cases: @@ -71,13 +71,12 @@ The saved data will be released in the following cases: - The application has been uninstalled. - Data is successfully restored. -**Table 6** APIs for saving a distributed data object and revoking the saving -| Class | API | Description | +**Table 6** APIs for saving and deleting a distributed data object + +| Class| API| Description| | -------- | -------- | -------- | -| DistributedDataObject | save(deviceId: string): Promise<SaveSuccessResponse> | Saves a distributed data object. This API uses a promise to return the result. | -| DistributedDataObject | save(deviceId: string, callback: AsyncCallback<SaveSuccessResponse>): void | Saves a distributed data object. This API uses an asynchronous callback to return the result. | -| DistributedDataObject | revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. | -| DistributedDataObject | revokeSave(): Promise<RevokeSaveSuccessResponse> | Revokes the data saving operation. This API uses a promise to return the result. | +| DistributedDataObject | save(deviceId: string): Promise<SaveSuccessResponse> | Saves a distributed data object.| +| DistributedDataObject| revokeSave(): Promise<RevokeSaveSuccessResponse> | Deletes a distributed data object. | ## How to Develop @@ -89,11 +88,11 @@ The following example shows how to implement distributed data object synchroniza import distributedObject from '@ohos.data.distributedDataObject'; ``` -2. Request the permission. - - Add the required permission in the **config.json** file. The sample code is as follows: - - ``` +2. Apply for the permission. + + Add the permissions required (FA model) to the **config.json** file. The sample code is as follows: + + ```json { "module": { "reqPermissions": [ @@ -104,11 +103,13 @@ The following example shows how to implement distributed data object synchroniza } } ``` - This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows: - - ``` + For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model). + + This permission must also be granted by the user when the application is started for the first time. The sample code is as follows: + + ```js import featureAbility from '@ohos.ability.featureAbility'; - + function grantPermission() { console.info('grantPermission'); let context = featureAbility.getContext(); @@ -116,93 +117,105 @@ The following example shows how to implement distributed data object synchroniza console.info(`result.requestCode=${result.requestCode}`) }) - console.info('end grantPermission'); + console.info('end grantPermission'); } + grantPermission(); ``` - - - + 3. Obtain a distributed data object instance. The sample code is as follows: ```js - var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, - parent:undefined, list:undefined}); + var local_object = distributedObject.createDistributedObject({ + name: undefined, + age: undefined, + isVis: true, + parent: undefined, + list: undefined + }); var sessionId = distributedObject.genSessionId(); ``` - -4. Add the synchronization network. The data objects in the synchronization network include the local and remote objects. +4. Add the distributed data object instance to a network for data synchronization. The data objects in the synchronization network include the local and remote objects. The sample code is as follows: ```js // Local object - var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true, - parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]}); + var local_object = distributedObject.createDistributedObject({ + name: "jack", + age: 18, + isVis: true, + parent: { mother: "jack mom", father: "jack Dad" }, + list: [{ mother: "jack mom" }, { father: "jack Dad" }] + }); local_object.setSessionId(sessionId); // Remote object - var remote_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, - parent:undefined, list:undefined}); + var remote_object = distributedObject.createDistributedObject({ + name: undefined, + age: undefined, + isVis: true, + parent: undefined, + list: undefined + }); + // After learning that the local device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. remote_object.setSessionId(sessionId); - // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. ``` 5. Observe the data changes of the distributed data object. - You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes. + You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be called to return the data changes. The sample code is as follows: ```js function changeCallback(sessionId, changeData) { - console.info("change" + sessionId); + console.info("change" + sessionId); - if (changeData != null && changeData != undefined) { - changeData.forEach(element => { - console.info("changed !" + element + " " + local_object[element]); - }); - } - } + if (changeData != null && changeData != undefined) { + changeData.forEach(element => { + console.info("changed !" + element + " " + local_object[element]); + }); + } + } - // To refresh the page in changeCallback, correctly bind (this) to the changeCallback. - local_object.on("change", this.changeCallback.bind(this)); + // To refresh the page in changeCallback, correctly bind (this) to the changeCallback. + local_object.on("change", this.changeCallback.bind(this)); ``` -6. Modify object attributes. +6. Modify attributes of the distributed data object. The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). The sample code is as follows: + ```js local_object.name = "jack"; local_object.age = 19; local_object.isVis = false; - local_object.parent = {mother:"jack mom", father:"jack Dad"}; - local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}]; + local_object.parent = { mother: "jack mom", father: "jack Dad" }; + local_object.list = [{ mother: "jack mom" }, { father: "jack Dad" }]; ``` - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** - > - > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. - - Example: + > **NOTE**
+ > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. Example: ```js // Supported modification. - local_object.parent = {mother:"mom", father:"dad"}; + local_object.parent = { mother: "mom", father: "dad" }; // Modification not supported. local_object.parent.mother = "mom"; ``` 7. Access the distributed data object. - Obtain the distributed data object attribute, which is the latest data on the network. + Obtain the distributed data object attributes, which are the latest data on the network. The sample code is as follows: + ```js console.info("name " + local_object["name"]); ``` @@ -221,7 +234,6 @@ The following example shows how to implement distributed data object synchroniza ``` 9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. - The sample code is as follows: ```js @@ -232,55 +244,31 @@ The following example shows how to implement distributed data object synchroniza local_object.on("status", this.statusCallback); ``` -10. Save a distributed data object and revoke the data saving operation. - - - Callback +10. Save a distributed data object and delete it. - ``` - ​```js - // Save a distributed data object. - local_object.save("local", (result, data) => { - console.log("save callback"); - console.info("save sessionId " + data.sessionId); - console.info("save version " + data.version); - console.info("save deviceId " + data.deviceId); - }); - // Revoke the data saving operation. - local_object.revokeSave((result, data) => { - console.log("revokeSave callback"); - console.info("revokeSave sessionId " + data.sessionId); - }); - ​``` - ``` - - - Promise - - ``` - ​```js - // Save a distributed data object. - g_object.save("local").then((result) => { - console.info("save sessionId " + result.sessionId); - console.info("save version " + result.version); - console.info("save deviceId " + result.deviceId); - }, (result)=>{ - console.info("save local failed."); - }); - // Revoke the data saving operation. - g_object.revokeSave().then((result) => { - console.info("revokeSave success."); - }, (result)=>{ - console.info("revokeSave failed."); - }); - ​``` - ``` - - + ```js + // Save a distributed data object. + g_object.save("local").then((result) => { + console.info("save sessionId " + result.sessionId); + console.info("save version " + result.version); + console.info("save deviceId " + result.deviceId); + }, (result) => { + console.info("save local failed."); + }); + // Delete a distributed data object.. + g_object.revokeSave().then((result) => { + console.info("revokeSave success."); + }, (result) => { + console.info("revokeSave failed."); + }); + ``` 11. Unsubscribe from the status changes of the distributed data object. - You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object. + You can specify the callback to unregister. If you do not specify the callback, all status change callbacks of this distributed data object will be unregistered. The sample code is as follows: + ```js // Unregister the specified status change callback. local_object.off("status", this.statusCallback); @@ -290,7 +278,8 @@ The following example shows how to implement distributed data object synchroniza 12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object. - The sample code is as follows: - ```js - local_object.setSessionId(""); - ``` + The sample code is as follows: + + ```js + local_object.setSessionId(""); + ``` diff --git a/en/application-dev/database/database-distributedobject-overview.md b/en/application-dev/database/database-distributedobject-overview.md index 618bc881d563c11c51c9012831f48357a79830b1..80985ed39b8c91a5c9635e0be8fd00f4be2da702 100644 --- a/en/application-dev/database/database-distributedobject-overview.md +++ b/en/application-dev/database/database-distributedobject-overview.md @@ -1,29 +1,29 @@ # Distributed Data Object Overview -The distributed data object management framework is an object-oriented in-memory data management framework. It provides application developers with basic data object management capabilities, such as creating, querying, deleting, modifying, and subscribing to in-memory objects. This management framework also provides distributed capabilities to implement data object collaboration for the same application between multiple devices that form a Super Device. +The distributed data object management framework provides object-oriented in-memory data management. It provides basic data management capabilities, such as creating, querying, deleting, and modifying distributed data objects, and observing data and status changes of the distributed data objects. This management framework also provides distributed capabilities to implement data object collaboration for the same application between multiple devices that form a Super Device. -## Key Concepts +## Basic Concepts - **Distributed in-memory database** - The distributed in-memory database caches data in the memory, so that applications can quickly access data. This database, however, does not store data persistently. If the database is closed, the data is not retained. + The distributed in-memory database caches data in the memory so that applications can quickly access data. This database, however, does not store data persistently. If the database is closed, the data is not retained. - **Distributed data object** - A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading or assigning values to distributed data objects is automatically mapped to the **put** or **get** operation of the corresponding database. + A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **put** and **get** operations in the corresponding database, respectively. The distributed data object can be in the following states in its lifecycle: - **Uninitialized**: The distributed data object is not instantiated or has been destroyed. - **Local**: The data table is created, but the data cannot be synchronized. - - **Distributed**: The data table is created, there are at least two online with the same session ID, and data can be synchronized across devices. If the device is offline or the session ID is empty, the distributed data object changes to the local state. + - **Distributed**: The data table is created, and there are at least two online devices with the same session ID. In this case, data can be synchronized across devices. If a device is offline or the session ID is empty, the distributed data object changes to the local state. ## Working Principles -The distributed data objects are encapsulated into JS objects in distributed in-memory databases, which allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization. +The distributed data objects are encapsulated into JS objects in distributed in-memory databases. This allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization. **Figure 1** Working mechanism @@ -34,7 +34,7 @@ The distributed data objects are encapsulated into JS objects in distributed in- ## Constraints -- Data synchronization can be implemented across devices only for the applications with the same bundleName. +- Data synchronization can be implemented across devices only for the applications with the same **bundleName**. - Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects. diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index dd1594215a10d1c93c9825444253484ed8956e05..2205df9ceffb51c3c6cb7816f6d11784ba532b20 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -6,113 +6,144 @@ The Distributed Data Service (DDS) implements synchronization of application dat ## Available APIs -For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md). +For details about the APIs, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md). **Table 1** APIs provided by the DDS | API | Description | | ------------------------------------------------------------ | ----------------------------------------------- | -| createKVManager(config:KVManagerConfig,callback:AsyncCallback<KVManager>):void
createKVManager(config:KVManagerConfig):Promise<KVManager> | Creates a **KVManager** object for database management.| -| getKVStore<TextendsKVStore>(storeId:string,options:Options,callback:AsyncCallback<T>):void
getKVStore<TextendsKVStore>(storeId:string,options:Options):Promise<T> | Obtains a KV store with the specified **Options** and **storeId**.| -| put(key:string,value:Uint8Array\|string\|number\|boolean,callback:AsyncCallback<void>):void
put(key:string,value:Uint8Array\|string\|number\|boolean):Promise<void> | Inserts and updates data. | -| delete(key:string,callback:AsyncCallback<void>):void
delete(key:string):Promise<void> | Deletes data. | -| get(key:string,callback:AsyncCallback<Uint8Array\|string\|boolean\|number>):void
get(key:string):Promise<Uint8Array\|string\|boolean\|number> | Queries data. | -| on(event:'dataChange',type:SubscribeType,observer:Callback<ChangeNotification>):void
on(event:'syncComplete',syncCallback:Callback<Array<[string,number]>>):void | Subscribes to data changes in the KV store. | -| sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | Triggers database synchronization in manual mode. | - - - +| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| +| getKVStore<TextendsKVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<TextendsKVStore>(storeId: string, options: Options): Promise<T> | Obtains a KV store with the specified **Options** and **storeId**.| +| put(key: string, value: Uint8Array\|string\|number\|boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array\|string\|number\|boolean): Promise<void> | Inserts and updates data. | +| delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | +| get(key: string, callback: AsyncCallback<Uint8Array\|string\|boolean\|number>): void
get(key: string): Promise<Uint8Array\|string\|boolean\|number> | Queries data. | +| on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void
on(event: 'syncComplete', syncCallback: Callback<Array<[string,number]>>): void | Subscribes to data changes in the KV store. | +| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | ## How to Develop The following uses a single KV store as an example to describe the development procedure. 1. Import the distributed data module. + ```js import distributedData from '@ohos.data.distributedData'; ``` +2. Apply for the required permission if data synchronization is required. -2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. - - (1) Create a **KvManagerConfig** object based on the application context. + Add the permission required (FA model) in the **config.json** file. The sample code is as follows: + + ```json + { + "module": { + "reqPermissions": [ + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } + ] + } + } + ``` + For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model). + + This permission must also be granted by the user when the application is started for the first time. The sample code is as follows: + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + function grantPermission() { + console.info('grantPermission'); + let context = featureAbility.getContext(); + context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { + console.info(`result.requestCode=${result.requestCode}`) + + }) + console.info('end grantPermission'); + } + + grantPermission(); + ``` + +3. Create a **kvManager** instance based on the specified **kvManagerConfig** object. + + 1. Create a **kvManagerConfig** object based on the application context. + 2. Create a **kvManager** instance. - (2) Create a **KvManager** instance. - The sample code is as follows: - - ``` + + ```js let kvManager; try { - const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } + const kvManagerConfig = { + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("createKVManager err: " + JSON.stringify(err)); - return; - } - console.log("createKVManager success"); - kvManager = manager; - }); + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("createKVManager err: " + JSON.stringify(err)); + return; + } + console.log("createKVManager success"); + kvManager = manager; + }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log("An unexpected error occurred. Error: " + e); } ``` - - -3. Create and obtain a single KV store. - (1) Declare the ID of the single KV store to create. +4. Create and obtain a single KV store. - (2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. + 1. Declare the ID of the single KV store to create. + 2. Create a single KV store. You are advised to disable automatic synchronization (`autoSync:false`) and call `sync` when a synchronization is required. The sample code is as follows: + ```js let kvStore; try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : false, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S0, - }; - kvManager.getKVStore('storeId', options, function (err, store) { - if (err) { - console.log("getKVStore err: " + JSON.stringify(err)); - return; - } - console.log("getKVStore success"); - kvStore = store; - }); + const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: false, + kvStoreType: distributedData.KVStoreType.SINGLE_VERSION, + securityLevel: distributedData.SecurityLevel.S0 + }; + kvManager.getKVStore('storeId', options, function (err, store) { + if (err) { + console.log("getKVStore err: " + JSON.stringify(err)); + return; + } + console.log("getKVStore success"); + kvStore = store; + }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log("An unexpected error occurred. Error: " + e); } ``` - > **NOTE** + > **NOTE**
> > For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (`kvStore` in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle. + +5. Subscribe to changes in the distributed data. -4. Subscribe to changes in the distributed data.
The following is the sample code for subscribing to the data changes of a single KV store: + ```js kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { console.log("dataChange callback call data: " + JSON.stringify(data)); }); ``` -5. Write data to the single KV store. - - (1) Construct the key and value to be written into the single KV store. +6. Write data to the single KV store. - (2) Write key-value pairs into the single KV store. + 1. Construct the `Key` and `Value` to be written into the single KV store. + 2. Write key-value pairs into the single KV store. The following is the sample code for writing key-value pairs of the string type into the single KV store: @@ -120,52 +151,54 @@ The following uses a single KV store as an example to describe the development p const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { console.log("put err: " + JSON.stringify(err)); return; } console.log("put success"); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } catch (e) { + console.log("An unexpected error occurred. Error: " + e); } ``` -6. Query data in the single KV store. - - (1) Construct the key to be queried from the single KV store. +7. Query data in the single KV store. - (2) Query data from the single KV store. + 1. Construct the `Key` to be queried from the single KV store. + 2. Query data from the single KV store. The following is the sample code for querying data of the string type from the single KV store: + ```js const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { if (err != undefined) { console.log("put err: " + JSON.stringify(err)); return; } console.log("put success"); - kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { console.log("get success data: " + data); }); }); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } catch (e) { + console.log("An unexpected error occurred. Error: " + e); } ``` -7. Synchronize data to other devices.
+8. Synchronize data to other devices. + Select the devices in the same network and the synchronization mode to synchronize data. - > **NOTE** + > **NOTE**
> > The APIs of the `deviceManager` module are system interfaces. + + The following is the example code for synchronizing data in a single KV store: - The following is the sample code for synchronizing data in a single KV store: ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; @@ -185,8 +218,8 @@ The following uses a single KV store as an example to describe the development p try{ // 1000 indicates that the maximum delay is 1000 ms. kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); - }catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } catch (e) { + console.log("An unexpected error occurred. Error: " + e); } } }); diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md index fdb69297523057f5530ef2f885fbe3e0b5cbf5cf..61aa2294c3f8ee077241e347e47e7780f50c4359 100644 --- a/en/application-dev/database/database-preference-guidelines.md +++ b/en/application-dev/database/database-preference-guidelines.md @@ -2,7 +2,7 @@ > **NOTE** > -> This feature is supported since API Version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs. +> This feature is supported since API version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs. ## When to Use @@ -88,8 +88,30 @@ Use the following APIs to delete a **Preferences** instance or data file. 2. Obtain a **Preferences** instance. Read the specified file and load its data to the **Preferences** instance for data operations. + + FA model: + ```js - let promise = data_preferences.getPreferences(this.context, 'mystore'); + // Obtain the context. + import featureAbility from '@ohos.ability.featureAbility' + var context = featureAbility.getContext() + + let promise = data_preferences.getPreferences(context, 'mystore'); + ``` + + Stage model: + + ```ts + // Obtain the context. + import Ability from '@ohos.application.Ability' + var context + class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } + } + + let promise = data_preferences.getPreferences(context, 'mystore'); ``` 3. Write data. @@ -115,12 +137,12 @@ Use the following APIs to delete a **Preferences** instance or data file. ```js promise.then((preferences) => { - let getPromise = preferences.get('startup', 'default'); - getPromise.then((value) => { - console.info("The value of 'startup' is " + value); - }).catch((err) => { - console.info("Failed to get the value of 'startup'. Cause: " + err); - }) + let getPromise = preferences.get('startup', 'default'); + getPromise.then((value) => { + console.info("The value of 'startup' is " + value); + }).catch((err) => { + console.info("Failed to get the value of 'startup'. Cause: " + err); + }) }).catch((err) => { console.info("Failed to get the preferences.") }); @@ -139,24 +161,24 @@ Use the following APIs to delete a **Preferences** instance or data file. Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. ```js - var observer = function (key) { - console.info("The key" + key + " changed."); - } - preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { - if (err) { - console.info("Failed to put the value of 'startup'. Cause: " + err); - return; - } + var observer = function (key) { + console.info("The key" + key + " changed."); + } + preferences.on('change', observer); + preferences.put('startup', 'auto', function (err) { + if (err) { + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; + } console.info("Put the value of 'startup' successfully."); - preferences.flush(function (err) { - if (err) { - console.info("Failed to flush data. Cause: " + err); - return; - } + preferences.flush(function (err) { + if (err) { + console.info("Failed to flush data. Cause: " + err); + return; + } console.info("Flushed data successfully."); // The observer will be called. - }) - }) + }) + }) ``` 7. Delete the specified file. @@ -164,10 +186,10 @@ Use the following APIs to delete a **Preferences** instance or data file. Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored. ```js - let proDelete = data_preferences.deletePreferences(context, 'mystore'); - proDelete.then(() => { + let proDelete = data_preferences.deletePreferences(context, 'mystore'); + proDelete.then(() => { console.info("Deleted data successfully."); - }).catch((err) => { + }).catch((err) => { console.info("Failed to delete data. Cause: " + err); - }) + }) ``` diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index f6c7395339d66cb1c79bf71d424c15072f77f1b6..a4acbd9a7b47dca4332c7f6a881939b1928abd78 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -30,9 +30,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th **Table 2** API for inserting data + | Class | API | Description | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStore | insert(table:string,values:ValuesBucket):Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| + | RdbStore | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| - **Updating Data** @@ -40,9 +41,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th **Table 3** API for updating data - | Class | API | Description | + + | Class | API | Description | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStore | update(values:ValuesBucket,predicates:RdbPredicates):Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data.
Return value: number of rows updated. | + | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.
the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data.| - **Deleting Data** @@ -50,11 +52,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th **Table 4** API for deleting data - | Class | API | Description | - | -------- | ------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStore | delete(predicates:RdbPredicates):Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
- **predicates**: conditions for deleting data.
Return value: number of rows updated. | - - + + | Class | API | Description | + | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | delete(predicates: RdbPredicates): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return
the number of rows updated.
- **predicates**: conditions for deleting data.| - **Querying Data** @@ -65,10 +66,11 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th **Table 5** APIs for querying data + | Class | API | Description | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | - | RdbStore | query(predicates:RdbPredicates,columns?:Array<string>):Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| - | RdbStore | querySql(sql:string,bindArgs?:Array<ValueType>):Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicates** that specifies the query condition.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| ### Using Predicates @@ -81,11 +83,11 @@ The following lists common predicates. For more information about predicates, se | Class | API | Description | | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| -| RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the OR condition.| -| RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the AND condition.| -| RdbPredicates | contains(field:string,value:string):RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| +| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the OR condition.| +| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the AND condition.| +| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| ### Using the Result Set @@ -101,12 +103,12 @@ For details about how to use result set APIs, see [Result Set](../reference/apis | Class | API | Description | | --------- | ---------------------------------------------------- | ------------------------------------------ | -| ResultSet | goToFirstRow():boolean | Moves to the first row of the result set. | -| ResultSet | getString(columnIndex:number):string | Obtains the value in the form of a string based on the specified column and current row. | -| ResultSet | getBlob(columnIndex:number):Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| -| ResultSet | getDouble(columnIndex:number):number | Obtains the value in the form of double based on the specified column and current row. | -| ResultSet | getLong(columnIndex:number):number | Obtains the value in the form of a long integer based on the specified column and current row. | -| ResultSet | close():void | Closes the result set. | +| ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set. | +| ResultSet | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. | +| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| +| ResultSet | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. | +| ResultSet | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. | +| ResultSet | close(): void | Closes the result set. | @@ -164,7 +166,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStore | backup(destName:string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| +| RdbStore | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.| **Restoring an RDB Store** @@ -172,7 +174,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStore | restore(srcName:string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| +| RdbStore | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.| **Transaction** @@ -180,9 +182,9 @@ Table 15 Transaction APIs | Class | API | Description | | -------- | ----------------------- | --------------------------------- | -| RdbStore | beginTransaction():void | Starts the transaction before executing SQL statements.| -| RdbStore | commit():void | Commits the executed SQL statements. | -| RdbStore | rollBack():void | Rolls back the SQL statements that have been executed. | +| RdbStore | beginTransaction(): void | Starts the transaction before executing SQL statements.| +| RdbStore | commit(): void | Commits the executed SQL statements. | +| RdbStore | rollBack(): void | Rolls back the SQL statements that have been executed. | ## How to Develop @@ -200,10 +202,10 @@ Table 15 Transaction APIs import data_rdb from '@ohos.data.rdb' const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; - const STORE_CONFIG = {name: "rdbstore.db"} + const STORE_CONFIG = { name: "rdbstore.db" } data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { - rdbStore.executeSql(CREATE_TABLE_TEST) - console.info('create table done.') + rdbStore.executeSql(CREATE_TABLE_TEST) + console.info('create table done.') }) ``` @@ -217,7 +219,7 @@ Table 15 Transaction APIs ```js var u8 = new Uint8Array([1, 2, 3]) - const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8} + const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 } let insertPromise = rdbStore.insert("test", valueBucket) ``` @@ -316,6 +318,7 @@ Table 15 Transaction APIs console.log('device=' + device[i] + 'data changed') } } + try { rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) } catch (err) { @@ -366,9 +369,7 @@ Table 15 Transaction APIs (1) Back up the current RDB store. - (2) Restore the RDB store using the backup file. - - The sample code is as follows: + The sample code is as follows: ```js let promiseBackup = rdbStore.backup("dbBackup.db") @@ -378,6 +379,10 @@ Table 15 Transaction APIs console.info('Backup failed, err: ' + err) }) ``` + (2) Restore the RDB store using the backup file. + + The sample code is as follows: + ```js let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(() => { @@ -386,4 +391,3 @@ Table 15 Transaction APIs console.info('Restore failed, err: ' + err) }) ``` - diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md b/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md index fc2a79e0990457a483c7dc75d3ab1fd88c55f126..69fca5fb8177eddc65ddfc0ffade70350446a8a1 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-overview.md @@ -7,21 +7,21 @@ With device usage statistics APIs, you can have a better understanding of the ap Currently you can have access to statistics on the application usage, and the notification and system usage statistics feature will be available for use in later versions. - **The application usage statistics is updated**: -1. Every 30 minutes -2. Upon system time change -3. Upon start of a new day + 1. Every 30 minutes + 2. Upon system time change + 3. Upon start of a new day - **The application usage statistics can include the following**: -1. Events of all applications based on the specified start time and end time -2. Application usage duration statistics based on the specified start time and end time -3. Events of the current application based on the specified start time and end time -4. Application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually) -5. Priority group of the current invoker application -6. Whether a specific application is in the idle state -7. Number of FA usage records specified by **maxNum**, sorted by time (most recent first). If **maxNum** is not specified, the default value **1000** will be used. -8. Number of notifications from applications based on the specified start time and end time -9. Statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time -10. Priority group of the invoker application or a specified application + 1. Events of all applications based on the specified start time and end time + 2. Application usage duration statistics based on the specified start time and end time + 3. Events of the current application based on the specified start time and end time + 4. Application usage duration statistics in the specified time frame at the specified interval (daily, weekly, monthly, or annually) + 5. Priority group of the current invoker application + 6. Whether a specific application is in the idle state + 7. Number of FA usage records specified by **maxNum**, sorted by time (most recent first). If **maxNum** is not specified, the default value **1000** will be used. + 8. Number of notifications from applications based on the specified start time and end time + 9. Statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time + 10. Priority group of the invoker application or a specified application - **The setters can be used to:** @@ -35,6 +35,6 @@ Currently you can have access to statistics on the application usage, and the no Deregister the callback for application group changes. -### Required Permissions +## Required Permissions - Before calling the following system APIs, you need to apply for the **ohos.permission.BUNDLE_ACTIVE_INFO** permission: **queryBundleActiveStates**, **queryBundleStateInfos**, **queryBundleStateInfoByInterval**, **queryBundleActiveEventStates**, **queryAppNotificationNumber**, **queryAppUsagePriorityGroup(bundleName?)**, **setBundleGroup**, **registerGroupCallBack**, and **unRegisterGroupCallBack**. - This permission is not required for calling third-party APIs: **queryCurrentBundleActiveStates**, **queryAppUsagePriorityGroup()**, and **isIdleState**. diff --git a/en/application-dev/device/vibrator-guidelines.md b/en/application-dev/device/vibrator-guidelines.md index 4f49e7996188a7bc668e23fc2a21a1a29ec6e562..97f9f5933b55c9a1b57b5555db5812b6576a262a 100644 --- a/en/application-dev/device/vibrator-guidelines.md +++ b/en/application-dev/device/vibrator-guidelines.md @@ -16,7 +16,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md | ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback<void>): void | Triggers vibration with the specified duration. This API uses a callback to return the result. | | ohos.vibrator | vibrate(effectId: EffectId): Promise<void> | Triggers vibration with the specified effect. This API uses a promise to return the result. | | ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void | Triggers vibration with the specified effect. This API uses a callback to return the result.| -| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void> | Stops vibration. This API uses a promise to return the result. | +| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise<void>| Stops vibration. This API uses a promise to return the result. | | ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void | Stops vibration. This API uses a callback to return the result. | @@ -55,7 +55,7 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ], "when": "inuse" } - }, + } ] ``` diff --git a/en/application-dev/device/vibrator-overview.md b/en/application-dev/device/vibrator-overview.md index 889f6b823cc0bbff99cd9bc9cbb2dde641766420..62e0d0d7b99e8bc4eaf5c38b4fc3006a19264df2 100644 --- a/en/application-dev/device/vibrator-overview.md +++ b/en/application-dev/device/vibrator-overview.md @@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ## Constraints -When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The sensitivity level of this permission is **system_grant**. +When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The authorization mode of this permission is **system_grant**. diff --git a/en/application-dev/faqs/Readme-EN.md b/en/application-dev/faqs/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..b87a565b6da485ea85add166accd20f25cbb686c --- /dev/null +++ b/en/application-dev/faqs/Readme-EN.md @@ -0,0 +1,13 @@ +# FAQs + +- [Ability Framework Development](faqs-ability.md) +- [ArkUI (JavaScript) Development](faqs-ui-js.md) +- [ArkUI (eTS) Development](faqs-ui-ets.md) +- [Graphics and Image Development](faqs-graphics.md) +- [File Management Development](faqs-file-management.md) +- [Data Management Development](faqs-data-management.md) +- [Device Management Development](faqs-device-management.md) +- [Native API Usage](faqs-native.md) +- [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) +- [Development Board](faqs-development-board.md) + diff --git a/en/application-dev/faqs/faqs-ability.md b/en/application-dev/faqs/faqs-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..0cabbba71815d043e29f9c840c8ce7589af76dad --- /dev/null +++ b/en/application-dev/faqs/faqs-ability.md @@ -0,0 +1,60 @@ +# Ability Framework Development + +## Is a guide similar to the Data ability development in the FA model available for the stage model? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +A guide is available for the **DataShareExtensionAbility** class in the stage model, which provides APIs for sharing data with other applications and managing the data. + +Reference: [DataShare Development](../database/database-datashare-guidelines.md) + +## What should I do if the UI does not respond when an ability is started? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +1. If the ability is started using **startAbility**, check whether the **abilityName** field in **want** uses the bundle name as the prefix. If yes, delete the bundle name. + +2. Make sure the ability's home page file configured by **onWindowStageCreate** in the **MainAbility.ts** file is defined in the **main_pages.json** file. + +3. You are advised to use the SDK and OpenHarmony SDK versions released on the same day. + +Reference: [Release Testing Version](https://gitee.com/openharmony-sig/oh-inner-release-management/blob/master/Release-Testing-Version.md) + +## How do I prevent "this" in a method from changing to "undefined" when the method is called? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +Method 1: Add **.bind(this)** when calling the method. + +Method 2: Use the arrow function. + +## What should I do when the message "must have required property 'startWindowIcon'" is displayed? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +Configure the **startWindowIcon** attribute under **abilities** in the **module.json5** file. + +Reference: [Application Package Structure Configuration File](../quick-start/stage-structure.md) + + Example: + +``` +{ + "module": { + // Do something. + "abilities": [{ + // Do something. + "startWindowIcon": "$media:space", + "startWindowBackground": "$color:white", + }] + } +} +``` + +## How do I obtain a notification when the device orientation changes? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +Implement the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the orientation and density) change. + +Reference: [Ability Development](../ability/stage-ability.md) diff --git a/en/application-dev/faqs/faqs-data-management.md b/en/application-dev/faqs/faqs-data-management.md new file mode 100644 index 0000000000000000000000000000000000000000..839514879b8198273bc86680614b6b2054f662e2 --- /dev/null +++ b/en/application-dev/faqs/faqs-data-management.md @@ -0,0 +1,24 @@ +# Device Management Development + + + +## How Do I Save PixelMap data to a database? + +Applicable to: OpenHarmony SDK 3.2.3.5 + +You can convert a **PixelMap** into a **ArrayBuffer** and save the **ArrayBuffer** to your database. + +Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1) + +## How Do I Obtain RDB Store Files? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +Run the hdc_std command to copy the .db, .db-shm, and .db-wal files from **/data/app/el2/100/database/Bundle name/entry/db/**, and then use the SQLite tool to open the files. + +Example: + + +``` + hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db +``` diff --git a/en/application-dev/faqs/faqs-development-board.md b/en/application-dev/faqs/faqs-development-board.md new file mode 100644 index 0000000000000000000000000000000000000000..4766d4f5271dec2e5ec937477cf1ce1b7946eef6 --- /dev/null +++ b/en/application-dev/faqs/faqs-development-board.md @@ -0,0 +1,52 @@ +# Development Board + + + +## How do I take screenshots on a development board? + +Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 + +- Method 1: Click the screenshot button in the Control Panel from the development board UI. The screenshot is displayed in Gallery. + +- Method 2: Run the screenshot script. Connect to the development board to a computer running Windows. Create a text file on the computer, copy the following script content to the file, change the file name extension to **.bat** (the HDC environment variables must be configured in advance), and click **Run**. The screenshot is saved to the same directory as the **.bat** script file. + Example: + + + ``` + set filepath=/data/%date:~0,4%%date:~5,2%%date:~8,2%%time:~1,1%%time:~3,2%%time:~6,2%.png + echo %filepath% + : pause + hdc_std shell snapshot_display -f %filepath% + : pause + hdc_std file recv %filepath% . + : pause + ``` + +## How do I adjust Previewer in DevEco Studio so that the preview looks the same as what's displayed on a real RK3568 development board? + +Applicable to: DevEco Studio 3.0.0.991 + +1. Create a profile in Previewer. + + ![en-us_image_0000001361254285](figures/en-us_image_0000001361254285.png) +2. Set the profile parameters as follows: + + Device type : default + + Resolution: 720\*1280 + + DPI: 240 + +## What should I do if Device Manager incorrectly identifies a development board as FT232R USB UART even when the development board already has a driver installed? + +Possible cause: The USB serial driver of the development version is not installed. + +Solution: Search for **FT232R USB UART**, and download and install the driver. + +## How do I complete authentication when logging in to the development board? + +Applicable to: OpenHarmony SDK 3.2.2.5 + +When connecting to the network that requires authentication, open any web page in the browser to access the authentication page. + +If there is no browser on the development board, you can install the [sample browser application](https://gitee.com/openharmony/app_samples/tree/master/device/Browser). diff --git a/en/application-dev/faqs/faqs-device-management.md b/en/application-dev/faqs/faqs-device-management.md new file mode 100644 index 0000000000000000000000000000000000000000..5bb748f758a4636fb40ae5d7fb741eccfb5306fe --- /dev/null +++ b/en/application-dev/faqs/faqs-device-management.md @@ -0,0 +1,24 @@ +# Device Management Development + + + +## How do I obtain the DPI of a device? + +Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 + +Import the **@ohos.display** module and call the **getDefaultDisplay** API. + +Example: + + +``` +import display from '@ohos.display'; +display.getDefaultDisplay((err, data) => { + if (err.code) { + console.error('Test Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; + } + console.info('Test Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + console.info('Test densityDPI:' + JSON.stringify(data.densityDPI)); +});https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-device-info.md) +``` diff --git a/en/application-dev/faqs/faqs-file-management.md b/en/application-dev/faqs/faqs-file-management.md new file mode 100644 index 0000000000000000000000000000000000000000..1e3740047768d5d5fefa1420659c64da403ad587 --- /dev/null +++ b/en/application-dev/faqs/faqs-file-management.md @@ -0,0 +1,36 @@ +# File Management Development + + + +## What If There is No Return Value or Error Captured After getAlbums Is Called? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbums**, and this permission needs user authorization. For details, see OpenHarmony [Application Permission List](../security/permission-list.md). + +1. Configure the required permission in the **module.json5** file. + + ``` + "requestPermissions": [ + { + "name": "ohos.permission.READ_MEDIA" + } + ] + ``` + +2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded. + + ``` + private requestPermissions() { + let permissionList: Array = [ + "ohos.permission.READ_MEDIA" + ]; + this.context.requestPermissionsFromUser(permissionList) + .then(data => { + console.info(`request permission data result = ${data.authResults}`) + }) + .catch(err => { + console.error(`fail to request permission error:${err}`) + }) + } + ``` diff --git a/en/application-dev/faqs/faqs-graphics.md b/en/application-dev/faqs/faqs-graphics.md new file mode 100644 index 0000000000000000000000000000000000000000..c4e151559b547b2cdb4f8d7cb19b35318203674a --- /dev/null +++ b/en/application-dev/faqs/faqs-graphics.md @@ -0,0 +1,13 @@ +# Graphics and Image Development + +## Why do the isStatusBarLightIcon and isNavigationBarLightIcon attributes not take effect when window.setSystemBarProperties() is called? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +In effect, the **isStatusBarLightIcon** and **isNavigationBarLightIcon** attributes turn the font white when set to **true**. If **statusBarContentColor** is also set in **window.setSystemBarProperties()**, the **isStatusBarLightIcon** attribute does not take effect. Similarly, if **navigationBarContentColor** is set, the **isNavigationBarLightIcon** attribute does not take effect. + +## How do I set the style of the system bar? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +Import the **\@ohos.window** module, and call **window.setSystemBarProperties()**. diff --git a/en/application-dev/faqs/faqs-native.md b/en/application-dev/faqs/faqs-native.md new file mode 100644 index 0000000000000000000000000000000000000000..da00895e4a5b5a532e67f9f709dd84c25abe3205 --- /dev/null +++ b/en/application-dev/faqs/faqs-native.md @@ -0,0 +1,55 @@ +# Native API Usage + +## When a native HAP is running, the error message "Obj is not a valid object" is displayed for the imported namespace. What should I do? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +Check the **abiFilters** parameter value in the **build-profile.json5** file in the root directory of the module (not the root directory of the project). If the device is 32-bit, the value must be **armeabi-v7a**. If the device is 64-bit, the value must be **arm64-v8a**. + +## How do I obtain the value of version in the package.json file of a module in the C++ code developed using native APIs? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +1. In the script file **hvigorfile.js** of Hvigor, use **subModule.getPackageJsonPath** to obtain the location of the **package.json** file in the module. + +2. Use Node.js to read the **version** field in the **package.json** file and write the value to the **buildOption.cppFlags** field in the **build-profile.json5** file. + +Example + + +``` +// Module-level hvigorfile.js +const subModule = require('@ohos/hvigor')(__filename) + +const fs = require("fs-extra") +const path = require("path") + +const packageJsonPath = subModule.getPackageJsonPath() +const buildProfilePath = path.resolve(packageJsonPath, '../build-profile.json5') +const packageJsonData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')) +let buildProfileData = fs.readFileSync(buildProfilePath, 'utf8') +buildProfileData = buildProfileData.replace(/\"cppFlags\"\:(.*)\,/, `"cppFlags": "-D NWEBEX_VERSION=${packageJsonData.version}",`) +fs.writeFileSync(buildProfilePath, buildProfileData, 'utf8') + +const ohosPlugin = require('@ohos/hvigor-ohos-plugin').hapTasks(subModule) // The plug-in executes the C++ build task and reads the build-profile.json5 file. + +module.exports = { + ohos: ohosPlugin +} +``` + + +``` +// Read the hello.cpp file. +#define _NWEBEX_VERSION(v) #v +#define _NWEBEX_VER2STR(v) _NWEBEX_VERSION(v) + +static napi_value Add(napi_env env, napi_callback_info info) +{ + + napi_value fixed_version_value = nullptr; + napi_create_string_utf8(env, _NWEBEX_VER2STR(NWEBEX_VERSION), NAPI_AUTO_LENGTH, &fixed_version_value); + + return fixed_version_value; +} +``` diff --git a/en/application-dev/faqs/faqs-third-party-library.md b/en/application-dev/faqs/faqs-third-party-library.md new file mode 100644 index 0000000000000000000000000000000000000000..323269c5e0a4d8c84e9adbb39c4184bba9a00b5e --- /dev/null +++ b/en/application-dev/faqs/faqs-third-party-library.md @@ -0,0 +1,7 @@ +# Usage of Third- and Fourth-Party Libraries + +## What does the following error message mean : "Stage model module... does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed." + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +The third- and fourth-party libraries are not yet compatible with the stage model of API version 9 and cannot be used. diff --git a/en/application-dev/faqs/faqs-ui-ets.md b/en/application-dev/faqs/faqs-ui-ets.md new file mode 100644 index 0000000000000000000000000000000000000000..fd21421cd95edc2bc838b8401724fae10448d9fd --- /dev/null +++ b/en/application-dev/faqs/faqs-ui-ets.md @@ -0,0 +1,282 @@ +# ArkUI (eTS) Development + + + +## What are the restrictions on using generator functions in TypeScript? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +Below are the restrictions on using generator functions in TypeScript: + +- Expressions can be used only in character strings (in the ${expression} format), **if** conditions, **ForEach** parameters, and component parameters. + +- No expressions should cause any application state variables (including **\@State**, **\@Link**, and **\@Prop**) to change. Otherwise, undefined and potentially unstable framework behavior may occur. + +- The generator function cannot contain local variables. + +None of the above restrictions apply to anonymous function implementations of event handlers (such as **onClick**). + +Negative example: + + +``` +build() { + let a: number = 1 // invalid: variable declaration not allowed + Column() { + Text('Hello ${this.myName.toUpperCase()}') // ok. + ForEach(this.arr.reverse(), ..., ...) // invalid: Array.reverse modifies the @State array varible in place + } + buildSpecial() // invalid: no function calls + Text(this.calcTextValue()) // this function call is ok. +} +``` + +## How do I use router to implement page redirection in the stage model? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +To implement page redirection through **router**, add all redirected-to pages to the pages list in the **main_pages.json** file. + +Page routing APIs in **router** can be invoked only after page rendering is complete. Do not call these APIs in **onInit** or **onReady** when the page is still in the rendering phase. + +## Will a page pushed into the stack through router.push be reclaimed? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +After being pushed to the stack through **router.push**, a page can be reclaimed only when it is popped from the stack through **router.back**. + +## How do I dynamically replace the %s placeholder in a resource file? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +In an application, you can replace the %s placeholder by using the second parameter in `$r('app.string.xx')`, which is used to reference application resources. + +Example: + +``` +build() { + //do something + // The second parameter indicates the referenced string resource, which can be used to replace the %s placeholder. + Text($r('app.string.entry_desc','aaa')) + .fontSize(100) + .fontColor(Color.Black) + //do something +} +``` + +## How do I read an XML file in Resource and convert data in it to the string type? + +Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 + +1. Obtain data in Uint8Array format by calling the **RawFile** API of **resourceManager**. + +2. Convert data in Uint8Array format to the string type by calling the **String.fromCharCode** API. + +Reference: [Resource Management](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-resource-manager.md) + +Example: + + +``` +resourceManager.getRawFile(path, (error, value) => { + if (error != null) { + console.log("error is " + error); + } else { + let rawFile = value; + let xml = String.fromCharCode.apply(null, rawFile) + } +}); +``` + +## How do I convert a Resource object to the string type? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +Use the **resourceManager.getString()** API of the **\@ohos.resourceManager** module. + +Reference: [Resource Management](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-resource-manager.md#getstring) + +## What should I do if the global static variables of a class do not work? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +Objects imported to abilities and pages are packaged into two different closures, that is, two global objects. In this case, a static variable referenced by the abilities is not the same object as that referenced by the pages. Therefore, global variables cannot be defined by defining static variables in the class. You are advised to use AppStorage to manage global variables. + +Reference: [AppStorage](https://docs.openharmony.cn/pages/v3.2Beta/en/application-dev/ui/ts-application-states-appstorage.md/) + +## How do I obtain resources in the stage model? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +The stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This method, however, is not applicable to the FA model. + +Example: + + +``` +const context = getContext(this) as any +context + .resourceManager + .getString($r('app.string.entry_desc').id) + .then(value => { + this.message = value.toString() +}) +``` + +## How do I position a container component to the bottom of the screen? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +Create a **** component, and set the target container at the bottom of the **** component. + +Example: + +``` +build() { + Stack({alignContent : Alignment.Bottom}) { + // The container is at the bottom. + Stack() { + Column() + .width('100%') + .height('100%') + .backgroundColor(Color.Yellow) + } + .width('100%') + .height('10%') + } + .width('100%') + .height('100%') + .backgroundColor('rgba(255,255,255, 0)') +} +``` + +## Can CustomDialog be used in TypeScript files? + +Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 + +No. Currently, **CustomDialog** can be used only on eTS pages. + +Reference: [Custom Dialog Box](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-methods-custom-dialog-box.md) + +## How do I transfer variables in CustomDialog to variables on pages? + +Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 + +Use a custom callback so that when the confirm button in the custom dialog box is clicked, the value of **data** is transferred from the dialog box to the current page. + +Example: + + +``` +// CustomDialog component +@CustomDialog +struct MyDialog { + controller: CustomDialogController + title: string + data: string + cancel: () => void + confirm: (data: string) => void + Button('confirm') + .onClick(() => { + this.controller.close() + this.data = 'test' + this.confirm(this.data) + }).backgroundColor(0xffffff).fontColor(Color.Red) +// Page +@Entry +@Component +struct DialogTest { + dialogController: CustomDialogController = new CustomDialogController({ + builder: MyDialog({ title:'Custom Title',cancel: this.onCancel, + confirm: this.onAccept.bind(this)}), // Bind the custom callback to the button. + cancel: this.existApp, + autoCancel: true + }) + onAccept(data:string) { + console.info('Callback when the second button is clicked ' + data) + } +} +``` + +## What should I do if the \ component cannot be dragged to the bottom after it has a \ component added? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +The **\** component is a scrollable container. By default, it taks up the entire screen height. When any component with a fixed height takes up part of the screen height, you need to explicitly specify **layoutWeight(1)** for the parent container of the **\** component to take up the remaining height instead of the entire screen height. + +## How do I center child components in a grid container? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +By default, child components in a **\** are horizontally aligned to the left. To center them, perform the following steps: + +Nest a **\** component and set it to **justifyContent(FlexAlign.Center)**. For details, see [Grid Layout](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/ui/ui-ts-layout-grid-container.md). + + Example: + +``` +GridContainer({ sizeType: SizeType.SM, columns: 12 }) { + Row() { + Text('1') + .useSizeType({ + sm: { span: 4, offset: 0 }, + }) + .backgroundColor(0x46F2B4) + }.justifyContent(FlexAlign.Center) // Center child components. +} +``` + +## How do I obtain the height of the status bar and navigation bar? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +Before the window content is loaded, enable listening for the **systemAvoidAreaChange** event. + +Example: + +``` +// MainAbility.ts +import window from '@ohos.window'; + +/** + * Set the immersive window and obtain the height of the status bar and navigation bar. + * @param mainWindow Indicates the main window. + */ +async function enterImmersion(mainWindow: window.Window) { + mainWindow.on("systemAvoidAreaChange", (area: window.AvoidArea) => { + AppStorage.SetOrCreate("topHeight", area.topRect.height); + AppStorage.SetOrCreate("bottomHeight", area.bottomRect.height); + }) + await mainWindow.setFullScreen(true) + await mainWindow.setSystemBarEnable(["status", "navigation"]) + await mainWindow.setSystemBarProperties({ + navigationBarColor: "#00000000", + statusBarColor: "#00000000", + navigationBarContentColor: "#FF0000", + statusBarContentColor: "#FF0000" + }) +} +export default class MainAbility extends Ability { + // do something + async onWindowStageCreate(windowStage: window.WindowStage) { + let mainWindow = await windowStage.getMainWindow() + await enterImmersion(mainWindow) + windowStage.loadContent('pages/index') + } + // do something +} +``` + +## How do I execute JavaScript functions in the \ component in eTS code? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +Call the **runJavaScript** API in the **WebController** to asynchronously execute JavaScript scripts. This API uses a callback to return the execution result. Note: **runJavaScript** can only be called after **loadUrl** has been completed. For example, it can be called in **onPageEnd**. + +Reference: [Web](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/arkui-ts/ts-basic-components-web.md) + +## How do I fix misidentification of the pan gesture where container nesting is involved? + +Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 + +Set the **distance** attribute to **1** for the gesture. By default, this attribute is set to **5**. diff --git a/en/application-dev/faqs/faqs-ui-js.md b/en/application-dev/faqs/faqs-ui-js.md new file mode 100644 index 0000000000000000000000000000000000000000..5d39db33199fddf298e66e4bd290999b58d6dddb --- /dev/null +++ b/en/application-dev/faqs/faqs-ui-js.md @@ -0,0 +1,96 @@ +# ArkUI (JavaScript) Development + + + +## How do I convert the fields in an XML file into JavaScript objects? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +To convert fields in an XML file into JavaScript objects, call the **convert** API in the **convertxml** module. + +Example: + + +``` +import convertxml from '@ohos.convertxml'; +// Code snippet +xml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let conv = new convertxml.ConvertXML(); +// Options for conversion. For details, see the reference document. +let options = {trim : false, declarationKey:"_declaration", + instructionKey : "_instruction", attributesKey : "_attributes", + textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", + commentKey : "_comment", parentKey : "_parent", typeKey : "_type", + nameKey : "_name", elementsKey : "_elements"} +let result:any = conv.convert(xml, options) // Convert fields in the XML file into JavaScript objects. +console.log('Test: ' + JSON.stringify(result)) +console.log('Test: ' + result._declaration._attributes.version) // vesion field in XML file +console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // title field in XML file +``` + +Reference: [XML-to-JavaScript Conversion](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-convertxml.md) + +## What are the differences between JavaScript, TypeScript, and eTS? + +Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 + +- JavaScript: a lightweight, weakly-typed programming language, most commonly known as the scripting language for web pages. + +- TypeScript: a superset of JavaScript, with additions of static typing and more object-oriented APIs, enums, etc. + +- eTS: a superset of TypeScript and the programming language for OpenHarmony ArkUI development, which powers UI development through a declarative development paradigm. + +## How do I convert the time to the HHMMSS format? + +Example: + + +``` +export default class DateTimeUtil{ + /** + * HHMMSS + */ + getTime() { + const DATETIME = new Date() + return this.concatTime(DATETIME.getHours(),DATETIME.getMinutes(),DATETIME.getSeconds()) + } + /** + * YYYYMMDD + */ + getDate() { + const DATETIME = new Date() + return this.concatDate(DATETIME.getFullYear(),DATETIME.getMonth()+1,DATETIME.getDate()) + } + /** + * If the date is less than 10, add a leading zero, for example, **07**. + * @param value Indicates the value. + */ + fill(value:number) { + return (value> 9 ? '' : '0') + value + } + /** + * Concatenate year, month, and date fields. + * @param year + * @param month + * @param date + */ + concatDate(year: number, month: number, date: number){ + return `${year}${this.fill(month)}${this.fill(date)}` + } + /** + Concatenate hours, minutes, and seconds fields. + * @param hours + * @param minutes + * @param seconds + */ + concatTime(hours:number,minutes:number,seconds:number){ + return `${this.fill(hours)}${this.fill(minutes)}${this.fill(seconds)}` + } +} +``` diff --git a/en/application-dev/faqs/figures/en-us_image_0000001361254285.png b/en/application-dev/faqs/figures/en-us_image_0000001361254285.png new file mode 100644 index 0000000000000000000000000000000000000000..b44ed1b13a0365a7ffaf3fcff1b00b7555e90159 Binary files /dev/null and b/en/application-dev/faqs/figures/en-us_image_0000001361254285.png differ diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md index 131114d67cb3e1c8519d6d5f3a85b438e5846f6f..5f6e88fc07c88d3e5913058a26887e818a3cc3bc 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -20,4 +20,4 @@ - Camera - [Camera Development](camera.md) - + - [Distributed Camera Development](remote-camera.md) diff --git a/en/application-dev/media/audio-capturer.md b/en/application-dev/media/audio-capturer.md index 64566aba64e213ca8e088ad3a71e036625153187..0815ef31a288440271a27a8f03fb417923a46190 100644 --- a/en/application-dev/media/audio-capturer.md +++ b/en/application-dev/media/audio-capturer.md @@ -8,7 +8,7 @@ You can use the APIs provided by **AudioCapturer** to record raw audio files. During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior. -For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md). +For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md#audiocapturer8). **Figure 1** Audio capturer state diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index 131cacdb3f39ecf6eafb5088525d97d209c9cf18..5227f6cdd1b9ec89818b0d1762c99267ec7eba97 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -18,7 +18,7 @@ You can use audio playback APIs to convert audio data into audible analog signal ## How to Develop -For details about the APIs, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md). +For details about the APIs, see [AudioPlayer in the Media API](../reference/apis/js-apis-media.md#audioplayer). ### Full-Process Scenario diff --git a/en/application-dev/media/audio-recorder.md b/en/application-dev/media/audio-recorder.md index 6fb1c28efa8bd8bd69e16b09cd577ec4bdeff6e6..f465db2b88118b77c9a4e64307170da07c3e8918 100644 --- a/en/application-dev/media/audio-recorder.md +++ b/en/application-dev/media/audio-recorder.md @@ -16,7 +16,7 @@ During audio recording, audio signals are captured, encoded, and saved to files. ## How to Develop -For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md). +For details about the APIs, see [AudioRecorder in the Media API](../reference/apis/js-apis-media.md#audiorecorder). ### Full-Process Scenario @@ -185,4 +185,3 @@ export class AudioRecorderDemo { } } ``` - diff --git a/en/application-dev/media/audio-stream-manager.md b/en/application-dev/media/audio-stream-manager.md index 4f0f88c8fa2c3357e7a8d582642cf4efbb7bf1db..eb89957e9b8793b149c368445f1232bf0ff3b563 100644 --- a/en/application-dev/media/audio-stream-manager.md +++ b/en/application-dev/media/audio-stream-manager.md @@ -12,7 +12,7 @@ For details about the APIs, see [AudioStreamManager](../reference/apis/js-apis-a **Figure 1** Audio stream management invoking relationship -![](figures/zh-ch_image_audio_stream_manager.png) +![](figures/en-us_image_audio_stream_manager.png) ## How to Develop @@ -117,7 +117,7 @@ This API can be used to obtain the unique ID of the audio stream, UID of the aud console.info('Address:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].address); console.info('SampleRates:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]); console.info('ChannelCounts' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]); - console.info('ChannnelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); + console.info('ChannelMask:' + i + ':' + AudioRendererChangeInfo.deviceDescriptors[j].channelMasks); } } } diff --git a/en/application-dev/media/camera.md b/en/application-dev/media/camera.md index 5af14112df2959acbcfc606c9cd2938860ad6f85..06439dd049be835cdf5a96a35e2a2a42012ee6f8 100644 --- a/en/application-dev/media/camera.md +++ b/en/application-dev/media/camera.md @@ -54,7 +54,7 @@ await cameraManager.getCameras((err, cameras) => { cameraArray = cameras }) -for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) { +for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position. console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. @@ -292,7 +292,7 @@ await captureSession.start().then(() => { ##### Switching a Session ```js -// Stop the current session. +// Stop the session. await captureSession.stop((err) => { if (err) { console.error('Failed to stop the session ${err.message}'); @@ -347,8 +347,8 @@ await captureSession.start().then(() => { ```js let settings = { - quality: camera.QualityLevel.QUALITY_LEVEL_HIGH // Set the image quality to high. - rotation: camera.ImageRotation.ROTATION_0, // Set the image rotation angle to 0. + quality: camera.QualityLevel.QUALITY_LEVEL_HIGH, // Set the image quality to high. + rotation: camera.ImageRotation.ROTATION_0 // Set the image rotation angle to 0. } // Use the current photographing settings to take photos. photoOutput.capture(settings, (err) => { @@ -395,7 +395,7 @@ await videoOutput.stop((err) => { #### Releasing Resources ```js -// Stop the current session. +// Stop the session. await captureSession.stop((err) => { if (err) { console.error('Failed to stop the session ${err.message}'); diff --git a/en/application-dev/media/figures/zh-ch_image_audio_stream_manager.png b/en/application-dev/media/figures/en-us_image_audio_stream_manager.png similarity index 100% rename from en/application-dev/media/figures/zh-ch_image_audio_stream_manager.png rename to en/application-dev/media/figures/en-us_image_audio_stream_manager.png diff --git a/en/application-dev/media/remote-camera.md b/en/application-dev/media/remote-camera.md index b63946d6a03a9fbb4d4e6b8e20c3e4920364523b..e35950e73b1993b8a446f75e3007a80e4bbaff19 100644 --- a/en/application-dev/media/remote-camera.md +++ b/en/application-dev/media/remote-camera.md @@ -5,7 +5,7 @@ You can call the APIs provided by the **Camera** module to develop a distributed camera that provides the basic camera functions such as shooting and video recording. ## How to Develop -Connect your calculator to a distributed device. Your calculator will call **getCameras()** to obtain the camera list and traverse the returned camera list to check **ConnctionType** of the **Camera** objects. If **ConnctionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **CameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md). +Connect your calculator to a distributed device. Your calculator will call **getCameras()** to obtain the camera list and traverse the returned camera list to check **ConnectionType** of the **Camera** objects. If **ConnectionType** of a **Camera** object is **CAMERA_CONNECTION_REMOTE**, your calculator will use this object to create a **CameraInput** object. The subsequent call process is the same as that of the local camera development. For details about the local camera development, see [Camera Development](./camera.md). For details about the APIs, see [Camera Management](../reference/apis/js-apis-camera.md). @@ -52,7 +52,7 @@ await cameraManager.getCameras((err, cameras) => { cameraArray = cameras }) -for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) { +for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) { console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position. console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. diff --git a/en/application-dev/media/video-playback.md b/en/application-dev/media/video-playback.md index cfc09db79fc853066e03205010f43c2f63c27ce5..6ee5cf660069294f717c5cac614ed707db9f1a8c 100644 --- a/en/application-dev/media/video-playback.md +++ b/en/application-dev/media/video-playback.md @@ -33,7 +33,7 @@ The table below lists the mainstream playback formats and resolutions. ## How to Develop -For details about the APIs, see [VideoPlayer in the Media API](../reference/apis/js-apis-media.md). +For details about the APIs, see [VideoPlayer in the Media API](../reference/apis/js-apis-media.md#videoplayer8). ### Full-Process Scenario diff --git a/en/application-dev/media/video-recorder.md b/en/application-dev/media/video-recorder.md index 2982675bd37ff683c83f253d23d3a6c71014d66b..62e81cf05c384a7cd1a780c562697be046153d05 100644 --- a/en/application-dev/media/video-recorder.md +++ b/en/application-dev/media/video-recorder.md @@ -14,7 +14,7 @@ During video recording, audio and video signals are captured, encoded, and saved ## How to Develop -For details about the APIs, see [VideoRecorder in the Media API](../reference/apis/js-apis-media.md). +For details about the APIs, see [VideoRecorder in the Media API](../reference/apis/js-apis-media.md#videorecorder9). ### Full-Process Scenario diff --git a/en/application-dev/napi/Readme-EN.md b/en/application-dev/napi/Readme-EN.md index d5297e9374fdf42b1b50fa2ac6e545fe9766971b..280efd8afa5fa845dab0d607ed94b33e2a75e6d3 100644 --- a/en/application-dev/napi/Readme-EN.md +++ b/en/application-dev/napi/Readme-EN.md @@ -2,6 +2,7 @@ - [Using Native APIs in Application Projects](napi-guidelines.md) - [Drawing Development](drawing-guidelines.md) -- [Native Window Development](native-window-guidelines.md) - [Raw File Development](rawfile-guidelines.md) +- [Native Window Development](native-window-guidelines.md) + diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index 86854eb072b19c7ee359dcb70413ce22580cb8f7..f471f4a6eed7d3eb2c96dab8cae4cb7480a13616 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -89,7 +89,7 @@ Register four synchronous APIs (`getSync`, `setSync`, `removeSync`, and`clearSyn /*********************************************** * Module export and register ***********************************************/ -static napi_value StorgeExport(napi_env env, napi_value exports) +static napi_value StorageExport(napi_env env, napi_value exports) { napi_property_descriptor desc[] = { DECLARE_NAPI_FUNCTION("get", JSStorageGet), @@ -110,7 +110,7 @@ static napi_value StorgeExport(napi_env env, napi_value exports) static napi_module storage_module = {.nm_version = 1, .nm_flags = 0, .nm_filename = nullptr, - .nm_register_func = StorgeExport, + .nm_register_func = StorageExport, .nm_modname = "storage", .nm_priv = ((void*)0), .reserved = {0}}; diff --git a/en/application-dev/notification/notification-guidelines.md b/en/application-dev/notification/notification-guidelines.md index 5630462352d721cb3337bfbe302576dc175e29bd..fb73f274202aafd9ff852201ca2fb8c5116aba50 100644 --- a/en/application-dev/notification/notification-guidelines.md +++ b/en/application-dev/notification/notification-guidelines.md @@ -28,14 +28,14 @@ System applications also support notification-related configuration options, suc ## Available APIs -Certain APIs can be invoked only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide same functions as their counterparts that use a promise. For details about the APIs, see the [API document](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-notification.md). +Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](../reference/apis/js-apis-notification.md). **Table 1** APIs for notification enabling | API | Description | | ------------------------------------------------------------ | ---------------- | -| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback): void | Checks whether notification is enabled.| -| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void | Sets whether to enable notification. | +| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void | Checks whether notification is enabled.| +| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void | Sets whether to enable notification. | If the notification function of an application is disabled, it cannot send notifications. @@ -45,11 +45,11 @@ If the notification function of an application is disabled, it cannot send notif | API | Description | | ------------------------------------------------------------ | ---------------- | -| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback): void | Subscribes to a notification with the subscription information specified.| -| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void | Subscribes to all notifications. | -| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void | Unsubscribes from a notification. | +| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void | Subscribes to a notification with the subscription information specified.| +| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Subscribes to all notifications. | +| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Unsubscribes from a notification. | -The subscription APIs support subscription to all notifications or notifications from specific applications. +The subscription APIs support subscription to all notifications and notifications from specific applications. @@ -69,10 +69,10 @@ The subscription APIs support subscription to all notifications or notifications | API | Description | | ------------------------------------------------------------ | ------------------------ | -| publish(request: NotificationRequest, callback: AsyncCallback): void | Publishes a notification. | -| publish(request: NotificationRequest, userId: number, callback: AsyncCallback): void | Publishes a notification to the specified user. | -| cancel(id: number, label: string, callback: AsyncCallback): void | Cancels a specified notification. | -| cancelAll(callback: AsyncCallback): void; | Cancels all notifications published by the application.| +| publish(request: NotificationRequest, callback: AsyncCallback\): void | Publishes a notification. | +| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void | Publishes a notification to the specified user. | +| cancel(id: number, label: string, callback: AsyncCallback\): void | Cancels a specified notification. | +| cancelAll(callback: AsyncCallback\): void; | Cancels all notifications published by the application.| The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. @@ -136,7 +136,7 @@ var subscriber = { Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature. ```js -Notification.requestEnableNotification() .then((data) => { +Notification.requestEnableNotification().then((data) => { console.info('===>requestEnableNotification success'); }).catch((err) => { console.error('===>requestEnableNotification failed because ' + JSON.stringify(err)); @@ -166,7 +166,7 @@ var notificationRequest = { } // Publish the notification. -Notification.publish(notificationRequest) .then((data) => { +Notification.publish(notificationRequest).then((data) => { console.info('===>publish promise success req.id : ' + notificationRequest.id); }).catch((err) => { console.error('===>publish promise failed because ' + JSON.stringify(err)); @@ -235,7 +235,7 @@ var notificationRequest = { } // Publish the notification. -Notification.publish(notificationRequest) .then((data) => { +Notification.publish(notificationRequest).then((data) => { console.info('===>publish promise success req.id : ' + notificationRequest.id); }).catch((err) => { console.error('===>publish promise failed because ' + JSON.stringify(err)); diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001215066868.png b/en/application-dev/quick-start/figures/en-us_image_0000001215066868.png deleted file mode 100644 index d3afe4570f4a839aaa531dea2b1889f318c81f71..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001215066868.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001215206886.png b/en/application-dev/quick-start/figures/en-us_image_0000001215206886.png deleted file mode 100644 index e90d0dbca27908da2964babcba1bc74876b04991..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001215206886.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001215226858.png b/en/application-dev/quick-start/figures/en-us_image_0000001215226858.png deleted file mode 100644 index e2444e0c8488f6632a098585409352a8ce8c7303..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001215226858.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001215227618.png b/en/application-dev/quick-start/figures/en-us_image_0000001215227618.png deleted file mode 100644 index d3afe4570f4a839aaa531dea2b1889f318c81f71..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001215227618.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001215386842.png b/en/application-dev/quick-start/figures/en-us_image_0000001215386842.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001215386842.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001215388136.png b/en/application-dev/quick-start/figures/en-us_image_0000001215388136.png deleted file mode 100644 index 890e12eee8b4534a2b94206c6b73edc81d1ee3ee..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001215388136.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001215388262.png b/en/application-dev/quick-start/figures/en-us_image_0000001215388262.png deleted file mode 100644 index 890e12eee8b4534a2b94206c6b73edc81d1ee3ee..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001215388262.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001216084724.png b/en/application-dev/quick-start/figures/en-us_image_0000001216084724.png deleted file mode 100644 index a8fac2a024e51aeb0439463dab83f2763fa3fa76..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001216084724.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001216239356.png b/en/application-dev/quick-start/figures/en-us_image_0000001216239356.png deleted file mode 100644 index fbbde9923a131d3ab69257b28cfe33ca2a1040cf..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001216239356.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001216269940.png b/en/application-dev/quick-start/figures/en-us_image_0000001216269940.png deleted file mode 100644 index 0b9e04b55e1f9dfca33d97b6b0b80635f6aa1adf..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001216269940.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001216288558.png b/en/application-dev/quick-start/figures/en-us_image_0000001216288558.png deleted file mode 100644 index 7795d74c5ec4915a1f2d6164e0625e308704528a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001216288558.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001217047316.png b/en/application-dev/quick-start/figures/en-us_image_0000001217047316.png deleted file mode 100644 index 6c1ea01d448434e7cfd94e174474e72b57d3b4cc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001217047316.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001217526428.png b/en/application-dev/quick-start/figures/en-us_image_0000001217526428.png deleted file mode 100644 index 2c026736133d41d80a1b92eb0db230dd6c0a7feb..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001217526428.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001217527892.png b/en/application-dev/quick-start/figures/en-us_image_0000001217527892.png deleted file mode 100644 index 0b9e04b55e1f9dfca33d97b6b0b80635f6aa1adf..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001217527892.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223397122.png b/en/application-dev/quick-start/figures/en-us_image_0000001223397122.png deleted file mode 100644 index 42b475577bcc805372336be8971afa5c69c284bd..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223397122.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223556342.png b/en/application-dev/quick-start/figures/en-us_image_0000001223556342.png deleted file mode 100644 index ab2ae3c740dfee9b303d6319516c9facb3574184..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223556342.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223557290.png b/en/application-dev/quick-start/figures/en-us_image_0000001223557290.png deleted file mode 100644 index 6e093d7a983e03a37143357001eefd57c3df2c3c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223557290.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223558810.png b/en/application-dev/quick-start/figures/en-us_image_0000001223558810.png deleted file mode 100644 index b9c3f899421f61b39480b831a662eebf6530100f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223558810.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223558814.png b/en/application-dev/quick-start/figures/en-us_image_0000001223558814.png deleted file mode 100644 index ab2ae3c740dfee9b303d6319516c9facb3574184..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223558814.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223716826.png b/en/application-dev/quick-start/figures/en-us_image_0000001223716826.png deleted file mode 100644 index 14dc492cb36d22c79d22bea78d0f66508867291e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223716826.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223717294.png b/en/application-dev/quick-start/figures/en-us_image_0000001223717294.png deleted file mode 100644 index 75910aaf0daa22be2c0b56ae94febaa672df7424..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223717294.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223722586.png b/en/application-dev/quick-start/figures/en-us_image_0000001223722586.png deleted file mode 100644 index 8ed9b0d3565e5fbb2f7897bc876369ebae5a8598..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223722586.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223877162.png b/en/application-dev/quick-start/figures/en-us_image_0000001223877162.png deleted file mode 100644 index 02d730cadf10899edd91f94ce4cb8badd3ba821c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223877162.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223877210.png b/en/application-dev/quick-start/figures/en-us_image_0000001223877210.png deleted file mode 100644 index 9ce82237297b06c04113d0368d7145661de0d997..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223877210.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001223882030.png b/en/application-dev/quick-start/figures/en-us_image_0000001223882030.png deleted file mode 100644 index 045487dc8fa30e8f87cd3fdd5c87e8ec17715c94..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001223882030.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233048996.png b/en/application-dev/quick-start/figures/en-us_image_0000001233048996.png deleted file mode 100644 index 6d8b4f343d3744e245a656987a85a6da2c9bb18e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233048996.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233049004.png b/en/application-dev/quick-start/figures/en-us_image_0000001233049004.png deleted file mode 100644 index b34bfa591849f5f0ffd0cee1fc898ef8d2f5a5cd..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233049004.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233049040.png b/en/application-dev/quick-start/figures/en-us_image_0000001233049040.png deleted file mode 100644 index c340326cce920ed6c55965126d38ddd973d9f50a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233049040.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233209020.png b/en/application-dev/quick-start/figures/en-us_image_0000001233209020.png deleted file mode 100644 index 890e12eee8b4534a2b94206c6b73edc81d1ee3ee..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233209020.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233209024.png b/en/application-dev/quick-start/figures/en-us_image_0000001233209024.png deleted file mode 100644 index dd28ccedfa20424aad7e01ee52d9246788b72eb8..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233209024.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233368860.png b/en/application-dev/quick-start/figures/en-us_image_0000001233368860.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233368860.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233368868.png b/en/application-dev/quick-start/figures/en-us_image_0000001233368868.png deleted file mode 100644 index cd1603f14f7a5d30c79613201e85ed240f10a409..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233368868.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233368900.png b/en/application-dev/quick-start/figures/en-us_image_0000001233368900.png deleted file mode 100644 index 890e12eee8b4534a2b94206c6b73edc81d1ee3ee..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233368900.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233528152.png b/en/application-dev/quick-start/figures/en-us_image_0000001233528152.png deleted file mode 100644 index ab2ae3c740dfee9b303d6319516c9facb3574184..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233528152.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233528160.png b/en/application-dev/quick-start/figures/en-us_image_0000001233528160.png deleted file mode 100644 index 6d8b4f343d3744e245a656987a85a6da2c9bb18e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233528160.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001233528192.png b/en/application-dev/quick-start/figures/en-us_image_0000001233528192.png deleted file mode 100644 index dd28ccedfa20424aad7e01ee52d9246788b72eb8..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001233528192.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001259866741.png b/en/application-dev/quick-start/figures/en-us_image_0000001259866741.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001259866741.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001259987441.png b/en/application-dev/quick-start/figures/en-us_image_0000001259987441.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001259987441.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001260106745.png b/en/application-dev/quick-start/figures/en-us_image_0000001260106745.png deleted file mode 100644 index d3afe4570f4a839aaa531dea2b1889f318c81f71..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001260106745.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001260107497.png b/en/application-dev/quick-start/figures/en-us_image_0000001260107497.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001260107497.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001260226691.png b/en/application-dev/quick-start/figures/en-us_image_0000001260226691.png deleted file mode 100644 index 6d8b4f343d3744e245a656987a85a6da2c9bb18e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001260226691.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001260227453.png b/en/application-dev/quick-start/figures/en-us_image_0000001260227453.png deleted file mode 100644 index d3afe4570f4a839aaa531dea2b1889f318c81f71..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001260227453.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001260684127.png b/en/application-dev/quick-start/figures/en-us_image_0000001260684127.png deleted file mode 100644 index 2c026736133d41d80a1b92eb0db230dd6c0a7feb..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001260684127.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001261142799.png b/en/application-dev/quick-start/figures/en-us_image_0000001261142799.png deleted file mode 100644 index 86ff220370fc26319a4a23434d70e2508d8f1b9a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001261142799.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001261809595.png b/en/application-dev/quick-start/figures/en-us_image_0000001261809595.png deleted file mode 100644 index 164371727ee8a351e2c42f4b3ecab9175e088e7c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001261809595.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001261979271.png b/en/application-dev/quick-start/figures/en-us_image_0000001261979271.png deleted file mode 100644 index 12978dc861aaa1f826404d9c6838bb8628381615..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001261979271.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001262127855.png b/en/application-dev/quick-start/figures/en-us_image_0000001262127855.png deleted file mode 100644 index 86ff220370fc26319a4a23434d70e2508d8f1b9a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001262127855.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001262206247.png b/en/application-dev/quick-start/figures/en-us_image_0000001262206247.png deleted file mode 100644 index 6c1ea01d448434e7cfd94e174474e72b57d3b4cc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001262206247.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001262207811.png b/en/application-dev/quick-start/figures/en-us_image_0000001262207811.png deleted file mode 100644 index 6c1ea01d448434e7cfd94e174474e72b57d3b4cc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001262207811.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001262219043.png b/en/application-dev/quick-start/figures/en-us_image_0000001262219043.png deleted file mode 100644 index 12978dc861aaa1f826404d9c6838bb8628381615..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001262219043.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001262339067.png b/en/application-dev/quick-start/figures/en-us_image_0000001262339067.png deleted file mode 100644 index 12978dc861aaa1f826404d9c6838bb8628381615..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001262339067.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001268077317.png b/en/application-dev/quick-start/figures/en-us_image_0000001268077317.png deleted file mode 100644 index 6e093d7a983e03a37143357001eefd57c3df2c3c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001268077317.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001268082945.png b/en/application-dev/quick-start/figures/en-us_image_0000001268082945.png deleted file mode 100644 index 55d41f7eb98b1c80bc5f85ea99be6b73bcdd7c1d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001268082945.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001268198893.png b/en/application-dev/quick-start/figures/en-us_image_0000001268198893.png deleted file mode 100644 index ab2ae3c740dfee9b303d6319516c9facb3574184..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001268198893.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001268283201.png b/en/application-dev/quick-start/figures/en-us_image_0000001268283201.png deleted file mode 100644 index 6e093d7a983e03a37143357001eefd57c3df2c3c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001268283201.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277488985.png b/en/application-dev/quick-start/figures/en-us_image_0000001277488985.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277488985.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277489017.png b/en/application-dev/quick-start/figures/en-us_image_0000001277489017.png deleted file mode 100644 index c659e54584bf8e78543facc3a1b3f821a6a9571f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277489017.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277608813.png b/en/application-dev/quick-start/figures/en-us_image_0000001277608813.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277608813.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277608849.png b/en/application-dev/quick-start/figures/en-us_image_0000001277608849.png deleted file mode 100644 index 12978dc861aaa1f826404d9c6838bb8628381615..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277608849.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277728569.png b/en/application-dev/quick-start/figures/en-us_image_0000001277728569.png deleted file mode 100644 index 4d6994bf5bf8dd05baf7eac6274f56de27fc23b3..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277728569.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277728577.png b/en/application-dev/quick-start/figures/en-us_image_0000001277728577.png deleted file mode 100644 index 6d8b4f343d3744e245a656987a85a6da2c9bb18e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277728577.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277728597.png b/en/application-dev/quick-start/figures/en-us_image_0000001277728597.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277728597.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277728613.png b/en/application-dev/quick-start/figures/en-us_image_0000001277728613.png deleted file mode 100644 index cc3ca5fd7274be67f62b32e531fcbbaf294317c1..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277728613.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277809333.png b/en/application-dev/quick-start/figures/en-us_image_0000001277809333.png deleted file mode 100644 index 64bb2a8edf4720cdb4d4d3b6055baa03c81b0a54..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277809333.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277809337.png b/en/application-dev/quick-start/figures/en-us_image_0000001277809337.png deleted file mode 100644 index 335548669bb32a22f146d76f9ab88527e52f515a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277809337.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001277809373.png b/en/application-dev/quick-start/figures/en-us_image_0000001277809373.png deleted file mode 100644 index 6c1ea01d448434e7cfd94e174474e72b57d3b4cc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001277809373.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png deleted file mode 100644 index 048b8e07817272b759781df104c1dd4526685d61..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655128646.png and /dev/null differ diff --git a/en/application-dev/quick-start/figures/en-us_image_202206250937.png b/en/application-dev/quick-start/figures/en-us_image_202206250937.png deleted file mode 100644 index c4aa65192d174763ee3b6c74e10274978868ac67..0000000000000000000000000000000000000000 Binary files a/en/application-dev/quick-start/figures/en-us_image_202206250937.png and /dev/null differ diff --git a/en/application-dev/quick-start/package-structure.md b/en/application-dev/quick-start/package-structure.md index cae1337dea083ff731be54f0536fa33f6fd64812..076bc9474ba724746938c1a4da837a3679c73d5a 100644 --- a/en/application-dev/quick-start/package-structure.md +++ b/en/application-dev/quick-start/package-structure.md @@ -232,7 +232,6 @@ Table 11 Internal structure of the module tag | distroFilter | Application distribution rules.
AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29. | Object | Yes (initial value: left empty)
Set this attribute when an application has multiple entry modules. | | reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | | commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | -| allowClassMap | Metadata of the HAP file. The value can be **true** or **false**. If the value is **true**, the HAP file uses the Java object proxy mechanism provided by the OpenHarmony framework. | Boolean | No (initial value: **false**) | | entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) | Example of the **module** tag structure: @@ -348,7 +347,7 @@ Table 17 Internal structure of the abilities attribute | Attribute | Description | Data Type | Initial Value Allowed | | ---------------- | ------------------------------------------------------------ | ---------- | -------------------------------------------------------- | | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. Devices running OpenHarmony do not support this attribute.| String | Yes (initial value: left empty) | -| name | Name of the ability. The value is a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.
Note: When you use DevEco Studio to create a project, the configuration of the first ability is generated by default, including the **MainAbility.java** file and the class name **MainAbility** defaulted in the **name** string for the **abilities** attribute in **config.json**. The value of this attribute can be customized if you use other IDE tools. The value can contain a maximum of 127 characters.| String | No | +| name | Name of the ability. The value is a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.
Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created together with the default configuration in the **config.json** file. The value of this attribute can be customized if you use other IDE tools. The value can contain a maximum of 127 characters.| String | No | | description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | | icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String | Yes (initial value: left empty) | | label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | @@ -372,7 +371,7 @@ Table 17 Internal structure of the abilities attribute | supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**) | | formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.
**true**: This ability can provide forms.
**false**: This ability cannot provide forms.| Boolean | Yes (initial value: **false**) | | forms | Details about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | -| srcLanguage | Programming language used to develop the ability. | String | The value can be **java**, **js**, or **ets**. | +| srcLanguage | Programming language used to develop the ability. | String | The value can be **js**, or **ets**. | | srcPath | Path of the JS code and components corresponding to the ability. | String | Yes (initial value: left empty) | | uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider. Devices running OpenHarmony do not support this attribute. For details, see Table 18.| Object | Yes (initial value: left empty) | | startWindowIcon | Index to the icon file of the ability startup page. Example value: **$media:icon**. | String | Yes (initial value: left empty) | @@ -587,12 +586,10 @@ Table 27 Internal structure of the forms attribute | name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | | isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | -| type | Type of the widget. Available values are as follows:
**Java**: indicates a Java-programmed widget.
**JS**: indicates a JavaScript-programmed widget.| String | No | +| type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget.| String | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| | supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | -| landscapeLayouts | Landscape layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No | -| portraitLayouts | Portrait layouts for the grid styles. Values in this array must correspond to the values in the **supportDimensions** array. This field is required only by Java-programmed widgets.| String array| No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | @@ -632,9 +629,9 @@ Example of the **forms** attribute structure: ] }, { - "name": "Form_Java", - "description": "It's Java Form", - "type": "Java", + "name": "Form_JS", + "description": "It's JS Form", + "type": "JS", "colorMode": "auto", "isDefault": false, "updateEnabled": true, diff --git a/en/application-dev/quick-start/start-with-ets-fa.md b/en/application-dev/quick-start/start-with-ets-fa.md index 325f4983f16f0cd48899fb657d3c9e41d2f9c3d8..03ed574bb99bcd65cecf0c6ca4710ab2271db9d3 100644 --- a/en/application-dev/quick-start/start-with-ets-fa.md +++ b/en/application-dev/quick-start/start-with-ets-fa.md @@ -187,7 +187,7 @@ ## Implementing Page Redirection -You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below: +You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. diff --git a/en/application-dev/quick-start/start-with-ets-stage.md b/en/application-dev/quick-start/start-with-ets-stage.md index 7703ff56e9336bb5e648a63eb3e7df470f0d88a5..b6b8cd11b8ba18b59931c1bf0244d4af3d7ec888 100644 --- a/en/application-dev/quick-start/start-with-ets-stage.md +++ b/en/application-dev/quick-start/start-with-ets-stage.md @@ -185,7 +185,7 @@ ## Implementing Page Redirection -You can implement page redirection through the page router, which finds the target page based on the page URL. Import the **router** module and then perform the steps below: +You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. @@ -285,7 +285,7 @@ You can implement page redirection through the page router, which finds the targ 1. Connect the development board running the OpenHarmony standard system to the computer. -2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signaure**. Wait until the automatic signing is complete, and click **OK**. See the following figure. +2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure. ![06](figures/06.png) diff --git a/en/application-dev/quick-start/start-with-js-fa.md b/en/application-dev/quick-start/start-with-js-fa.md index dbd2931eba6f6de6c6d23777a5c761dc505dc7c4..03b037aeb529dcf7d481caf56db32625943c055b 100644 --- a/en/application-dev/quick-start/start-with-js-fa.md +++ b/en/application-dev/quick-start/start-with-js-fa.md @@ -181,7 +181,7 @@ ## Implementing Page Redirection -You can implement page redirection through the [page router](../ui/ui-js-building-ui-routes.md), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: +You can implement page redirection through the [page router](../reference/apis/js-apis-router.md#routerpush), which finds the target page based on the page URL. Import the **router** module and then perform the steps below: 1. Implement redirection from the first page to the second page. diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index fe77dc5347f70c5cbcef596dbd8c3b57df83d9cc..e580b6bbef7bd71869de1da19a3a3d5c4757370d 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -146,6 +146,7 @@ - [@ohos.privacyManager](js-apis-privacyManager.md) - [@ohos.security.huks ](js-apis-huks.md) - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) + - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) - [@system.cipher](js-apis-system-cipher.md) - Data Management diff --git a/en/application-dev/reference/apis/development-intro.md b/en/application-dev/reference/apis/development-intro.md index 8528a10ab6f4ba3dd14186079357ce28e650ee6a..f1cc73aa8437b7cb20bf5fe16b284da2a788d570 100644 --- a/en/application-dev/reference/apis/development-intro.md +++ b/en/application-dev/reference/apis/development-intro.md @@ -26,6 +26,12 @@ A description regarding system APIs will be provided in the document. - If all the APIs of a module are system APIs, the following description is provided at the beginning of the reference document: "All the APIs of this module are system APIs." - If a specific API of a module is a system API, the following description is provided individually for the API: "This is a system API." +Non-system applications are applications whose Ability Privilege Level (APL) is **normal**. The default application level is **normal**. + +For details about the APL and how to declare the APL of an application higher than **normal**, see [Access Control Overview - App APLs](../../security/accesstoken-overview.md#app-apls). + +The public SDK, which does not include system APIs, is provided as standard in DevEco Studio. To use system APIs, switch to the full SDK. For details on the operation, see [Guide to Switching to Full SDK](../../quick-start/full-sdk-switch-guide.md). + ## Permission Description By default, applications can access limited system resources. However, in some cases, an application needs to access excess data (including personal data) and functions of the system or another application to implement extended functions. For details, see [Access Control Overview](../../security/accesstoken-overview.md). diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index cd4e27214b3617970071bcfb8e4e5b1c76bc2a2c..9aab0179f06478fef211871d29e90daa33cf5609 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -5,8 +5,8 @@ The **AbilityContext** module, inherited from **Context**, implements the contex This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a dialog box. > **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The 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 @@ -78,7 +78,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - + ```js var want = { "deviceId": "", @@ -127,7 +127,7 @@ Starts an ability. This API uses a promise to return the result. windowMode: 0, }; this.context.startAbility(want, options) - .then((data) => { + .then(() => { console.log('Operation successful.') }).catch((error) => { console.log('Operation failed.'); @@ -407,8 +407,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re "abilityName": "MainAbility" }; this.context.startServiceExtensionAbility(want) - .then((data) => { - console.log('---------- startServiceExtensionAbility success, data: -----------', data); + .then(() => { + console.log('---------- startServiceExtensionAbility success -----------'); }) .catch((err) => { console.log('---------- startServiceExtensionAbility fail, err: -----------', err); @@ -477,8 +477,8 @@ Starts a new Service Extension ability with the account ID specified. This API u }; var accountId = 100; this.context.startServiceExtensionAbilityWithAccount(want,accountId) - .then((data) => { - console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data); + .then(() => { + console.log('---------- startServiceExtensionAbilityWithAccount success -----------'); }) .catch((err) => { console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); @@ -539,8 +539,8 @@ Stops a Service Extension ability in the same application. This API uses a promi "abilityName": "MainAbility" }; this.context.stopServiceExtensionAbility(want) - .then((data) => { - console.log('---------- stopServiceExtensionAbility success, data: -----------', data); + .then(() => { + console.log('---------- stopServiceExtensionAbility success -----------'); }) .catch((err) => { console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); @@ -610,8 +610,8 @@ Stops a Service Extension ability in the same application with the account ID sp }; var accountId = 100; this.context.stopServiceExtensionAbilityWithAccount(want,accountId) - .then((data) => { - console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data); + .then(() => { + console.log('---------- stopServiceExtensionAbilityWithAccount success -----------'); }) .catch((err) => { console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); @@ -658,8 +658,8 @@ Terminates this ability. This API uses a promise to return the result. **Example** ```js - this.context.terminateSelf().then((data) => { - console.log('success:' + JSON.stringify(data)); + this.context.terminateSelf().then(() => { + console.log('success'); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); @@ -848,11 +848,11 @@ Disconnects a connection. This API uses a promise to return the result. | Promise\ | Promise used to return the result.| **Example** - + ```js var connectionNumber = 0; - this.context.disconnectAbility(connectionNumber).then((data) => { - console.log('disconnectAbility success, data: ', data); + this.context.disconnectAbility(connectionNumber).then(() => { + console.log('disconnectAbility success'); }).catch((err) => { console.log('disconnectAbility fail, err: ', err); }); @@ -888,7 +888,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r startAbilityByCall(want: Want): Promise<Caller>; -Starts an ability in the foreground or background and obtains the caller interface for communication with the ability. +Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -905,11 +905,11 @@ Starts an ability in the foreground or background and obtains the caller interfa | Promise<Caller> | Promise used to return the caller object to communicate with.| **Example** - + ```js let caller = undefined; - // Start an ability in the background without passing parameters. + // Start an ability in the background by not passing parameters. var wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", @@ -1050,8 +1050,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu windowMode: 0, }; this.context.startAbilityWithAccount(want, accountId, options) - .then((data) => { - console.log('---------- startAbilityWithAccount success, data: -----------', data); + .then(() => { + console.log('---------- startAbilityWithAccount success -----------'); }) .catch((err) => { console.log('---------- startAbilityWithAccount fail, err: -----------', err); @@ -1074,13 +1074,13 @@ Requests permissions from the user by displaying a dialog box. This API uses an | callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result.| **Example** - + ```js var permissions=['com.example.permission'] this.context.requestPermissionsFromUser(permissions,(result) => { console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); }); - + ``` @@ -1105,7 +1105,7 @@ Requests permissions from the user by displaying a dialog box. This API uses a p | Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result.| **Example** - + ```js var permissions=['com.example.permission'] this.context.requestPermissionsFromUser(permissions).then((data) => { @@ -1133,7 +1133,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - + ```js this.context.setMissionLabel("test",(result) => { console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); @@ -1162,10 +1162,10 @@ Sets a label for this ability in the mission. This API uses a promise to return | Promise<void> | Promise used to return the result.| **Example** - + ```js - this.context.setMissionLabel("test").then((data) => { - console.log('success:' + JSON.stringify(data)); + this.context.setMissionLabel("test").then(() => { + console.log('success'); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); @@ -1188,7 +1188,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** - + ```js import image from '@ohos.multimedia.image' var imagePixelMap; @@ -1235,7 +1235,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return | Promise<void> | Promise used to return the result.| **Example** - + ```js import image from '@ohos.multimedia.image' var imagePixelMap; @@ -1254,8 +1254,8 @@ Sets an icon for this ability in the mission. This API uses a promise to return console.log('--------- createPixelMap fail, err: ---------', err) }); this.context.setMissionIcon(imagePixelMap) - .then((data) => { - console.log('-------------- setMissionIcon success, data: -------------', data); + .then(() => { + console.log('-------------- setMissionIcon success -------------'); }) .catch((err) => { console.log('-------------- setMissionIcon fail, err: -------------', err); diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index 545da5d468feefce2440a356812356e6206e11e3..619ed387b6338fa06a064b3848a3491ee7ea08c9 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -32,7 +32,7 @@ Enumerates the action constants of the **Want** object. | ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | | ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | | ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. | -| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for openning a contact or picture. | +| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for opening a contact or picture. | | ACTION_IMAGE_CAPTURE8+ | ohos.want.action.imageCapture | Action of launching the UI for photographing. | | ACTION_VIDEO_CAPTURE8+ | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | | ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. | diff --git a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md b/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md index f8323a391ace1995486ff721666805a7bbb9b658..6a592ba663ec3723884fd0f44fef90a733230fa7 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md @@ -9,10 +9,18 @@ You can use the APIs of this module to configure the concerned information, obta > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. -## Modules to Import +## Usage + +Before using the **AccessibilityExtensionContext** module, you must define a child class that inherits from **AccessibilityExtensionAbility**. ```js import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' +class MainAbility extends AccessibilityExtensionAbility { + onConnect(): void { + console.log("AxExtensionAbility onConnect"); + let axContext = this.context; + } +} ``` ## FocusDirection @@ -203,9 +211,9 @@ this.context.getWindows().then(windows => { }) ``` -## AccessibilityExtensionContext.gestureInject +## AccessibilityExtensionContext.injectGesture -gestureInject(gesturePath: GesturePath, listener: Callback\): Promise\): Promise\- **'accessibilityStateChange'** means to listen for enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| - | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| + | 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.| - **Example** @@ -456,13 +460,15 @@ Enables listening for the accessibility application or touch guide mode status c off(type: 'accessibilityStateChange ' | 'touchGuideStateChange', callback?: Callback<boolean>): void -Disables listening for the accessibility application or touch guide mode status changes. +Disables listening for the enabled status changes of the accessibility application or touch guide mode. + + - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | No| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| + | 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.| - **Example** diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index ef0e355c63726bc167dac72801adfdce030827f3..44f96b01b333ed9ad5e1258b0173734c0c7869d7 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 +# App Account Management The **appAccount** module provides APIs for app account management. You can use the APIs to add, delete, query, modify, and authorize app accounts, write data to disks, and synchronize data. @@ -154,7 +154,7 @@ Implicitly adds an app account based on the specified account owner, authenticat } const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccountImplicitly("LiSi", "readAge", {}, { + appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -321,7 +321,8 @@ Enables an app account to access an app with the given bundle name. This API use **Example** ```js - app_account_instance.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { console.log('enableAppAccess Success'); }).catch((err) => { console.log("enableAppAccess err: " + JSON.stringify(err)); @@ -334,7 +335,7 @@ checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): Checks whether an app account allows app data synchronization. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Account.AppAccount @@ -361,7 +362,7 @@ checkAppAccountSyncEnable(name: string): Promise<boolean> Checks whether an app account allows app data synchronization. This API uses a promise to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Account.AppAccount @@ -510,7 +511,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback Sets whether to enable app data synchronization for an app account. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Account.AppAccount @@ -537,7 +538,7 @@ setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> Sets whether to enable app data synchronization for an app account. This API uses a promise to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.Account.AppAccount @@ -585,7 +586,8 @@ Sets data to be associated with an app account. This API uses an asynchronous ca **Example** ```js - app_account_instance.setAssociatedData("ZhangSan", "k001", "v001", (err) => { + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { console.log("setAssociatedData err: " + JSON.stringify(err)); }); ``` @@ -795,6 +797,35 @@ Obtains data associated with an app account. This API uses a promise to return t }); ``` +### getAssociatedDataSync9+ + +getAssociatedDataSync(name: string, key: string): string; + +Obtains the data associated with this app account. This API returns the result synchronously. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to obtain.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------- | +| string | Data obtained.| + +**Example** + + ```js + const appAccountManager = account_appAccount.createAppAccountManager(); + var backData = appAccountManager.getAssociatedDataSync("ZhangSan", "k001"); + console.info("getAssociatedDataSync backData:" + JSON.stringify(backData)); + ``` + ### getAllAccessibleAccounts getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void @@ -868,7 +899,7 @@ Obtains information about all app accounts of the specified app. This API uses a **Example** ```js - const appAccountManager = account.createAppAccountManager(); + const appAccountManager = account_appAccount.createAppAccountManager(); const selfBundle = "com.example.actsgetallaaccounts"; appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ console.debug("getAllAccounts err:" + JSON.stringify(err)); @@ -929,7 +960,7 @@ Subscribes to the account change events of the specified account owners. This AP **Example** ```js - const appAccountManager = account.createAppAccountManager(); + const appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ console.debug("receive change data:" + JSON.stringify(data)); } @@ -959,7 +990,7 @@ Unsubscribes from the account change events. This API uses an asynchronous callb **Example** ```js - const appAccountManager = account.createAppAccountManager(); + const appAccountManager = account_appAccount.createAppAccountManager(); function changeOnCallback(data){ console.debug("receive change data:" + JSON.stringify(data)); appAccountManager.off('change', function(){ @@ -1010,7 +1041,7 @@ Authenticates an app account to obtain an Open Authorization (OAuth) token. This } const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "readAge", {}, { + appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback }); @@ -1037,7 +1068,7 @@ Obtains the OAuth token of an app account based on the specified authentication ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", (err, data) => { + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthToken err: ' + JSON.stringify(err)); console.log('getOAuthToken token: ' + data); }); @@ -1069,7 +1100,7 @@ Obtains the OAuth token of an app account based on the specified authentication ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge").then((data) => { + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthToken token: ' + data); }).catch((err) => { console.log("getOAuthToken err: " + JSON.stringify(err)); @@ -1097,7 +1128,7 @@ Sets an OAuth token for an app account. This API uses an asynchronous callback t ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx", (err) => { + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -1128,7 +1159,7 @@ Sets an OAuth token for an app account. This API uses a promise to return the re ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx").then(() => { + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { console.log('setOAuthToken successfully'); }).catch((err) => { console.log('setOAuthToken err: ' + JSON.stringify(err)); @@ -1157,7 +1188,7 @@ Deletes the specified OAuth token for an app account. This API uses an asynchron ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx", (err) => { + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` @@ -1189,7 +1220,7 @@ Deletes the specified OAuth token for an app account. This API uses a promise to ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx").then(() => { + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { console.log('deleteOAuthToken successfully'); }).catch((err) => { console.log("deleteOAuthToken err: " + JSON.stringify(err)); @@ -1218,7 +1249,7 @@ Sets the visibility of an OAuth token to an app. This API uses an asynchronous c ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err) => { + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` @@ -1250,7 +1281,7 @@ Sets the visibility of an OAuth token to an app. This API uses a promise to retu ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then(() => { + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -1278,7 +1309,7 @@ Checks whether an OAuth token is visible to an app. This API uses an asynchronou ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err, data) => { + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); console.log('checkOAuthTokenVisibility isVisible: ' + data); }); @@ -1310,7 +1341,7 @@ Checks whether an OAuth token is visible to an app. This API uses a promise to r ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then((data) => { + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err) => { console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); @@ -1369,7 +1400,7 @@ Obtains all OAuth tokens visible to the caller for an app account. This API uses ```js const appAccountManager = account_appAccount.createAppAccountManager(); appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { - console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }).catch((err) => { console.log("getAllOAuthTokens err: " + JSON.stringify(err)); }); @@ -1395,7 +1426,7 @@ Obtains a list of authorized OAuth tokens of an app account. This API uses an as ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge", (err, data) => { + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { console.log('getOAuthList err: ' + JSON.stringify(err)); console.log('getOAuthList data: ' + JSON.stringify(data)); }); @@ -1426,7 +1457,7 @@ Obtains a list of authorized OAuth tokens of an app account. This API uses a pro ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge").then((data) => { + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err) => { console.log("getOAuthList err: " + JSON.stringify(err)); @@ -1462,9 +1493,9 @@ Obtains the authenticator callback for an authentication session. This API uses } var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); }); }); ``` @@ -1492,15 +1523,17 @@ Obtains the authenticator callback for an authentication session. This API uses **Example** ```js + import featureAbility from '@ohos.ability.featureAbility'; + const appAccountManager = account_appAccount.createAppAccountManager(); featureAbility.getWant().then((want) => { var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); }); @@ -1578,7 +1611,7 @@ Checks whether an app account is authorized to access an app. This API uses an a | Name | Type | Mandatory | Description | | ---------- | ---------------------------- | ----- | ---------------- | | name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app to access.| +| bundleName | string | Yes | Bundle name of the app to access. | | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Example** @@ -1604,7 +1637,7 @@ Checks whether an app account is authorized to access an app. This API uses a pr | Name | Type | Mandatory | Description | | ---------- | ------ | ----- | ---------------- | | name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app to access.| +| bundleName | string | Yes | Bundle name of the app to access. | **Parameters** @@ -1702,7 +1735,8 @@ Checks whether an app account has specific labels. This API uses an asynchronous ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", (err, data) => { + var labels = ["student"]; + appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels, (err, data) => { console.log('checkAccountLabels: ' + JSON.stringify(data)); console.log("checkAccountLabels err: " + JSON.stringify(err)); }); @@ -1734,7 +1768,8 @@ Checks whether an app account has specific labels. This API uses a promise to re ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo").then((data) => { + var labels = ["student"]; + appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels).then((data) => { console.log('checkAccountLabels: ' + JSON.stringify(data)); }).catch((err) => { console.log("checkAccountLabels err: " + JSON.stringify(err)); @@ -1944,7 +1979,7 @@ Defines app account information. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----------- | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| name | string | Yes | Name of the target app account. | +| name | string | Yes | Name of the app account. | ## OAuthTokenInfo8+ @@ -1967,8 +2002,8 @@ Defines OAuth authenticator information. | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ---------- | | owner | string | Yes | Owner of the authenticator. The value is the bundle name of the app.| -| iconId | string | Yes | ID of the authenticator icon. | -| labelId | string | Yes | ID of the authenticator label. | +| iconId | number | Yes | ID of the authenticator icon. | +| labelId | number | Yes | ID of the authenticator label. | ## SelectAccountsOptions9+ @@ -2082,9 +2117,9 @@ Called to return the result of an authentication request. appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "readAge", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.OnResult(account_appAccount.ResultCode.SUCCESS, result); + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); }).catch((err) => { console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); }); @@ -2137,7 +2172,7 @@ Called to continue to process the request. const appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { - callback.OnRequestContinued(); + callback.onRequestContinued(); }).catch((err) => { console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); }); @@ -2167,7 +2202,7 @@ Implicitly adds an app account based on the specified authentication type and op authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -Authenticates an app account to obtain the OAuth access token. This API uses an asynchronous callback to return the result. +Authenticates an app account to obtain the OAuth token. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -2264,7 +2299,7 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. callback.onResult(account_appAccount.ResultCode.SUCCESS, result); } - verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback) { + verifyCredential(name, options, callback) { callback.onRequestRedirected({ bundleName: "com.example.ohos.accountjsdemo", abilityName: "com.example.ohos.accountjsdemo.VerifyAbility", @@ -2274,11 +2309,11 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. }); } - setProperties(options: SetPropertiesOptions, callback: AuthenticatorCallback) { + setProperties(options, callback) { callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); } - checkAccountLabels(name: string, labels: Array, callback: AuthenticatorCallback) { + checkAccountLabels(name, labels, callback) { var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); } diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md index fd15443a5b2ac2b28642a0c89d441cdbee5d6866..b7f2605363e849a8d5531b9ebda7d2277a2fd11c 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -49,6 +49,7 @@ import Want from '@ohos.application.Want'; - Passing a file descriptor (FD) ``` js + import fileio from '@ohos.fileio'; var fd; try { fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); @@ -59,9 +60,9 @@ import Want from '@ohos.application.Want'; "deviceId": "", // An empty deviceId indicates the local device. "bundleName": "com.extreme.test", "abilityName": "MainAbility", - "moduleName": "entry" // moduleName is optional. + "moduleName": "entry", // moduleName is optional. "parameters": { - "keyFd":{"type":"FD", "value":fd} + "keyFd":{"type":"FD", "value":fd} } }; this.context.startAbility(want, (error) => { diff --git a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md index 8a366b1e21bb988c608ba0a5e57251f2bd237d75..3509cdff1bc50c134be76aa4a90742cb3a14f778 100644 --- a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @@ -25,56 +25,25 @@ import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; ## WindowExtensionAbility.onConnect -onConnect(want: Want): rpc.RemoteObject +onConnect(want: Want): void Called when this Window Extension ability is connected to an ability for the first time. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. | - -**Return value** -| Type | Description | -| ----------------------------------------------- | -------------------- | -| [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Proxy of this Window Extension ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.| **Example** ```ts -import rpc from '@ohos.rpc'; - -class StubTest extends rpc.RemoteObject { - constructor(des) { - super(des); - } - onRemoteRequest(code, data, reply, option) { - return true; - } - queryLocalInterface(descriptor) { - return null; - } - getInterfaceDescriptor() { - return ""; - } - sendRequest(code, data, reply, options) { - return null; - } - getCallingPid() { - return 1; - } - getCallingUid() { - return 1; - } - attachLocalInterface(localInterface, descriptor){} -} - export default class MyWindowExtensionAbility extends WindowExtensionAbility { - onConnect(want): rpc.RemoteObject { + onConnect(want) { console.info('WindowExtAbility onConnect ' + want.abilityName); - return new StubTest("test"); } } @@ -88,9 +57,11 @@ Called when this Window Extension ability is disconnected from all connected abi **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. | +| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.| **Example** @@ -105,7 +76,6 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { } ``` - ## WindowExtensionAbility.onWindowReady onWindowReady(window: Window): void @@ -114,6 +84,8 @@ Called when a window is ready. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | window | [Window](js-apis-window.md) | Yes| Current **Window** instance.| @@ -127,7 +99,7 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { onWindowReady(window) { window.loadContent('WindowExtAbility/pages/index1').then(() => { window.getProperties().then((pro) => { - console.log("WindowExtension " + JSON.stringify(pro)); + console.log('WindowExtension ' + JSON.stringify(pro)); }) window.show(); }) diff --git a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md index 7c5ba607718d5d14317a55645627022b78976461..57a313f1f600607c143aaec48205a482221ba355 100644 --- a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -26,7 +26,7 @@ Callback of the common event of a static subscriber. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | event | CommonEventData | Yes| Common event of a static subscriber.| + | event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index f019d61969e28699cc1324a6f8d8af29ba7d60f6..7fa4e76c7a448d1272d1a50b8da71e0303b27762 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -4911,7 +4911,7 @@ audioCapturer.getBufferSize().then((data) => { console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.error(`AudioFrameworkRecLog: getBufferSize: EROOR: ${err}`); + console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); }); audioCapturer.read(bufferSize, true, async(err, buffer) => { if (!err) { diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md new file mode 100644 index 0000000000000000000000000000000000000000..b1c81e2eecd00b5043bb703b574bcc0c06533373 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -0,0 +1,2445 @@ +# Buffer + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +A **Buffer** object represents a fixed-length sequence of bytes. It is used to store binary data. + +You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, and receive or upload files. + +## Modules to Import + +```ts +import buffer from '@ohos.buffer'; +``` + +## Buffer + +### alloc + +alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer + +Allocates and initializes a **Buffer** instance of the specified size. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| +| fill | string \| Buffer \| number | No| Pre-filled value. The default value is **0**.| +| encoding | BufferEncoding | No| Encoding format (valid only when **fill** is a string). The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | Initialized **Buffer** instance.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.alloc(5); +let buf2 = buffer.alloc(5, 'a'); +let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +``` + +### allocUninitializedFromPool + +allocUninitializedFromPool(size: number): Buffer + +Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it. +To initialize the **Buffer** instance, call **fill()**. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | Uninitialized **Buffer** instance.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(10); +buf.fill(0); +``` + +### allocUninitialized + +allocUninitialized(size: number): Buffer + +Allocates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| size | number | Yes|Size of the **Buffer** instance to allocate, in bytes.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | Uninitialized **Buffer** instance.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitialized(10); +buf.fill(0); +``` + +### byteLength + +byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number + +Obtains the number of bytes of a string based on the encoding format. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| string | string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.| +| encoding | BufferEncoding | No| Encoding format. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes of the string.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let str = '\u00bd + \u00bc = \u00be'; +console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8')} bytes`); +// Print: ½ + ¼ = ¾: 9 characters, 12 bytes +``` + +### compare + +compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1 + +Compares two **Buffer** instances. This API is used for sorting **Buffer** instances. + + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| buf1 | Buffer \| Uint8Array | Yes| **Buffer** instance to compare.| +| buf2 | Buffer \| Uint8Array | Yes| **Buffer** instance to compare.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| -1 \| 0 \| 1 | Returns **0** if **buf1** is the same as **buf2**.
Returns **1** if **buf1** comes after **buf2** when sorted.
Returns **-1** if **buf1** comes before **buf2** when sorted.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('1234'); +let buf2 = buffer.from('0123'); +let res = buf1.compare(buf2); + +console.log(Number(res).toString()); +// Print 1 +``` + +### concat + +concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer + +Concatenates an array of **Buffer** instances into a new instance of the specified length. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| list | Buffer[] \| Uint8Array[] | Yes| Array of instances to concatenate.| +| totalLength | number | No| Total length of the new **Buffer** instance, in bytes.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from("1234"); +let buf2 = buffer.from("abcd"); +let buf = buffer.concat([buf1, buf2]); +console.log(buf.toString('hex')); // 3132333461626364 +``` + +### from + +from(array: number[]): Buffer; + +Creates a **Buffer** instance with the specified array. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| array | number[] | Yes| Array to create a **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); +console.log(buf.toString('hex')); // 627566666572 +``` + +### from + +from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer + +Creates a **Buffer** instance that shares memory with the specified array of **Buffer** instances. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| arrayBuffer | ArrayBuffer \| SharedArrayBuffer | Yes| Array of **Buffer** instances, whose memory is to be shared.| +| byteOffset | number | No| Byte offset. The default value is **0**.| +| length | number | No| Length of the **Buffer** instance to create, in bytes. The default value is the length of **arrayBuffer** minus **byteOffset**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance with shared memory.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let ab = new ArrayBuffer(10); +let buf = buffer.from(ab, 0, 2); +``` + +### from + +from(buffer: Buffer | Uint8Array): Buffer + +Creates a **Buffer** instance with the copy of another instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy. | + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('buffer'); +let buf2 = buffer.from(buf1); +``` + +### from + +from(object: Object, offsetOrEncoding: number | string, length: number): Buffer + +Creates a **Buffer** instance based on the specified object. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| object | Object | Yes| Object that supports **Symbol.toPrimitive** or **valueOf()**.| +| offsetOrEncoding | number \| string | No| Byte offset or encoding format.| +| length | number | No| Length of the **Buffer** instance to create.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from(new String('this is a test')); +``` + +### from + +from(string: String, encoding?: BufferEncoding): Buffer + +Creates a **Buffer** instance based on a string in the given encoding format. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| string | String | Yes| String.| +| encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('this is a test'); +let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex'); + +console.log (buf1.toString()); // Print: this is a test +console.log(buf2.toString()); +``` + + +### isBuffer + +isBuffer(obj: Object): boolean + +Checks whether the specified object is a **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| obj | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the object is a **Buffer** instance; returns **false** otherwise.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +buffer.isBuffer(buffer.alloc(10)); // true +buffer.isBuffer(buffer.from('foo')); // true +buffer.isBuffer('a string'); // false +buffer.isBuffer([]); // false +buffer.isBuffer(new Uint8Array(1024)); // false +``` + +### isEncoding + +isEncoding(encoding: string): boolean + +Checks whether the encoding format is supported. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| encoding | string | Yes| Encoding format to check. | + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the encoding format is supported; returns **false** otherwise.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +console.log(buffer.isEncoding('utf-8').toString()); // Print: true +console.log(buffer.isEncoding('hex').toString()); // Print: true +console.log(buffer.isEncoding('utf/8').toString()); // Print: false +console.log(buffer.isEncoding('').toString()); // Print: false +``` + +### compare + +compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1 + +Compares this **Buffer** instance with another instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| target | Buffer \| Uint8Array | Yes| Target **Buffer** instance to compare.| +| targetStart | number | No| Offset to the start of the data to compare in the target **Buffer** instance. The default value is **0**.| +| targetEnd | number | No| Offset to the end of the data to compare in the target **Buffer** instance (not inclusive). The default value is the length of the target **Buffer** instance.| +| sourceStart | number | No| Offset to the start of the data to compare in this **Buffer** instance. The default value is **0**.| +| sourceEnd | number | No| Offset to the end of the data to compare in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); +let buf2 = buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + +console.log(buf1.compare(buf2, 5, 9, 0, 4).toString()); // Print: 0 +console.log(buf1.compare(buf2, 0, 6, 4).toString()); // Print: -1 +console.log(buf1.compare(buf2, 5, 6, 5).toString()); // Print: 1 +``` + +### copy + +copy(target: Buffer| Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number + +Copies data at the specified position in this **Buffer** instance to the specified position in another **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| target | Buffer \| Uint8Array | Yes| Instance to which data is copied.| +| targetStart | number | No| Offset to the start position in the target instance where data is copied. The default value is **0**.| +| sourceStart | number | No| Offset to the start position in this **Buffer** instance where data is copied. The default value is **0**.| +| sourceEnd | number | No| Offset to the end position in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Total length of the data copied, in bytes.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); +let buf2 = buffer.allocUninitializedFromPool(26).fill('!'); + +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} + +buf1.copy(buf2, 8, 16, 20); +console.log(buf2.toString('ascii', 0, 25)); +// Print: !!!!!!! qrst!!!!!!!!!!!!! +``` + +### entries + +entries(): IterableIterator<[number, number]> + +Creates and returns an iterator that contains key-value pairs of this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('buffer'); +for (let pair of buf.entries()) { + console.log(pair.toString()); +} +``` + +### equals + +equals(otherBuffer: Uint8Array | Buffer): boolean + +Checks whether this **Buffer** instance is the same as another **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| otherBuffer | Uint8Array \| Buffer | Yes| **Buffer** instance to compare.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the two instances are the same; returns **false** otherwise.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('ABC'); +let buf2 = buffer.from('414243', 'hex'); +let buf3 = buffer.from('ABCD'); + +console.log(buf1.equals(buf2).toString()); // Print: true +console.log(buf1.equals(buf3).toString()); // Print: false + +``` + +### fill + +fill(value: string | Buffer | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): Buffer + +Fills this **Buffer** instance at the specified position. By default, data is filled cyclically. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string \| Buffer \| Uint8Array \| number | Yes| Value to fill.| +| offset | number | No| Offset to the start position in this **Buffer** instance where data is filled. The default value is **0**.| +| end | number | No| Offset to the end position in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| +| encoding | BufferEncoding | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance filled with the specified value.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let b = buffer.allocUninitializedFromPool(50).fill('h'); +console.log(b.toString()); +``` + + +### includes + +includes(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): boolean + +Checks whether this **Buffer** instance contains the specified value. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| +| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. | +| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the instance contains the specified value; returns **false** otherwise.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this is a buffer'); +console.log(buf.includes('this').toString()); // Print: true +console.log(buf.includes('be').toString()); // Print: false +``` + +### indexOf + +indexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number + +Obtains the index of the first occurrence of the specified value in this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| +| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. | +| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Index obtained.
If **-1** is returned, the **Buffer** instance does not contain the specified value.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this is a buffer'); +console.log(buf.indexOf('this').toString()); // Print: 0 +console.log(buf.indexOf('is').toString()); // Print: 2 +``` + +### keys + +keys(): IterableIterator<number> + +Creates and returns an iterator that contains the keys of this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type| Description| +| -------- | -------- | +| IterableIterator<number> | Iterator.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('buffer'); +for (const key of buf.keys()) { + console.log(key.toString()); +} +``` + +### lastIndexOf + +lastIndexOf(value: string | number | Buffer | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number + +Obtains the index of the last occurrence of the specified value in this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| +| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. | +| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Index obtained.
If **-1** is returned, the **Buffer** instance does not contain the specified value.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from('this buffer is a buffer'); +console.log(buf.lastIndexOf('this').toString()); // Print: 0 +console.log(buf.lastIndexOf('buffer').toString()); // Print: 17 +``` + + +### readBigInt64BE + +readBigInt64BE(offset?: number): bigint + +Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| bigint | A signed, big-endian 64-bit Big integer. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigInt64BE(0).toString()); +``` + +### readBigInt64LE + +readBigInt64LE(offset?: number): bigint + +Reads a signed, little-endian 64-bit Big integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| bigint | A signed, little-endian 64-bit Big integer. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigInt64LE(0).toString()); +``` + +### readBigUInt64BE + +readBigUInt64BE(offset?: number): bigint + +Reads an unsigned, big-endian 64-bit Big integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| bigint | An unsigned, big-endian 64-bit Big integer. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigUInt64BE(0).toString()); +``` + +### readBigUInt64LE + +readBigUInt64LE(offset?: number): bigint + +Reads an unsigned, little-endian 64-bit Big integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| bigint | An unsigned, little-endian 64-bit Big integer. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, + 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); +console.log(buf.readBigUInt64LE(0).toString()); +``` + +### readDoubleBE + +readDoubleBE(offset?: number): number + +Reads a big-endian double-precision floating-point number from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A big-endian double-precision floating-point number. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readDoubleBE(0).toString()); +``` + +### readDoubleLE + +readDoubleLE(offset?: number): number + +Reads a little-endian double-precision floating-point number from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A little-endian double-precision floating-point number. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readDoubleLE(0).toString()); +``` + +### readFloatBE + +readFloatBE(offset?: number): number + +Reads a big-endian single-precision floating-point number from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A big-endian single-precision floating-point number. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readFloatBE(0).toString()); +``` + +### readFloatLE + +readFloatLE(offset?: number): number + +Reads a little-endian single-precision floating-point number from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A little-endian single-precision floating-point number. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); +console.log(buf.readFloatLE(0).toString()); +``` + +### readInt8 + +readInt8(offset?: number): number + +Reads a signed 8-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed 8-bit integer. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([-1, 5]); +console.log(buf.readInt8(0).toString()); // Print: -1 +console.log(buf.readInt8(1).toString()); // Print: 5 +``` + +### readInt16BE + +readInt16BE(offset?: number): number + +Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, big-endian 16-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0, 5]); +console.log(buf.readInt16BE(0).toString()); // Print: 5 +``` + +### readInt16LE + +readInt16LE(offset?: number): number + +Reads a signed, little-endian 16-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, little-endian 16-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0, 5]); +console.log(buf.readInt16LE(0).toString()); // Print: 1280 +``` + +### readInt32BE + +readInt32BE(offset?: number): number + +Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, big-endian 32-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0, 0, 0, 5]); +console.log(buf.readInt32BE(0).toString()); // Print: 5 +``` + +### readInt32LE + +readInt32LE(offset?: number): number + +Reads a signed, little-endian 32-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | A signed, little-endian 32-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0, 0, 0, 5]); +console.log(buf.readInt32LE(0).toString()); // Print: 83886080 +``` + +### readIntBE + +readIntBE(offset: number, byteLength: number): number + +Reads the specified number of bytes from this **Buffer** instance at the specified offset, and interprets the result as a big-endian, two's complement signed value that supports up to 48 bits of precision. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before starting to read data. The default value is **0**.| +| byteLength | number | Yes| Number of bytes to read.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Data read.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from("ab"); +let num = buf.readIntBE(0, 1); +console.log(num.toString()); // 97 +``` + + +### readIntLE + +readIntLE(offset: number, byteLength: number): number + +Reads the specified number of bytes from this **Buffer** instance at the specified offset and interprets the result as a little-endian, two's complement signed value that supports up to 48 bits of precision. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before starting to read data. The default value is **0**.| +| byteLength | number | Yes| Number of bytes to read.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Data read.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readIntLE(0, 6).toString(16)); +``` + +### readUInt8 + +readUInt8(offset?: number): number + +Reads an unsigned 8-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned 8-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([1, -2]); +console.log(buf.readUInt8(0).toString()); +console.log(buf.readUInt8(1).toString()); +``` + +### readUInt16BE + +readUInt16BE(offset?: number): number + +Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, big-endian 16-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56]); +console.log(buf.readUInt16BE(0).toString(16)); +console.log(buf.readUInt16BE(1).toString(16)); +``` + +### readUInt16LE + +readUInt16LE(offset?: number): number + +Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, little-endian 16-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56]); +console.log(buf.readUInt16LE(0).toString(16)); +console.log(buf.readUInt16LE(1).toString(16)); +``` + +### readUInt32BE + +readUInt32BE(offset?: number): number + +Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, big-endian 32-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); +console.log(buf.readUInt32BE(0).toString(16)); +``` + +### readUInt32LE + +readUInt32LE(offset?: number): number + +Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | No| Number of bytes to skip before starting to read data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | An unsigned, little-endian 32-bit integer.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); +console.log(buf.readUInt32LE(0).toString(16)); +``` + +### readUIntBE + +readUIntBE(offset: number, byteLength: number): number + +Reads the specified number of bytes from this **Buffer** instance at the specified offset, and interprets the result as an unsigned, big-endian integer that supports up to 48 bits of precision. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before starting to read data. The default value is **0**.| +| byteLength | number | Yes| Number of bytes to read.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Data read.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readUIntBE(0, 6).toString(16)); +``` + +### readUIntLE + +readUIntLE(offset: number, byteLength: number): number + +Reads the specified number of bytes from this **Buffer** instance at the specified offset, and interprets the result as an unsigned, little-endian integer that supports up to 48 bits of precision. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| offset | number | Yes| Number of bytes to skip before starting to read data. The default value is **0**.| +| byteLength | number | Yes| Number of bytes to read.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Data read.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); +console.log(buf.readUIntLE(0, 6).toString(16)); +``` + +### subarray + +subarray(start?: number, end?: number): Buffer + +Truncates this **Buffer** instance from the specified position to create a new **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| start | number | No| Offset to the start position in this **Buffer** instance where data is truncated. The default value is **0**.| +| end | number | No| Offset to the end position in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); + +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} +const buf2 = buf1.subarray(0, 3); +console.log(buf2.toString('ascii', 0, buf2.length)); +// Print: abc +``` + +### swap16 + +swap16(): Buffer + +Interprets this **Buffer** instance as an array of unsigned 16-bit integers and swaps the byte order in place. + +**System capability**: SystemCapability.Utils.Lang + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance swapped.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1.toString('hex')); // Print: 0102030405060708 + +buf1.swap16(); +console.log(buf1.toString('hex')); // Print: 0201040306050807 +``` + +### swap32 + +swap32(): Buffer + +Interprets this **Buffer** instance as an array of unsigned 32-bit integers and swaps the byte order in place. + +**System capability**: SystemCapability.Utils.Lang + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance swapped.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1.toString('hex')); // Print: 0102030405060708 + +buf1.swap32(); +console.log(buf1.toString('hex')); // Print: 0403020108070605 +``` + +### swap64 + +swap64(): Buffer + +Interprets this **Buffer** instance as an array of unsigned 64-bit integers and swaps the byte order in place. + +**System capability**: SystemCapability.Utils.Lang + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | **Buffer** instance swapped.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); +console.log(buf1.toString('hex')); // Print: 0102030405060708 +buf1.swap64(); +console.log(buf1.toString('hex')); // Print: 0807060504030201 +``` + +### toJSON + +toJSON(): Object + +Converts this **Buffer** instance into a JSON object. + +**System capability**: SystemCapability.Utils.Lang + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Object | JSON object.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); +let obj = buf1.toJSON(); +console.log(JSON.stringify(obj)) +// Print: {"type":"Buffer","data":[1,2,3,4,5]} +``` + +### toString + +toString(encoding?: string, start?: number, end?: number): string + +Converts the data at the specified position in this **Buffer** instance into a string in the specified encoding format. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| encoding | string | No| Encoding format of the string. The default value is **utf-8**.| +| start | number | No| Offset to the start position of the data to convert. The default value is **0**.| +| end | number | No| Offset to the end position of the data to convert. The default value is the length of this **Buffer** instance.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | String obtained.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.allocUninitializedFromPool(26); +for (let i = 0; i < 26; i++) { + buf1[i] = i + 97; +} +console.log(buf1.toString('utf-8')); +// Print: abcdefghijklmnopqrstuvwxyz +``` + +### values + +values(): IterableIterator<number> + +Creates and returns an iterator that contains the values of this **Buffer** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type| Description| +| -------- | -------- | +| IterableIterator<number> | Iterator created.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf1 = buffer.from('buffer'); +for (let value of buf1.values()) { + console.log(value.toString()); +} +``` + +### write + +write(str: string, offset?: number, length?: number, encoding?: string): number + +Writes a string of the specified length to this **Buffer** instance at the specified position in the given encoding format. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| str | string | Yes| String to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| +| length | number | No| Maximum number of bytes to write. The default value is the length of the **Buffer** instance minus the offset.| +| encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(256); +let len = buf.write('\u00bd + \u00bc = \u00be', 0); +console.log(`${len} bytes: ${buf.toString('utf-8', 0, len)}`); +// Print: 12 bytes: ½ + ¼ = ¾ + +let buffer1 = buffer.alloc(10); +let length = buffer1.write('abcd', 8); +``` + +### writeBigInt64BE + +writeBigInt64BE(value: bigint, offset?: number): number + +Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | bigint | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigInt64BE(0x0102030405060708n, 0); +``` + +### writeBigInt64LE + +writeBigInt64LE(value: bigint, offset?: number): number + +Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | bigint | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigInt64LE(0x0102030405060708n, 0); +``` + +### writeBigUInt64BE + +writeBigUInt64BE(value: bigint, offset?: number): number + +Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | bigint | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigUInt64BE(0xdecafafecacefaden, 0); +``` + +### writeBigUInt64LE + +writeBigUInt64LE(value: bigint, offset?: number): number + +Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | bigint | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeBigUInt64LE(0xdecafafecacefaden, 0); +``` + +### writeDoubleBE + +writeDoubleBE(value: number, offset?: number): number + +Writes a big-endian double-precision floating-point number to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeDoubleBE(123.456, 0); +``` + +### writeDoubleLE + +writeDoubleLE(value: number, offset?: number): number + +Writes a little-endian double-precision floating-point number to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeDoubleLE(123.456, 0); +``` + +### writeFloatBE + +writeFloatBE(value: number, offset?: number): number + +Writes a big-endian single-precision floating-point number to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeFloatBE(0xcafebabe, 0); +``` + + +### writeFloatLE + +writeFloatLE(value: number, offset?: number): number + +Writes a little-endian single-precision floating-point number to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(8); +buf.writeFloatLE(0xcafebabe, 0); +``` + +### writeInt8 + +writeInt8(value: number, offset?: number): number + +Writes a signed 8-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt8(2, 0); +buf.writeInt8(-2, 1); +``` + + +### writeInt16BE + +writeInt16BE(value: number, offset?: number): number + +Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt16BE(0x0102, 0); +``` + + +### writeInt16LE + +writeInt16LE(value: number, offset?: number): number + +Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(2); +buf.writeInt16LE(0x0304, 0); +``` + +### writeInt32BE + +writeInt32BE(value: number, offset?: number): number + +Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeInt32BE(0x01020304, 0); +``` + + +### writeInt32LE + +writeInt32LE(value: number, offset?: number): number + +Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeInt32LE(0x05060708, 0); +``` + +### writeIntBE + +writeIntBE(value: number, offset: number, byteLength: number): number + +Writes a big-endian signed value of the specified length to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | Yes| Number of bytes to skip before starting to write data. The default value is **0**.| +| byteLength | number | Yes| Number of bytes to write.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeIntBE(0x1234567890ab, 0, 6); +``` + + +### writeIntLE + +writeIntLE(value: number, offset: number, byteLength: number): number + +Writes a little-endian signed value of the specified length to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | Yes| Number of bytes to skip before starting to write data. The default value is **0**.| +| byteLength | number | Yes| Number of bytes to write.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeIntLE(0x1234567890ab, 0, 6); +``` + +### writeUInt8 + +writeUInt8(value: number, offset?: number): number + +Writes an unsigned 8-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt8(0x3, 0); +buf.writeUInt8(0x4, 1); +buf.writeUInt8(0x23, 2); +buf.writeUInt8(0x42, 3); +``` + +### writeUInt16BE + +writeUInt16BE(value: number, offset?: number): number + +Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt16BE(0xdead, 0); +buf.writeUInt16BE(0xbeef, 2); +``` + +### writeUInt16LE + +writeUInt16LE(value: number, offset?: number): number + +Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt16LE(0xdead, 0); +buf.writeUInt16LE(0xbeef, 2); +``` + +### writeUInt32BE + +writeUInt32BE(value: number, offset?: number): number + +Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt32BE(0xfeedface, 0); +``` + +### writeUInt32LE + +writeUInt32LE(value: number, offset?: number): number + +Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(4); +buf.writeUInt32LE(0xfeedface, 0); +``` + +### writeUIntBE + +writeUIntBE(value: number, offset: number, byteLength: number): number + +Writes an unsigned big-endian value of the specified length to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | Yes| Number of bytes to skip before starting to write data. The default value is **0**.| +| byteLength | number | Yes| Number of bytes to write.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeUIntBE(0x1234567890ab, 0, 6); +``` + +### writeUIntLE + +writeUIntLE(value: number, offset: number, byteLength: number): number + +Writes an unsigned little-endian value of the specified length to this **Buffer** instance at the specified offset. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Data to write.| +| offset | number | Yes| Number of bytes to skip before starting to write data. The default value is **0**.| +| byteLength | number | Yes| Number of bytes to write.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Number of bytes written.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.allocUninitializedFromPool(6); +buf.writeUIntLE(0x1234567890ab, 0, 6); +``` + +### transcode + +transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer + +Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | Buffer \| Uint8Array | Yes| Instance to transcode. | +| fromEnc | string | Yes| Current encoding format.| +| toEnc | string | Yes| Target encoding format.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | New **Buffer** instance in the target encoding format.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(50); +let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); +console.log(newBuf.toString('ascii')); +``` + +## Blob + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| size | number | Yes| No| Total size of the **Blob** instance, in bytes.| +| type | string | Yes| No| Type of the data in the **Blob** instance.| + +### constructor + +constructor(sources: string[] | ArrayBuffer[] | TypedArray[] | DataView[] | Blob[] , options?: Object) + +A constructor used to create a **Blob** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sources | string[] \| ArrayBuffer[] \| TypedArray[] \| DataView[] \| Blob[] | Yes| Data sources of the **Blob** instance.| +| options | Object | No| options:
- **endings**: 'transparent' or 'native'.
- **type**: type of the data in **Blob**.| + + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let blob = new buffer.Blob(['a', 'b', 'c']); +let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'}); +``` + +### encode + +arrayBuffer(): Promise<ArrayBuffer> + +Puts the **Blob** data into an **ArrayBuffer** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<ArrayBuffer> | Promise used to return the **ArrayBuffer** containing the **Blob** data.| + +**Example** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let pro = blob.arrayBuffer(); + pro.then(val => { + let uintarr = new Uint8Array(val); + console.log(uintarr.toString()); + }); + ``` +### slice + +slice(start?: number, end?: number, type?: string): Blob + +Creates a **Blob** instance by copying specified data from this **Blob** instance. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| start | number | No| Offset to the start position of the data to copy.| +| end | number | No| Offset to the end position of the data to copy.| +| type | string | No| Type of the data in the new **Blob** instance.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Blob | **Blob** instance created. | + +**Example** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let blob2 = blob.slice(0, 2); + let blob3 = blob.slice(0, 2, "MIME"); + ``` + + ### text + +text(): Promise<string> + +Returns text in UTF-8 format. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the text encoded in UTF-8.| + +**Example** + ```ts + let blob = new buffer.Blob(['a', 'b', 'c']); + let pro = blob.text(); + pro.then(val => { + console.log(val) + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md index 7b932cacbc2195e8c52976aa80e71bd3b638921d..3a00ac698a3529d153ef3741979238569555f12c 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @@ -10,6 +10,8 @@ The **LauncherAbilityInfo** module provides information about a launcher ability **System capability**: SystemCapability.BundleManager.BundleFramework +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Readable| Writable| Description | | --------------- | ---------------------------------------------------- | ---- | ---- | ------------------------------------ | | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.| diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 1631e3318f49bd07012e836449dfa4431a67db65..ac82d0b2e610751bd000849ec35337363b0dcb3a 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -2810,10 +2810,11 @@ This is a system API. | Name | Value | Description | | -------------------- | ---- | ------------ | -| DEVICE_EARPIECE | 0 | Headset device. | -| DEVICE_SPEAKER | 1 | Speaker device.| -| DEVICE_WIRED_HEADSET | 2 | Wired headset device.| +| DEVICE_EARPIECE | 0 | Earpiece. | +| DEVICE_SPEAKER | 1 | Speaker.| +| DEVICE_WIRED_HEADSET | 2 | Wired headset.| | DEVICE_BLUETOOTH_SCO | 3 | Bluetooth SCO device. | +| DEVICE_MIC | 4 | Microphone. | ## CallRestrictionType8+ diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index f9c55898029eee1a6782df976cfd40ec43574735..78db0562f97cf687e26c210d870519c829b691ee 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -20,9 +20,9 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ---------------------------- | -| context | Context | Yes | Application context. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ---------------------------------- | +| context | Context | Yes | Application context. | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | Yes | Callback used to return the **CameraManager** instance.| **Example** @@ -30,7 +30,7 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to ```js camera.getCameraManager(context, (err, cameraManager) => { if (err) { - console.error(`Failed to get the CameraManager instance ${err.message}`); + console.error('Failed to get the CameraManager instance ${err.message}'); return; } console.log('Callback returned with the CameraManager instance'); @@ -53,8 +53,8 @@ Obtains a **CameraManager** instance. This API uses a promise to return the resu **Return value** -| Type | Description | -| ----------------------------------------- | ----------------------------------- | +| Type | Description | +| ----------------------------------------- | ----------------------------------------- | | Promise<[CameraManager](#cameramanager)\> | Promise used to return the **CameraManager** instance.| **Example** @@ -78,1149 +78,947 @@ Enumerates the camera statuses. | CAMERA_STATUS_AVAILABLE | 2 | The camera is available. | | CAMERA_STATUS_UNAVAILABLE | 3 | The camera is unavailable.| -## Profile -Defines the camera profile. +## CameraPosition + +Enumerates the camera positions. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| -------- | ----------------------------- |---- | ------------- | -| format | [CameraFormat](#cameraformat) | Yes | Output format. | -| size | [Size](#size) | Yes | Resolution. | +| Name | Value | Description | +| --------------------------- | ---- | ---------------- | +| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position.| +| CAMERA_POSITION_BACK | 1 | Rear camera. | +| CAMERA_POSITION_FRONT | 2 | Front camera. | -## FrameRateRange +## CameraType - Defines the frame rate range. +Enumerates the camera types. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| ------------------------- | ------ | ---- | ------------------- | -| min | number | Yes | Minimum rate, in fps. | -| max | number | Yes | Maximum rate, in fps. | +| Name | Value | Description | +| ----------------------- | ---- | ---------------- | +| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type.| +| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. | +| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. | +| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. | +| CAMERA_TYPE_TRUE_DEPTH | 4 | Camera with depth of field information. | + -## VideoProfile +## ConnectionType -Defines the video profile. +Enumerates the camera connection types. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| ------------------------- | ----------------------------------------- | --- |------------ | -| frameRateRanges | [FrameRateRange](#frameraterange) | Yes | Frame rate range. | +| Name | Value | Description | +| ---------------------------- | ---- | ------------- | +| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera. | +| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB.| +| CAMERA_CONNECTION_REMOTE | 2 | Remote camera. | -## CameraOutputCapability +## Size -Defines the camera output capability. +Defines the image size that can be used in previewing, photographing, and video recording. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read only| Description | -| ----------------------------- | -------------------------------------------------- | --- |------------------- | -| previewProfiles | Array<[Profile](#profile)\> | Yes | Supported preview profiles. | -| photoProfiles | Array<[Profile](#profile)\> | Yes | Supported shooting profiles. | -| videoProfiles | Array<[VideoProfile](#videoprofile)\> | Yes | Supported video recording profiles. | -| supportedMetadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| +| Name | Type | Readable| Writable| Description | +| ------ | ------ | ---- | ---- | ------------ | +| height | string | Yes | Yes | Image height.| +| width | number | Yes | Yes | Image width.| ## CameraManager Implements camera management. Before calling any API in **CameraManager**, you must use **getCameraManager** to obtain a **CameraManager** instance. -### getSupportedCameras +### getCameras -getSupportedCameras(callback: AsyncCallback\>): void +getCameras(callback: AsyncCallback\>): void -Obtains supported cameras. This API uses an asynchronous callback to return the result. +Obtains all cameras supported by the device. This API uses an asynchronous callback to return the array of supported cameras. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ------------------------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the array of supported cameras.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return the array of supported cameras.| **Example** ```js -cameraManager.getSupportedCameras((err, cameras) => { +cameraManager.getCameras((err, cameras) => { if (err) { - console.error(`Failed to get the cameras. ${err.message}`); + console.error('Failed to get the cameras. ${err.message}'); return; } - console.log(`Callback returned with an array of supported cameras: ${cameras.length}`); + console.log('Callback returned with an array of supported cameras: ' + cameras.length); }) ``` -### getSupportedCameras +### getCameras -getSupportedCameras(): Promise\> +getCameras(): Promise\> -Obtains supported cameras. This API uses a promise to return the result. +Obtains all cameras supported by the device. This API uses a promise to return the array of supported cameras. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ----------------------------------------------- | ------------------------- | -| Promise\> | Promise used to return the array of supported cameras.| +| Type | Description | +| ----------------------------------- | ----------------------------- | +| Promise\> | Promise used to return the array of supported cameras.| **Example** ```js -cameraManager.getSupportedCameras().then((cameraArray) => { - console.log(`Promise returned with an array of supported cameras: ${cameraArray.length}`); +cameraManager.getCameras().then((cameraArray) => { + console.log('Promise returned with an array of supported cameras: ' + cameraArray.length); }) ``` -### getSupportedOutputCapability +### createCameraInput + +createCameraInput(cameraId: string, callback: AsyncCallback): void -getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback): void +Creates a **CameraInput** instance with the specified camera ID. This API uses an asynchronous callback to return the result. -Obtains the output capability supported by a camera. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------------------- | -- | -------------------------- | -| camera | [CameraDevice](#cameradevice) | Yes| **CameraDevice** object. | -| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | Yes| Callback used to return the output capability.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| cameraId | string | Yes | ID of the target camera. | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| **Example** ```js -cameraManager.getSupportedOutputCapability(cameraDevice, (err, cameras) => { +cameraManager.createCameraInput(cameraId, (err, cameraInput) => { if (err) { - console.error(`Failed to get the cameras. ${err.message}`); + console.error('Failed to create the CameraInput instance. ${err.message}'); return; } - console.log('Callback returned with an array of supported outputCapability'); + console.log('Callback returned with the CameraInput instance.'); }) ``` -### getSupportedOutputCapability +### createCameraInput + +createCameraInput(cameraId: string): Promise -getSupportedOutputCapability(camera:CameraDevice): Promise +Creates a **CameraInput** instance with the specified camera ID. This API uses a promise to return the result. -Obtains the output capability supported by a camera. This API uses a promise to return the result. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------- | ---- | ---------- | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------ | +| cameraId | string | Yes | ID of the target camera.| **Return value** -| Type | Description | -| -------------------------------------------------------------- | ----------------------------- | -| Promise<[CameraOutputCapability](#cameraoutputcapability)\> | Promise used to return the output capability.| - +| Type | Description | +| ------------------------------------- | ---------------------------------------- | +| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| **Example** ```js -cameraManager.getSupportedOutputCapability(cameraDevice).then((cameraoutputcapability) => { - console.log('Promise returned with an array of supported outputCapability'); +cameraManager.createCameraInput(cameraId).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance'); }) ``` -### getSupportedMetadataObjectType +### createCameraInput + +createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void -getSupportedMetadataObjectType(callback: AsyncCallback\>): void +Creates a **CameraInput** instance with the specified camera position and type. This API uses an asynchronous callback to return the result. -Obtains the metadata object types supported by this camera. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------------------- | -- | -------------------------- | -| callback | AsyncCallback\> | Yes| Callback used to return the metadata object types.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ----------------------------------- | +| position | [CameraPosition](#cameraposition) | Yes | Camera position. | +| type | [CameraType](#cameratype) | Yes | Camera type. | +| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance.| **Example** ```js -cameraManager.getSupportedMetadataObjectType((err, metadataobject) => { +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { if (err) { - console.error(`Failed to get the supported metadataObjectType. ${err.message}`); + console.error('Failed to create the CameraInput instance. ${err.message}'); return; } - console.log('Callback returned with an array of supported metadataObjectType.' ); + console.log('Callback returned with the CameraInput instance'); }) ``` -### getSupportedMetadataObjectType +### createCameraInput + +createCameraInput(position: CameraPosition, type: CameraType): Promise -getSupportedMetadataObjectType(camera:CameraDevice): Promise +Creates a **CameraInput** instance with the specified camera position and type. This API uses a promise to return the result. -Obtains the metadata object types supported by this camera. This API uses a promise to return the result. +**Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** +**Parameters** -| Type | Description | -| -------------------------------------------------------------- | ----------------------------- | -| Promise\> | Promise used to return the metadata object types.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ---------- | +| position | [CameraPosition](#cameraposition) | Yes | Camera position.| +| type | [CameraType](#cameratype) | Yes | Camera type.| + +**Return value** +| Type | Description | +| ------------------------------------- | ---------------------------------------- | +| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| **Example** ```js -cameraManager.getSupportedMetadataObjectType().then((metadataobject) => { - console.log('Promise returned with an array of supported metadataObjectType.' ); +cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { + console.log('Promise returned with the CameraInput instance.'); }) ``` -### isCameraMuted +### on('cameraStatus') -isCameraMuted(callback: AsyncCallback): void +on(type: 'cameraStatus', callback: AsyncCallback): void -Checks whether this camera is muted. This API uses an asynchronous callback to return the result. +Listens for camera status changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result. The value **true** means that the camera is muted, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **`cameraStatus`**, indicating the camera status change event.| +| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change. | **Example** ```js -cameraManager.isCameraMuted((err, status) => { +cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { if (err) { - console.error(`Failed to get the cameraMuted status. ${err.message}`); + console.error('Failed to get cameraStatus callback. ${err.message}'); return; } - console.log('Callback returned with cameraMuted status'); + console.log('camera : ' + cameraStatusInfo.camera.cameraId); + console.log('status: ' + cameraStatusInfo.status); }) ``` -### isCameraMuted - -isCameraMuted(): Promise +## Camera -Checks whether this camera is muted. This API uses a promise to return the result. +After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera instance is returned, with camera-related metadata such as **cameraId**, **cameraPosition**, **cameraType**, and **connectionType**. **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** - -| Type | Description | -| ------------------------------------ | --------------------------------------------- | -| Promise | Promise used to return the result. The value **true** means that the camera is muted, and **false** means the opposite. | - +| Name | Type | Read only| Description | +| -------------- | --------------------------------- | ---- | -------------- | +| cameraId | string | Yes | Camera ID. | +| cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | +| cameraType | [CameraType](#cameratype) | Yes | Camera type. | +| connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type.| **Example** ```js -cameraManager.isCameraMuted().then((status) => { - console.log('Promise returned with the status whether camera is muted.'); -}) +async function getCameraInfo("cameraId") { + var cameraManager = await camera.getCameraManager(context); + var cameras = await cameraManager.getCameras(); + var cameraObj = cameras[0]; + var cameraId = cameraObj.cameraId; + var cameraPosition = cameraObj.cameraPosition; + var cameraType = cameraObj.cameraType; + var connectionType = cameraObj.connectionType; +} ``` -### isCameraMuteSupported +## CameraStatusInfo + +Describes the camera status information. + +**System capability**: SystemCapability.Multimedia.Camera.Core -isCameraMuteSupported(callback: AsyncCallback): void +| Name | Type | Description | +| ------ | ----------------------------- | ---------- | +| camera | [Camera](#camera) | Camera object.| +| status | [CameraStatus](#camerastatus) | Camera status.| -Checks whether this camera can be muted. This API uses an asynchronous callback to return the result. -This is a system API. +## CameraInput -**Required permissions**: ohos.permission.CAMERA +Implements a **CameraInput** instance. Before calling any API in **CameraInput**, you must create a **CameraInput** instance. + +### getCameraId + +getCameraId(callback: AsyncCallback\): void + +Obtains the camera ID based on which this **CameraInput** instance is created. This API uses an asynchronous callback to return the camera ID. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result. The value **true** means that the camera can be muted, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the camera ID.| **Example** ```js -cameraManager.isCameraMuteSupported((err, status) => { +cameraInput.getCameraId((err, cameraId) => { if (err) { - console.error(`Failed to get the cameraMuteSupported. ${err.message}`); + console.error('Failed to get the camera ID. ${err.message}'); return; } - console.log('Callback returned with the status whether cameraMuteSupported.'); + console.log('Callback returned with the camera ID: ' + cameraId); }) ``` -### isCameraMuteSupported +### getCameraId -isCameraMuteSupported(): Promise +getCameraId(): Promise -Checks whether this camera can be muted. This API uses a promise to return the result. - -This is a system API. - -**Required permissions**: ohos.permission.CAMERA +Obtains the camera ID based on which this **CameraInput** instance is created. This API uses a promise to return the camera ID. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| --------------------- | ----------------------------- | -| Promise | Promise used to return the result. The value **true** means that the camera can be muted, and **false** means the opposite.| - +| Type | Description | +| ---------------- | ----------------------------- | +| Promise | Promise used to return the camera ID.| **Example** ```js -cameraManager.isCameraMuteSupported().then((status) => { - console.log('Promise returned with the status whether cameraMuteSupported.'); +cameraInput.getCameraId().then((cameraId) => { + console.log('Promise returned with the camera ID:' + cameraId); }) ``` -### muteCamera -muteCamera(mute:boolean, callback: AsyncCallback): void - -Mutes this camera. This API uses an asynchronous callback to return the result. +### hasFlash -This is a system API. +hasFlash(callback: AsyncCallback): void -**Required permissions**: ohos.permission.CAMERA +Checks whether the device has flash. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------ | -| mute | boolean | Yes | Whether to mute the camera. The value **true** means to mute the camera, and **false** means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the flash support status. The value **true** means that the device has flash.| **Example** ```js -cameraManager.muteCamera(isMuted, (err) => { +cameraInput.hasFlash((err, status) => { if (err) { - console.error(`Failed to mute the camera. ${err.message}`); + console.error('Failed to check whether the device has flash light. ${err.message}'); return; } - console.log('Callback returned with the muteCamera.'); + console.log('Callback returned with flash light support status: ' + status); }) ``` -### muteCamera - -muteCamera(mute:boolean): Promise - -Mutes this camera. This API uses a promise to return the result. +### hasFlash -This is a system API. +hasFlash(): Promise -**Required permissions**: ohos.permission.CAMERA +Checks whether the device has flash. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------ | -| mute | boolean | Yes | Whether to mute the camera. The value **true** means to mute the camera, and **false** means the opposite. | - **Return value** -| Type | Description | -| ----------------------------------- | ----------------------------- | -| Promise | Promise used to return the result.| - +| Type | Description | +| ----------------- | ------------------------------------------------------- | +| Promise | Promise used to return the flash support status. The value **true** means that the device has flash.| **Example** -```js -cameraManager.muteCamera(isMuted).then(() => { - console.log('Promise returned muteCamera.'); +```js +cameraInput.hasFlash().then((status) => { + console.log('Promise returned with the flash light support status:' + status); }) ``` -### createCameraInput - -createCameraInput(camera: CameraDevice, callback: AsyncCallback): void - -Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses an asynchronous callback to return the result. +### isFlashModeSupported -This is a system API. +isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void -**Required permissions**: ohos.permission.CAMERA +Checks whether a specified flash mode is supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | --------------------------------- | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object. | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------------------------------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | +| callback | AsyncCallback | Yes | Callback used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| **Example** ```js -cameraManager.createCameraInput(camera, (err, cameraInput) => { +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { if (err) { - console.error(`Failed to create the CameraInput instance. ${err.message}`); + console.error('Failed to check whether the flash mode is supported. ${err.message}'); return; } - console.log('Callback returned with the CameraInput instance.'); + console.log('Callback returned with the flash mode support status: ' + status); }) ``` -### createCameraInput - -createCameraInput(camera: CameraDevice): Promise - -Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses a promise to return the result. +### isFlashModeSupported -This is a system API. +isFlashModeSupported(flashMode: FlashMode): Promise -**Required permissions**: ohos.permission.CAMERA +Checks whether a specified flash mode is supported. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------- | ---- | ---------- | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| **Return value** -| Type | Description | -| ------------------------------------- | ------------------------------------ | -| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise | Promise used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| **Example** ```js -cameraManager.createCameraInput(camera).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance'); +cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { + console.log('Promise returned with flash mode support status.' + status); }) ``` -### createCameraInput +### setFlashMode -createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCallback): void +setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void -Creates a **CameraInput** instance with the specified camera position and type. This API uses an asynchronous callback to return the result. +Sets the flash mode. This API uses an asynchronous callback to return the result. -This is a system API. +Before the setting, do the following checks: -**Required permissions**: ohos.permission.CAMERA +1. Use **[hasFlash](#hasflash)** to check whether the device has flash. +2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | --------------------------------- | -| position | [CameraPosition](#cameraposition) | Yes | Camera position. | -| type | [CameraType](#cameratype) | Yes | Camera type. | -| callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ------------------------ | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { if (err) { - console.error(`Failed to create the CameraInput instance. ${err.message}`); + console.error('Failed to set the flash mode ${err.message}'); return; } - console.log('Callback returned with the CameraInput instance'); + console.log('Callback returned with the successful execution of setFlashMode.'); }) ``` -### createCameraInput +### setFlashMode -createCameraInput(position: CameraPosition, type:CameraType ): Promise +setFlashMode(flashMode: FlashMode): Promise -Creates a **CameraInput** instance with the specified camera position and type. This API uses a promise to return the result. +Sets a flash mode. This API uses a promise to return the result. -This is a system API. +Before the setting, do the following checks: -**Required permissions**: ohos.permission.CAMERA +1. Use **[hasFlash](#hasflash)** to check whether the device has flash. +2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ------------ | -| position | [CameraPosition](#cameraposition) | Yes | Camera position. | -| type | [CameraType](#cameratype) | Yes | Camera type. | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------------- | +| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| **Return value** -| Type | Description | -| ------------------------------------- | ------------------------------------ | -| Promise<[CameraInput](#camerainput)\> | Promise used to return the **CameraInput** instance.| +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| **Example** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED).then((cameraInput) => { - console.log('Promise returned with the CameraInput instance'); +cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFlashMode.'); }) ``` -### createPreviewOutput +### getFlashMode -createPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void +getFlashMode(callback: AsyncCallback): void -Creates a **PreviewOutput** instance. This API uses an asynchronous callback to return the result. +Obtains the flash mode in use. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ------------------------------- | -| profile | [Profile](#profile) | Yes | Supported preview profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback<[FlashMode](#flashmode)\> | Yes | Callback used to return the flash mode.| **Example** ```js -cameraManager.createPreviewOutput(profile, surfaceId, (err, previewoutput) => { +cameraInput.getFlashMode((err, flashMode) => { if (err) { - console.error(`Failed to gcreate previewOutput. ${err.message}`); + console.error('Failed to get the flash mode ${err.message}'); return; } - console.log('Callback returned with previewOutput created.'); + console.log('Callback returned with current flash mode: ' + flashMode); }) ``` -### createPreviewOutput +### getFlashMode -createPreviewOutput(profile: Profile, surfaceId: string): Promise +getFlashMode(): Promise -Creates a **PreviewOutput** instance. This API uses a promise to return the result. +Obtains the flash mode in use. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------| ---- | ----------------- | -| profile | [Profile](#profile) | Yes | Supported preview profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| - **Return value** -| Type | Description | -| ---------------------------------------- | ---------------------------------------- | -| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance. | +| Type | Description | +| --------------------------------- | --------------------------------------- | +| Promise<[FlashMode](#flashmode)\> | Promise used to return the flash mode.| **Example** ```js -cameraManager.createPreviewOutput(profile, survaceId).then((previewoutput) => { - console.log('Promise returned with previewOutput created.'); +cameraInput.getFlashMode().then((flashMode) => { + console.log('Promise returned with current flash mode : ' + flashMode); }) ``` -### createDeferredPreviewOutput +### isFocusModeSupported -createDeferredPreviewOutput(profile: Profile, callback: AsyncCallback): void +isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void -Creates a **PreviewOutput** instance without a surface ID. This API uses an asynchronous callback to return the result. +Checks whether a specified focus mode is supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | --------------------------------- | -| profile | [Profile](#profile) | Yes | Supported preview profile. | -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | +| callback | AsyncCallback | Yes | Callback used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.| **Example** ```js -cameraManager.createDeferredPreviewOutput(profile, (err, previewoutput) => { +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { if (err) { - console.error(`Failed to create deferredPreviewOutput. ${err.message}`); + console.error('Failed to check whether the focus mode is supported. ${err.message}'); return; } - console.log('Callback returned with deferredPreviewOutput created.'); + console.log('Callback returned with the focus mode support status: ' + status); }) ``` -### createDeferredPreviewOutput +### isFocusModeSupported -createDeferredPreviewOutput(profile: Profile): Promise +isFocusModeSupported(afMode: FocusMode): Promise -Creates a **PreviewOutput** instance without a surface ID. This API uses a promise to return the result. +Checks whether a specified focus mode is supported. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------| ---- | ---------- | -| profile | [Profile](#profile) | Yes | Supported preview profile. | +| Name | Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| **Return value** -| Type | Description | -| ----------------------------------------- | --------------------------------------- | -| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the **PreviewOutput** instance.| +| Type | Description | +| ----------------- | ----------------------------------------------------------- | +| Promise | Promise used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.| **Example** ```js -cameraManager.createDeferredPreviewOutput(profile).then((previewoutput) => { - console.log('Promise returned with DefeerredPreviewOutput created.'); +cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { + console.log('Promise returned with focus mode support status.' + status); }) ``` -### createPhotoOutput +### setFocusMode -createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void +setFocusMode(afMode: FocusMode, callback: AsyncCallback): void -Creates a **PhotoOutput** instance. This API uses an asynchronous callback to return the result. +Sets a focus mode. This API uses an asynchronous callback to return the result. + +Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ----------------------------------- | -| profile | [Profile](#profile) | Yes | Supported shooting profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| -| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | Yes | Callback used to return the **PhotoOutput** instance. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------ | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraManager.createPhotoOutput(profile, surfaceId, (err, photooutput) => { +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { if (err) { - console.error(`Failed to create photoOutput. ${err.message}`); + console.error('Failed to set the focus mode ${err.message}'); return; } - console.log('Callback returned with photoOutput created.'); + console.log('Callback returned with the successful execution of setFocusMode.'); }) ``` -### createPhotoOutput +### setFocusMode + +setFocusMode(afMode: FocusMode): Promise -createPhotoOutput(profile: Profile, surfaceId: string): Promise +Sets a focus mode. This API uses a promise to return the result. -Creates a **PhotoOutput** instance. This API uses a promise to return the result. +Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------| ---- | ----------- | -| profile | [Profile](#profile) | Yes | Supported shooting profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| Name | Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------- | +| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| **Return value** -| Type | Description | -| ------------------------------------- | -------------------------------------- | -| Promise<[PhotoOutput](#photooutput)\> | Promise used to return the **PhotoOutput** instance. | +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| **Example** ```js -cameraManager.createPhotoOutput(profile, surfaceId).then((photooutput) => { - console.log('Promise returned with photoOutput created.'); +cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { + console.log('Promise returned with the successful execution of setFocusMode.'); }) ``` -### createVideoOutput +### getFocusMode -createVideoOutput(profile: VideoProfile, surfaceId: string, callback: AsyncCallback): void +getFocusMode(callback: AsyncCallback): void -Creates a **VideoOutput** instance. This API uses an asynchronous callback to return the result. +Obtains the focus mode in use. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | ------------------------------ | -| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| -| callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback<[FocusMode](#focusmode)\> | Yes | Callback used to return the focus mode.| **Example** ```js -cameraManager.createVideoOutput(profile, surfaceId, (err, videooutput) => { +cameraInput.getFocusMode((err, afMode) => { if (err) { - console.error(`Failed to create videoOutput. ${err.message}`); + console.error('Failed to get the focus mode ${err.message}'); return; } - console.log('Callback returned with an array of supported outputCapability' ); + console.log('Callback returned with current focus mode: ' + afMode); }) ``` -### createVideoOutput +### getFocusMode -createVideoOutput(profile: VideoProfile, surfaceId: string): Promise +getFocusMode(): Promise -Creates a **VideoOutput** instance. This API uses a promise to return the result. +Obtains the focus mode in use. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------| ---- | ---------- | -| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| - **Return value** -| Type | Description | -| ------------------------------------- | -------------------------------------- | -| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance. | +| Type | Description | +| ------------------- | ------------------------------------- | +| Promise | Promise used to return the focus mode.| **Example** ```js -cameraManager.createVideoOutput(profile, surfaceId).then((videooutput) => { - console.log('Promise returned with videoOutput created.'); +cameraInput.getFocusMode().then((afMode) => { + console.log('Promise returned with current focus mode : ' + afMode); }) ``` -### createMetadataOutput +### getZoomRatioRange -createMetadataOutput(metadataObjectTypes: Array, callback: AsyncCallback): void +getZoomRatioRange\(callback: AsyncCallback\>\): void -Creates a **MetadataOutput** instance. This API uses an asynchronous callback to return the result. +Obtains the zoom ratio range. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------------------- | -------------------------------------------------- | --- | ---------------------------- | -| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types. | -| callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | Yes | Callback used to return the **MetadataOutput** instance. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | ------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| **Example** ```js -cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataoutput) => { +cameraInput.getZoomRatioRange((err, zoomRatioRange) => { if (err) { - console.error(`Failed to create metadataOutput. ${err.message}`); + console.error('Failed to get the zoom ratio range. ${err.message}'); return; } - console.log('Callback returned with metadataOutput created.'); + console.log('Callback returned with zoom ratio range: ' + zoomRatioRange.length); }) ``` -### createMetadataOutput +### getZoomRatioRange -createMetadataOutput(metadataObjectTypes: Array): Promise +getZoomRatioRange\(\): Promise\> -Creates a **MetadataOutput** instance. This API uses a promise to return the result. +Obtains the zoom ratio range. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------------- | -------------------------------------------------- | --- | -------------- | -| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Supported metadata object types.| - **Return value** -| Type | Description | -| ------------------------------------------ | ----------------------------------------- | -| Promise<[MetadataOutput](#metadataoutput)\> | Promise used to return the **MetadataOutput** instance.| +| Type | Description | +| ------------------------ | ------------------------------------------- | +| Promise\> | Promise used to return the zoom ratio range.| **Example** ```js -cameraManager.createMetadataOutput(metadataObjectTypes).then((metadataoutput) => { - console.log('Promise returned with metadataOutput created.'); +cameraInput.getZoomRatioRange().then((zoomRatioRange) => { + console.log('Promise returned with zoom ratio range: ' + zoomRatioRange.length); }) ``` -### createCaptureSession +### setZoomRatio -createCaptureSession(callback: AsyncCallback): void +setZoomRatio(zoomRatio: number, callback: AsyncCallback): void -Creates a **CaptureSession** instance. This API uses an asynchronous callback to return the result. +Sets a zoom ratio. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------------------- | ----------------------------------------- | ----------- | ---------------------------- | -| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.| +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ------------------------ | +| zoomRatio | number | Yes | Zoom ratio. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraManager.createCaptureSession((err, capturesession) => { +cameraInput.setZoomRatio(1, (err) => { if (err) { - console.error(`Failed to create captureSession. ${err.message}`); + console.error('Failed to set the zoom ratio value ${err.message}'); return; } - console.log('Callback returned with captureSession created.'); -}) -``` - -### createCaptureSession - -createCaptureSession(): Promise - -Creates a **CaptureSession** instance. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ------------------------------------------- | ---------------------------------------- | -| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.| - -**Example** - -```js -cameraManager.createCaptureSession().then((capturesession) => { - console.log('Promise returned with captureSession created.'); + console.log('Callback returned with the successful execution of setZoomRatio.'); }) ``` -### on('cameraStatus') +### setZoomRatio -on(type: 'cameraStatus', callback: AsyncCallback): void +setZoomRatio(zoomRatio: number): Promise -Listens for camera status changes. This API uses an asynchronous callback to return the result. +Sets a zoom ratio. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | --------- | -| type | string | Yes | Event type. The value is fixed at **'cameraStatus'**, indicating the camera status change event.| -| callback | AsyncCallback<[CameraStatusInfo](#camerastatusinfo)\> | Yes | Callback used to return the camera status change. | - -**Example** - -```js -cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { - if (err) { - console.error(`Failed to get cameraStatus callback. ${err.message}`); - return; - } - console.log(`camera : ${cameraStatusInfo.camera.cameraId}`); - console.log(`status: ${cameraStatusInfo.status}`); -}) -``` - -### on('cameraMute') - -on(type: 'cameraMute', callback: AsyncCallback): void - -Listens for camera mute status changes. This API uses an asynchronous callback to return the result. - -This is a system API. - -**Required permissions**: ohos.permission.CAMERA - -**System capability**: SystemCapability.Multimedia.Camera.Core +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------ | +| zoomRatio | number | Yes | Zoom ratio.| -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status change event.| -| callback | AsyncCallback | Yes | Callback used to return the camera mute status. | +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| **Example** ```js -cameraManager.on('cameraMute', (err, status) => { - if (err) { - console.error(`Failed to get cameraMute callback. ${err.message}`); - return; - } - console.log(`status: ${status}`); +cameraInput.setZoomRatio(1).then(() => { + console.log('Promise returned with the successful execution of setZoomRatio.'); }) ``` -## CameraStatusInfo - -Describes the camera status information. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Description | -| ------ | ----------------------------- | ---------- | -| camera | [CameraDevice](#cameradevice) | Camera object.| -| status | [CameraStatus](#camerastatus) | Camera status.| - -## CameraPosition - -Enumerates the camera positions. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| --------------------------- | ---- | -------------- | -| CAMERA_POSITION_UNSPECIFIED | 0 | Unspecified position. | -| CAMERA_POSITION_BACK | 1 | Rear camera. | -| CAMERA_POSITION_FRONT | 2 | Front camera. | - -## CameraType - -Enumerates the camera types. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ----------------------- | ---- | -------------- | -| CAMERA_TYPE_UNSPECIFIED | 0 | Unspecified camera type. | -| CAMERA_TYPE_WIDE_ANGLE | 1 | Wide camera. | -| CAMERA_TYPE_ULTRA_WIDE | 2 | Ultra wide camera. | -| CAMERA_TYPE_TELEPHOTO | 3 | Telephoto camera. | -| CAMERA_TYPE_TRUE_DEPTH | 4 | Camera with depth of field information.| - -## ConnectionType - -Enumerates the camera connection types. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ---------------------------- | ---- | ------------- | -| CAMERA_CONNECTION_BUILT_IN | 0 | Built-in camera. | -| CAMERA_CONNECTION_USB_PLUGIN | 1 | Camera connected using USB.| -| CAMERA_CONNECTION_REMOTE | 2 | Remote camera.| - -## CameraDevice - -Defines the camera device information. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Read only| Description | -| -------------- | --------------------------------- | ---- | ---------- | -| cameraId | string | Yes | **CameraDevice** object.| -| cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | -| cameraType | [CameraType](#cameratype) | Yes | Camera type. | -| connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type.| - -**Example** - -```js -async function getCameraInfo("cameraId") { - let cameraManager = await camera.getCameraManager(context); - let cameras = await cameraManager.getSupportedCameras(); - let cameraObj = cameras[0]; - let cameraId = cameraObj.cameraId; - let cameraPosition = cameraObj.cameraPosition; - let cameraType = cameraObj.cameraType; - let connectionType = cameraObj.connectionType; -} -``` - -## Size - -Enumerates the camera output capability. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Readable| Writable| Description | -| ------ | ------ | ---- | ---- | ------------ | -| height | number | Yes | Yes | Image height, in pixels.| -| width | number | Yes | Yes | Image width, in pixels.| - -## Point - -Enumerates the point coordinates, which are used for focus and exposure configuration. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ------------ | -| x | number | Yes | X coordinate of a point. | -| y | number | Yes | Y coordinate of a point. | - -## CameraFormat - -Enumerates the camera output formats. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Default Value | Description | -| ----------------------- | --------- | ------------ | -| CAMERA_FORMAT_YUV_420_SP| 1003 | YUV 420 SP image. | -| CAMERA_FORMAT_JPEG | 2000 | JPEG image. | - -## CameraInput - -Provides camera information used in **[CaptureSession](#capturesession)**. - -### open +### getZoomRatio -open\(callback: AsyncCallback\): void +getZoomRatio(callback: AsyncCallback): void -Opens this camera. This API uses an asynchronous callback to return the result. +Obtains the zoom ratio in use. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraInput.open((err) => { +cameraInput.getZoomRatio((err, zoomRatio) => { if (err) { - console.error(`Failed to open the camera. ${err.message}`); + console.error('Failed to get the zoom ratio ${err.message}'); return; } - console.log('Callback returned with camera opened.'); + console.log('Callback returned with current zoom ratio: ' + zoomRatio); }) ``` -### open +### getZoomRatio -open(): Promise +getZoomRatio(): Promise -Opens this camera. This API uses a promise to return the result. +Obtains the zoom ratio in use. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | ----------------------- | -| Promise| Promise used to return the result.| +| Type | Description | +| ---------------- | --------------------------- | +| Promise | Promise used to return the zoom ratio.| **Example** ```js -cameraInput.open().then(() => { - console.log('Promise returned with camera opened.'); +cameraInput.getZoomRatio().then((zoomRatio) => { + console.log('Promise returned with current zoom ratio : ' + zoomRatio); }) ``` -### close +### release -close\(callback: AsyncCallback\): void +release\(callback: AsyncCallback\): void -Closes this camera. This API uses an asynchronous callback to return the result. +Releases this **CameraInput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraInput.close((err) => { +cameraInput.release((err) => { if (err) { - console.error(`Failed to close the cameras. ${err.message}`); + console.error('Failed to release the CameraInput instance ${err.message}'); return; } - console.log('Callback returned with camera closed.'); -}) + console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); +}); ``` -### close +### release -close(): Promise +release(): Promise -Closes this camera. This API uses a promise to return the result. +Releases this **CameraInput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | ----------------------- | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| **Example** ```js -cameraInput.close().then(() => { - console.log('Promise returned with camera closed.'); +cameraInput.release().then(() => { + console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); }) ``` -### release +### on('focusStateChange') -release\(callback: AsyncCallback\): void +on(type: 'focusStateChange', callback: AsyncCallback): void -Releases this camera. This API uses an asynchronous callback to return the result. +Listens for focus state changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -cameraInput.release((err) => { - if (err) { - console.error(`Failed to release the CameraInput instance ${err.message}`); - return; - } - console.log('Callback invoked to indicate that the CameraInput instance is released successfully.'); -}); -``` - -### release - -release(): Promise - -Releases this camera. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| -------------- | ----------------------- | -| Promise| Promise used to return the result.| +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------- | :--- | :------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**, indicating the focus state change event.| +| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. | **Example** ```js -cameraInput.release().then(() => { - console.log('Promise returned to indicate that the CameraInput instance is released successfully.'); +cameraInput.on('focusStateChange', (focusState) => { + console.log('Focus state : ' + focusState); }) ``` @@ -1234,42 +1032,37 @@ Listens for **CameraInput** errors. This API uses a callback to return the resul **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------- | ---- | ------------------------------------------- | +| Name | Type | Mandatory| Description | +| :------- | :------------------------------- | :--- | :----------------------------------------------- | | type | string | Yes | Event type. The value is fixed at **'error'**, indicating the camera input error event.| -| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the result. | +| callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the result. | **Example** ```js cameraInput.on('error', (cameraInputError) => { - console.log(`Camera input error code: ${cameraInputError.code}`); + console.log('Camera input error code: ' + cameraInputError.code); }) ``` -## CameraInputErrorCode +## CameraInputErrorCode -Enumerates the error codes used for camera input. +Enumerates the error codes used in a **CameraInput** instance. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------- | ---- | ---------- | -| ERROR_UNKNOWN | -1 | Unknown error.| -| ERROR_NO_PERMISSION | 0 | You do not have the required permission.| -| ERROR_DEVICE_PREEMPTED | 1 | The camera is preempted.| -| ERROR_DEVICE_DISCONNECTED | 2 | The camera is disconnected.| -| ERROR_DEVICE_IN_USE | 3 | The camera is in use.| -| ERROR_DRIVER_ERROR | 4 | Driver error. | +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -## CameraInputError +## CameraInputError -Defines an error object used for **[CameraInput](#camerainput)**. +Defines a **CameraInput** error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | --------------------------------------------- | --------------------- | +| Name| Type | Description | +| ---- | ------------------------------------------- | -------------------------- | | code | [CameraInputErrorCode](#camerainputerrorcode) | **CameraInput** error code.| @@ -1279,37 +1072,25 @@ Enumerates the flash modes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ---------------------- | ---- | ---------- | +| Name | Value | Description | +| ---------------------- | ---- | ------------ | | FLASH_MODE_CLOSE | 0 | The flash is off.| | FLASH_MODE_OPEN | 1 | The flash is on.| | FLASH_MODE_AUTO | 2 | The flash mode is auto, indicating that the flash fires automatically depending on the shooting conditions.| | FLASH_MODE_ALWAYS_OPEN | 3 | The flash is steady on.| -## ExposureMode - -Enumerates the exposure modes. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ----------------------------- | ---- | ----------- | -| EXPOSURE_MODE_LOCKED | 0 | Exposure locked.| -| EXPOSURE_MODE_AUTO | 1 | Auto exposure.| -| EXPOSURE_MODE_CONTINUOUS_AUTO | 2 | Continuous auto exposure.| - ## FocusMode Enumerates the focus modes. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| -------------------------- | ---- | ------------ | +| Name | Value | Description | +| -------------------------- | ---- | ------------------ | | FOCUS_MODE_MANUAL | 0 | Manual focus. | | FOCUS_MODE_CONTINUOUS_AUTO | 1 | Continuous auto focus.| | FOCUS_MODE_AUTO | 2 | Auto focus. | -| FOCUS_MODE_LOCKED | 3 | Focus locked. | +| FOCUS_MODE_LOCKED | 3 | Focus locked. | ## FocusState @@ -1317,40 +1098,70 @@ Enumerates the focus states. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| --------------------- | ---- | --------- | -| FOCUS_STATE_SCAN | 0 | Focusing. | -| FOCUS_STATE_FOCUSED | 1 | Focused. | +| Name | Value | Description | +| --------------------- | ---- | ------------ | +| FOCUS_STATE_SCAN | 0 | Focusing. | +| FOCUS_STATE_FOCUSED | 1 | Focused.| | FOCUS_STATE_UNFOCUSED | 2 | Unfocused.| -## ExposureState +## camera.createCaptureSession + +createCaptureSession\(context: Context, callback: AsyncCallback\): void -Enumerates the exposure states. +Creates a **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------- | ---- | -------- | -| EXPOSURE_STATE_SCAN | 0 | Exposing. | -| EXPOSURE_STATE_CONVERGED | 1 | Exposure converged.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | -------------------------------------- | +| context | Context | Yes | Application context. | +| callback | AsyncCallback<[CaptureSession](#capturesession)\> | Yes | Callback used to return the **CaptureSession** instance.| + +**Example** + +```js +camera.createCaptureSession((context), (err, captureSession) => { + if (err) { + console.error('Failed to create the CaptureSession instance. ${err.message}'); + return; + } + console.log('Callback returned with the CaptureSession instance.' + captureSession); +}); +``` + +## camera.createCaptureSession -## VideoStabilizationMode +createCaptureSession(context: Context\): Promise; -Enumerates the video stabilization modes. +Creates a **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| --------- | ---- | ------------ | -| OFF | 0 | Video stabilization is disabled. | -| LOW | 1 | The basic video stabilization algorithm is used. | -| MIDDLE | 2 | A video stabilization algorithm with a stabilization effect better than that of the **LOW** type is used. | -| HIGH | 3 | A video stabilization algorithm with a stabilization effect better than that of the **MIDDLE** type is used. | -| AUTO | 4 | Automatic video stabilization is used. | +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------ | +| context | Context | Yes | Application context.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------------------- | +| Promise<[CaptureSession](#capturesession)\> | Promise used to return the **CaptureSession** instance.| + +**Example** + +```js +camera.createCaptureSession(context).then((captureSession) => { + console.log('Promise returned with the CaptureSession instance'); +}) +``` ## CaptureSession -Implements a shooting session, which saves all **[CameraInput](#camerainput)** and **[CameraOutput](#cameraoutput)** instances required to run the camera and requests the camera to complete shooting or video recording. +Implements a shooting session. ### beginConfig @@ -1362,8 +1173,8 @@ Starts configuration for this **CaptureSession** instance. This API uses an asyn **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------- | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1371,7 +1182,7 @@ Starts configuration for this **CaptureSession** instance. This API uses an asyn ```js captureSession.beginConfig((err) => { if (err) { - console.error(`Failed to start the configuration. ${err.message}`); + console.error('Failed to start the configuration. ${err.message}'); return; } console.log('Callback invoked to indicate the begin config success.'); @@ -1388,8 +1199,8 @@ Starts configuration for this **CaptureSession** instance. This API uses a promi **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| @@ -1411,8 +1222,8 @@ Commits the configuration for this **CaptureSession** instance. This API uses an **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1420,7 +1231,7 @@ Commits the configuration for this **CaptureSession** instance. This API uses an ```js captureSession.commitConfig((err) => { if (err) { - console.error(`Failed to commit the configuration. ${err.message}`); + console.error('Failed to commit the configuration. ${err.message}'); return; } console.log('Callback invoked to indicate the commit config success.'); @@ -1437,8 +1248,8 @@ Commits the configuration for this **CaptureSession** instance. This API uses a **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| **Example** @@ -1449,529 +1260,546 @@ captureSession.commitConfig().then(() => { }) ``` -### canAddInput +### addInput -canAddInput(cameraInput: CameraInput, callback: AsyncCallback): void +addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -Checks whether a **[CameraInput](#camerainput)** instance can be added to this **CaptureSession**. This API uses an asynchronous callback to return the result. +Adds a **CameraInput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | | cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.canAddInput(cameraInput, (err, status) => { +captureSession.addInput(cameraInput, (err) => { if (err) { - console.error(`Can not add cameraInput. ${err.message}`); + console.error('Failed to add the CameraInput instance. ${err.message}'); return; } - console.log('Callback returned with cameraInput can added.'); -}) + console.log('Callback invoked to indicate that the CameraInput instance is added.'); +}); ``` -### canAddInput +### addInput -canAddInput(cameraInput: CameraInput): Promise +addInput\(cameraInput: CameraInput\): Promise -Checks whether a **[CameraInput](#camerainput)** instance can be added to this **CaptureSession**. This API uses a promise to return the result. +Adds a **CameraInput** instance to this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | ------------------------ | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | | cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| **Return value** -| Type | Description | -| -------------- | -------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| **Example** ```js -captureSession.canAddInput(cameraInput).then(() => { - console.log('Promise returned with cameraInput can added.'); +captureSession.addInput(cameraInput).then(() => { + console.log('Promise used to indicate that the CameraInput instance is added.'); }) ``` -### addInput +### addOutput -addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void +addOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void -Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This API uses an asynchronous callback to return the result. +Adds a **PreviewOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | ------------------------ | -| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ----------------------------- | +| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.addInput(cameraInput, (err) => { +captureSession.addOutput(previewOutput, (err) => { if (err) { - console.error(`Failed to add the CameraInput instance. ${err.message}`); + console.error('Failed to add the PreviewOutput instance ${err.message}'); return; } - console.log('Callback invoked to indicate that the CameraInput instance is added.'); + console.log('Callback invoked to indicate that the PreviewOutput instance is added.'); }); ``` -### addInput +### addOutput -addInput\(cameraInput: CameraInput\): Promise +addOutput\(previewOutput: PreviewOutput\): Promise -Adds a **[CameraInput](#camerainput)** instance to this **CaptureSession**. This API uses a promise to return the result. +Adds a **PreviewOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | ------------------------ | -| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to add.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ----------------------------- | +| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| **Example** ```js -captureSession.addInput(cameraInput).then(() => { - console.log('Promise used to indicate that the CameraInput instance is added.'); +captureSession.addOutput(previewOutput).then(() => { + console.log('Promise used to indicate that the PreviewOutput instance is added.'); }) ``` -### removeInput +### addOutput -removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void +addOutput\(photoOutput: PhotoOutput, callback: AsyncCallback\): void -Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. This API uses an asynchronous callback to return the result. +Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | ------------------------ | -| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to add.| | callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.removeInput(cameraInput, (err) => { +captureSession.addOutput(photoOutput, (err) => { if (err) { - console.error(`Failed to remove the CameraInput instance. ${err.message}`); + console.error('Failed to add the PhotoOutput instance ${err.message}'); return; } - console.log('Callback invoked to indicate that the cameraInput instance is removed.'); + console.log('Callback invoked to indicate that the PhotoOutput instance is added.'); }); ``` -### removeInput +### addOutput -removeInput\(cameraInput: CameraInput\): Promise +addOutput\(photoOutput: PhotoOutput\): Promise -Removes a **[CameraInput](#camerainput)** instance from this **CaptureSession**. This API uses a promise to return the result. +Adds a **PhotoOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | ------------------------ | -| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to add.| **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | --------------------------- | +| Promise\ | Promise used to return the result.| **Example** ```js -captureSession.removeInput(cameraInput).then(() => { - console.log('Promise returned to indicate that the cameraInput instance is removed.'); +captureSession.addOutput(photoOutput).then(() => { + console.log('Promise used to indicate that the PhotoOutput instance is added.'); }) ``` -### canAddOutput +### addOutput -canAddOutput(cameraOutput: CameraOutput, callback: AsyncCallback\): void +addOutput\(videoOutput: VideoOutput, callback: AsyncCallback\): void -Checks whether a **[CameraOutput](#cameraoutput)** instance can be added to this **CaptureSession**. This API uses an asynchronous callback to return the result. +Adds a **VideoOutput** instance to this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to add.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.canAddOutput(cameraOutput, (err, status) => { +captureSession.addOutput(videoOutput, (err) => { if (err) { - console.error(`Can not add cameraOutput. ${err.message}`); + console.error('Failed to add the VideoOutput instance ${err.message}'); return; } - console.log('Callback returned with cameraOutput can added.'); -}) + console.log('Callback invoked to indicate that the VideoOutput instance is added.'); +}); ``` -### canAddOutput +### addOutput -canAddOutput(cameraOutput: CameraOutput): Promise +addOutput\(videoOutput: VideoOutput\): Promise -Checks whether a **[CameraOutput](#cameraoutput)** instance can be added to this **CaptureSession**. This API uses a promise to return the result. +Adds a **VideoOutput** instance to this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| - +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to add.| **Return value** -| Type | Description | +| Type | Description | | -------------- | --------------------------- | -| Promise | Promise used to return the result.| - +| Promise\ | Promise used to return the result.| **Example** ```js -captureSession.canAddOutput(cameraOutput).then(() => { - console.log('Promise returned with cameraOutput can added.'); +captureSession.addOutput(videoOutput).then(() => { + console.log('Promise used to indicate that the VideoOutput instance is added.'); }) ``` -### addOutput +### removeInput -addOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void +removeInput\(cameraInput: CameraInput, callback: AsyncCallback\): void -Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. This API uses an asynchronous callback to return the result. +Removes a **CameraInput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ------------------------ | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.addOutput(cameraOutput, (err) => { +captureSession.removeInput(cameraInput, (err) => { if (err) { - console.error(`Failed to add output. ${err.message}`); + console.error('Failed to remove the CameraInput instance. ${err.message}'); return; } - console.log('Callback returned with output added.'); -}) + console.log('Callback invoked to indicate that the cameraInput instance is removed.'); +}); ``` -### addOutput +### removeInput -addOutput\(cameraOutput: CameraOutput\): Promise +removeInput\(cameraInput: CameraInput\): Promise -Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. This API uses a promise to return the result. +Removes a **CameraInput** instance from this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| cameraInput | [CameraInput](#camerainput) | Yes | **CameraInput** instance to remove.| **Return value** -| Type | Description | -| -------------- | ----------------------- | -| Promise| Promise used to return the result.| +| Type | Description | +| -------------- | --------------------------- | +| Promise\ | Promise used to return the result.| **Example** ```js -captureSession.addOutput(cameraOutput).then(() => { - console.log('Promise returned with cameraOutput added.'); +captureSession.removeInput(cameraInput).then(() => { + console.log('Promise returned to indicate that the cameraInput instance is removed.'); }) ``` ### removeOutput -removeOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void +removeOutput\(previewOutput: PreviewOutput, callback: AsyncCallback\): void -Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession**. This API uses an asynchronous callback to return the result. +Removes a **PreviewOutput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ------------------------ | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ----------------------------- | +| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| | callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.removeOutput(cameraOutput, (err) => { +captureSession.removeOutput(previewOutput, (err) => { if (err) { - console.error(`Failed to remove the CameraOutput instance. ${err.message}`); + console.error('Failed to remove the PreviewOutput instance. ${err.message}'); return; } - console.log('Callback invoked to indicate that the CameraOutput instance is removed.'); + console.log('Callback invoked to indicate that the PreviewOutput instance is removed.'); }); ``` ### removeOutput -removeOutput(cameraOutput: CameraOutput): Promise +removeOutput(previewOutput: PreviewOutput): Promise -Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession**. This API uses a promise to return the result. +Removes a **PreviewOutput** instance from this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------- | ---- | ----------------------------- | +| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| **Example** ```js -captureSession.removeOutput(cameraOutput).then(() => { - console.log('Promise returned to indicate that the CameraOutput instance is removed.'); +captureSession.removeOutput(previewOutput).then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is removed.'); }) ``` -### start +### removeOutput -start\(callback: AsyncCallback\): void +removeOutput(photoOutput: PhotoOutput, callback: AsyncCallback): void -Starts this **CaptureSession**. This API uses an asynchronous callback to return the result. +Removes a **PhotoOutput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to remove.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.start((err) => { +captureSession.removeOutput(photoOutput, (err) => { if (err) { - console.error(`Failed to start the session ${err.message}`); + console.error('Failed to remove the PhotoOutput instance. ${err.message}'); return; } - console.log('Callback invoked to indicate the session start success.'); + console.log('Callback invoked to indicate that the PhotoOutput instance is removed.'); }); ``` -### start +### removeOutput -start\(\): Promise +removeOutput(photoOutput: PhotoOutput): Promise -Starts this **CaptureSession**. This API uses a promise to return the result. +Removes a **PhotoOutput** instance from this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| photoOutput | [PhotoOutput](#photooutput) | Yes | **PhotoOutput** instance to remove.| + + **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| + **Example** ```js -captureSession.start().then(() => { - console.log('Promise returned to indicate the session start success.'); +captureSession.removeOutput(photoOutput).then(() => { + console.log('Promise returned to indicate that the PhotoOutput instance is removed.'); }) ``` -### stop +### removeOutput -stop\(callback: AsyncCallback\): void +removeOutput(videoOutput: VideoOutput, callback: AsyncCallback): void -Stops this **CaptureSession**. This API uses an asynchronous callback to return the result. +Removes a **VideoOutput** instance from this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to remove.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.stop((err) => { +captureSession.removeOutput(videoOutput, (err) => { if (err) { - console.error(`Failed to stop the session ${err.message}`); + console.error('Failed to remove the VideoOutput instance. ${err.message}'); return; } - console.log('Callback invoked to indicate the session stop success.'); + console.log('Callback invoked to indicate that the VideoOutput instance is removed.'); }); ``` -### stop +### removeOutput -stop(): Promise +removeOutput(videoOutput: VideoOutput): Promise -Stops this **CaptureSession**. This API uses a promise to return the result. +Removes a **VideoOutput** instance from this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | --------------------------- | +| videoOutput | [VideoOutput](#videooutput) | Yes | **VideoOutput** instance to remove.| + + **Return value** -| Type | Description | -| -------------- | ----------------------- | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| + **Example** ```js -captureSession.stop().then(() => { - console.log('Promise returned to indicate the session stop success.'); +captureSession.removeOutput(videoOutput).then(() => { + console.log('Promise returned to indicate that the VideoOutput instance is removed.'); }) ``` -### lockForControl +### start -lockForControl(callback: AsyncCallback): void +start\(callback: AsyncCallback\): void -Requests to exclusively control the hardware attributes **[CameraInput](#camerainput)** of the camera device. This API uses an asynchronous callback to return the result. After the exclusive control is complete, you must call **[unlockForControl](#unlockforcontrol)** to release the exclusive control. +Starts this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------- | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -captureSession.lockForControl((err) => { +captureSession.start((err) => { if (err) { - console.error(`Failed to lock. ${err.message}`); + console.error('Failed to start the session ${err.message}'); return; } - console.log('Locked.'); -}) + console.log('Callback invoked to indicate the session start success.'); +}); ``` -### lockForControl +### start -lockForControl(): Promise +start\(\): Promise -Requests to exclusively control the hardware attributes **[CameraInput](#camerainput)** of the camera device. This API uses a promise to return the result. After the exclusive control is complete, you must call **[unlockForControl](#unlockforcontrol)** to release the exclusive control. +Starts this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| **Example** ```js -captureSession.lockForControl().then(() => { - console.log('Locked.'); +captureSession.start().then(() => { + console.log('Promise returned to indicate the session start success.'); }) ``` -### unlockForControl +### stop -unlockForControl(callback: AsyncCallback): void +stop\(callback: AsyncCallback\): void -Releases the exclusive control on the device configuration. This API uses an asynchronous callback to return the result. +Stops this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -captureSession.unlockForControl((err) => { +captureSession.stop((err) => { if (err) { - console.error(`Failed to unlock. ${err.message}`); + console.error('Failed to stop the session ${err.message}'); return; } - console.log('Unlocked.'); -}) + console.log('Callback invoked to indicate the session stop success.'); +}); ``` -### unlockForControl +### stop -unlockForControl(): Promise +stop(): Promise -Releases the exclusive control on the device configuration. This API uses a promise to return the result. +Stops this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| **Example** ```js -captureSession.unlockForControl().then(() => { - console.log('Unlocked.'); +captureSession.stop().then(() => { + console.log('Promise returned to indicate the session stop success.'); }) ``` @@ -1979,14 +1807,14 @@ captureSession.unlockForControl().then(() => { release\(callback: AsyncCallback\): void -Releases this **CaptureSession**. This API uses an asynchronous callback to return the result. +Releases this **CaptureSession** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** @@ -1994,7 +1822,7 @@ Releases this **CaptureSession**. This API uses an asynchronous callback to retu ```js captureSession.release((err) => { if (err) { - console.error(`Failed to release the CaptureSession instance ${err.message}`); + console.error('Failed to release the CaptureSession instance ${err.message}'); return; } console.log('Callback invoked to indicate that the CaptureSession instance is released successfully.'); @@ -2005,14 +1833,14 @@ captureSession.release((err) => { release(): Promise -Releases this **CaptureSession**. This API uses a promise to return the result. +Releases this **CaptureSession** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| **Example** @@ -2023,2077 +1851,433 @@ captureSession.release().then(() => { }) ``` -### hasFlash +### on('error') -hasFlash(callback: AsyncCallback): void +on(type: 'error', callback: ErrorCallback): void -Checks whether the device has flash. This API uses an asynchronous callback to return the result. +Listens for **CaptureSession** errors. This API uses a callback to return the errors. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the flash support status. The value **true** means that the device has flash.| +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------------------------- | :--- | :-------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the capture session error event.| +| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | Yes | Callback used to return the error information. | **Example** ```js -cameraInput.hasFlash((err, status) => { - if (err) { - console.error(`Failed to check whether the device has flash light. ${err.message}`); - return; - } - console.log(`Callback returned with flash light support status: ${status}`); +captureSession.on('error', (captureSessionError) => { + console.log('Capture session error code: ' + captureSessionError.code); }) ``` -### hasFlash - -hasFlash(): Promise +## CaptureSessionErrorCode -Checks whether the device has flash. This API uses a promise to return the result. +Enumerates the error codes used in a **CaptureSession** instance. **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -| Type | Description | -| ----------------- | ----------------------------------------------- | -| Promise | Promise used to return the flash support status. The value **true** means that the device has flash.| +## CaptureSessionError -**Example** +Defines a **CaptureSession** error. -```js -cameraInput.hasFlash().then((status) => { - console.log(`Promise returned with the flash light support status: ${status}`); -}) -``` +**System capability**: SystemCapability.Multimedia.Camera.Core -### isFlashModeSupported +| Name| Type | Description | +| ---- | ------------------------------------------- | -------------------------- | +| code | [CaptureSessionError](#capturesessionerror) | **CaptureSession** error code.| -isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): void +## camera.createPreviewOutput -Checks whether a specified flash mode is supported. This API uses an asynchronous callback to return the result. +createPreviewOutput(surfaceId: string, callback: AsyncCallback): void + +Creates a **PreviewOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | --------------------------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | -| callback | AsyncCallback | Yes | Callback used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| --------- | ----------------------------------------------- | ---- | ------------------------------------- | +| surfaceId | string | Yes | Surface ID, which is obtained from **XComponent**. | +| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.| **Example** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { +camera.createPreviewOutput(("surfaceId"), (err, previewOutput) => { if (err) { - console.error(`Failed to check whether the flash mode is supported. ${err.message}`); + console.error('Failed to create the PreviewOutput instance. ${err.message}'); return; } - console.log(`Callback returned with the flash mode support status: ${status}`); -}) + console.log('Callback returned with previewOutput instance'); +}); ``` -### isFlashModeSupported +## camera.createPreviewOutput -isFlashModeSupported(flashMode: FlashMode): Promise +createPreviewOutput(surfaceId: string): Promise\ -Checks whether a specified flash mode is supported. This API uses a promise to return the result. +Creates a **PreviewOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------------------------- | +| surfaceId | string | Yes | Surface ID, which is obtained from **XComponent**.| **Return value** -| Type | Description | -| ----------------- | ---------------------------------------------------- | -| Promise | Promise used to return the flash mode support status. The value **true** means that the flash mode is supported, and **false** means the opposite.| +| Type | Description | +| ----------------------------------------- | --------------------------- | +| Promise<[PreviewOutput](#previewoutput)\> | Promise used to return the result.| **Example** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { - console.log(`Promise returned with flash mode support status.${status}`); +camera.createPreviewOutput("surfaceId").then((previewOutput) => { + console.log('Promise returned with the PreviewOutput instance'); }) ``` -### setFlashMode +## PreviewOutput -setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void +Implements preview output. -Sets the flash mode. This API uses an asynchronous callback to return the result. +### release -Before the setting, do the following checks: +release(callback: AsyncCallback): void -1. Use **[hasFlash](#hasflash)** to check whether the device has flash. -2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. +Releases this **PreviewOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | --------------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode. | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { +previewOutput.release((err) => { if (err) { - console.error(`Failed to set the flash mode ${err.message}`); + console.error('Failed to release the PreviewOutput instance ${err.message}'); return; } - console.log('Callback returned with the successful execution of setFlashMode.'); -}) + console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); +}); ``` -### setFlashMode - -setFlashMode(flashMode: FlashMode): Promise - -Sets a flash mode. This API uses a promise to return the result. +### release -Before the setting, do the following checks: +release(): Promise -1. Use **[hasFlash](#hasflash)** to check whether the device has flash. -2. Use **[isFlashModeSupported](#isflashmodesupported)** to check whether the device supports the flash mode. +Releases this **PreviewOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ------------- | -| flashMode | [FlashMode](#flashmode) | Yes | Flash mode.| - **Return value** -| Type | Description | -| -------------- | ------------------------ | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| + **Example** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFlashMode.'); +previewOutput.release().then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); }) ``` -### getFlashMode +### on('frameStart') -getFlashMode(callback: AsyncCallback): void +on(type: 'frameStart', callback: AsyncCallback): void -Obtains the flash mode in use. This API uses an asynchronous callback to return the result. +Listens for preview frame start events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | --------------------------------- | -| callback | AsyncCallback<[FlashMode](#flashmode)\> | Yes | Callback used to return the flash mode.| +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'frameStart'**, indicating the preview frame start event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -cameraInput.getFlashMode((err, flashMode) => { - if (err) { - console.error(`Failed to get the flash mode ${err.message}`); - return; - } - console.log(`Callback returned with current flash mode: ${flashMode}`); +previewOutput.on('frameStart', () => { + console.log('Preview frame started'); }) ``` -### getFlashMode +### on('frameEnd') -getFlashMode(): Promise +on(type: 'frameEnd', callback: AsyncCallback): void -Obtains the flash mode in use. This API uses a promise to return the result. +Listens for preview frame end events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** +**Parameters** -| Type | Description | -| --------------------------------- | --------------------------------- | -| Promise<[FlashMode](#flashmode)\> | Promise used to return the flash mode.| +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'frameEnd'**, indicating the preview frame end event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -cameraInput.getFlashMode().then((flashMode) => { - console.log(`Promise returned with current flash mode : ${flashMode}`); +previewOutput.on('frameEnd', () => { + console.log('Preview frame ended'); }) ``` -### isExposureModeSupported +### on('error') -isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback): void; +on(type: 'error', callback: ErrorCallback): void -Checks whether a specified exposure mode is supported. This API uses an asynchronous callback to return the result. +Listens for **PreviewOutput** errors. This API uses a callback to return the errors. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------| ---- | ----------------------------- | -| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | -| callback | AsyncCallback | Yes | Callback used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| :------- | :----------------------------------------------------------- | :--- | :-------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the preview output error event.| +| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | Yes | Callback used to return the error information. | **Example** ```js -cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { - if (err) { - console.log(`Failed to check exposure mode supported ${err.message}`); - return ; - } - console.log('Callback returned with the successful excution of isExposureModeSupported'); +previewOutput.on('error', (previewOutputError) => { + console.log('Preview output error code: ' + previewOutputError.code); }) ``` -### isExposureModeSupported - -isExposureModeSupported(aeMode: ExposureMode): Promise +## PreviewOutputErrorCode -Checks whether a specified exposure mode is supported. This API uses a promise to return the result. +Enumerates the error codes used in a **PreviewOutput** instance. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------------------| ---- | ----------------------------- | -| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -**Return value** +## PreviewOutputError -| Name | Description | -| ----------------- |--------------------------------- | -| Promise | Promise used to return the exposure mode support status. The value **true** means that the exposure mode is supported, and **false** means the opposite.| +Defines a **PreviewOutput** error. -**Example** +**System capability**: SystemCapability.Multimedia.Camera.Core -```js -cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { - console.log(`Promise returned with exposure mode supported : ${isSupported}`); -}) -``` +| Name| Type | Description | +| ---- | ------------------------------------------------- | ---------------------- | +| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | **PreviewOutput** error code.| -### getExposureMode +## camera.createPhotoOutput -getExposureMode(callback: AsyncCallback): void +createPhotoOutput(surfaceId: string, callback: AsyncCallback): void -Obtains the exposure mode in use. This API uses an asynchronous callback to return the result. +Creates a **PhotoOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------| ---- | ---------------------------------------- | -| callback | AsyncCallback<[ExposureMode](#exposuremode)\> | Yes | Callback used to return the exposure mode.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------- | ---- | ----------------------------------- | +| surfaceId | string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**. | +| callback | AsyncCallback<[PhotoOutput](#photooutput)\> | Yes | Callback used to return the **PhotoOutput** instance.| **Example** ```js -cameraInput.getExposureMode((err, exposureMode) => { +camera.createPhotoOutput(("surfaceId"), (err, photoOutput) => { if (err) { - console.log(`Failed to get the exposure mode ${err.message}`); - return ; + console.error('Failed to create the PhotoOutput instance. ${err.message}'); + return; } - console.log(`Callback returned with current exposure mode: ${exposureMode}`); -}) + console.log('Callback returned with the PhotoOutput instance.'); +}); ``` -### getExposureMode +## camera.createPhotoOutput -getExposureMode(): Promise +createPhotoOutput(surfaceId: string): Promise -Obtains the exposure mode in use. This API uses a promise to return the result. +Creates a **PhotoOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------------------------------- | +| surfaceId | string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| + **Return value** -| Name | Description | -| --------------------------------------- |------------------------------- | -| Promise<[ExposureMode](#exposuremode)\> | Promise used to return the exposure mode.| +| Type | Description | +| ------------------------------------- | -------------------------------------- | +| Promise<[PhotoOutput](#photooutput)\> | Promise used to return the **PhotoOutput** instance.| **Example** ```js -cameraInput.getExposureMode().then((exposureMode) => { - console.log(`Promise returned with current exposure mode : ${exposureMode}`); +camera.createPhotoOutput("surfaceId").then((photoOutput) => { + console.log('Promise returned with PhotoOutput instance'); }) ``` +## ImageRotation -### setExposureMode - -setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void - -Sets an exposure mode. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core +Enumerates the image rotation angles. -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------| ---- | ----------------------- | -| aeMode | [ExposureMode](#exposuremode) | Yes | Exposure mode. | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { - if (err) { - console.log(`Failed to set the exposure mode ${err.message}`); - return ; - } - console.log('Callback returned with the successful excution of setExposureMode'); -}) -``` - -### setExposureMode - -setExposureMode(aeMode: ExposureMode): Promise - -Sets an exposure mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Name | Description | -| ----------------- |---------------------------- | -| Promise | Promise used to return the result.| - -**Example** - -```js -cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => { - console.log('Promise returned with the successful execution of setExposureMode.'); -}) -``` - -### getMeteringPoint - -getMeteringPoint(callback: AsyncCallback): void - -Obtains the center of the metering area. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------| ---- | ------------------------ | -| callback | AsyncCallback<[Point](#point)\>| Yes | Callback used to return the center of the metering area.| - -**Example** - -```js -cameraInput.getMeteringPoint((err, exposurePoint) => { - if (err) { - console.log(`Failed to get the current exposure point ${err.message}`); - return ; - } - console.log(`Callback returned with current exposure point: ${exposurePoint}`); -}) -``` - -### getMeteringPoint - -getMeteringPoint(): Promise - -Obtains the center of the metering area. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Name | Description | -| ------------------------- |----------------------------- | -| Promise<[Point](#point)\> | Promise used to return the center of the metering area.| - -**Example** - -```js -cameraInput.getMeteringPoint().then((exposurePoint) => { - console.log(`Promise returned with current exposure point : ${exposurePoint}`); -}) -``` - -### setMeteringPoint - -setMeteringPoint(point: Point, callback: AsyncCallback): void - -Sets the center of the metering area. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------------- | -------------------------------| ---- | ------------------- | -| exposurePoint | [Point](#point) | Yes | Exposure point. | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -const Point1 = {x: 1, y: 1}; - -cameraInput.setMeteringPoint(Point1,(err) => { - if (err) { - console.log(`Failed to set the exposure point ${err.message}`); - return ; - } - console.log('Callback returned with the successful excution of setMeteringPoint'); -}) -``` - -### setMeteringPoint - -setMeteringPoint(point: Point): Promise - -Sets the center of the metering area. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------------- | -------------------------------| ---- | ------------------- | -| exposurePoint | [Point](#point) | Yes | Exposure point. | - -**Return value** - -| Name | Description | -| ----------------- |------------------------ | -| Promise | Promise used to return the center of the metering area.| - -**Example** - -```js -const Point2 = {x: 2, y: 2}; - -cameraInput.setMeteringPoint(Point2).then(() => { - console.log('Promise returned with the successful execution of setMeteringPoint'); -}) -``` - -### getExposureBiasRange - -getExposureBiasRange(callback: AsyncCallback\>): void - -Obtains the exposure compensation values. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------| ---- | ----------------------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the array of compensation values.| - -**Example** - -```js -cameraInput.getExposureBiasRange((err, biasRangeArray) => { - if (err) { - console.log(`Failed to get the array of compenstation range ${err.message}`); - return ; - } - console.log('Callback returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); -}) -``` - -### getExposureBiasRange - -getExposureBiasRange(): Promise\> - -Obtains the exposure compensation values. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Name | Description | -| ----------------- |-------------------------------------- | -| Promise\> | Promise used to return the array of compensation values.| - -**Example** - -```js -cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { - console.log(`Promise returned with exposure mode supported : ${isSupported}`); -}) -``` - -### setExposureBias - -setExposureBias(exposureBias: number, callback: AsyncCallback): void - -Sets an exposure compensation value. This API uses an asynchronous callback to return the result. - -Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------| ---- | ------------------- | -| exposureBias | number | Yes | Compensation value. | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -cameraInput.setExposureBias(-4,(err) => { - if (err) { - console.log(`Failed to set the exposure bias ${err.message}`); - return ; - } - console.log('Callback returned with the successful excution of setExposureBias'); -}) -``` - -### setExposureBias - -setExposureBias(exposureBias: number): Promise - -Sets an exposure compensation value. This API uses a promise to return the result. - -Before the setting, you are advised to use **[getExposureBiasRange](#getexposurebiasrange)** to obtain the supported values. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | --------- | ---- | --------- | -| exposureBias | number | Yes | Compensation value. | - -**Return value** - -| Name | Description | -| ----------------- |------------------------- | -| Promise | Promise used to return the result.| - -**Example** - -```js -cameraInput.setExposureBias(-4).then(() => { - console.log('Promise returned with the successful execution of setExposureBias.'); -}) -``` - -### getExposureValue - -getExposureValue(callback: AsyncCallback): void - -Obtains the exposure value in use. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------| ---- | --------------------- | -| callback | AsyncCallback | Yes | Callback used to the exposure value.| - -**Example** - -```js -cameraInput.getExposureValue((err, exposureValue) => { - if (err) { - console.log(`Failed to get the exposure value ${err.message}`); - return ; - } - console.log(`Callback returned with the exposure value: ${exposureValue}`); -}) -``` - -### getExposureValue - -getExposureValue(): Promise - -Obtains the exposure value in use. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Name | Description | -| ----------------- |-------------------------- | -| Promise | Promise used to the exposure value.| - -**Example** - -```js -cameraInput.getExposureValue().then((exposureValue) => { - console.log(`Promise returned with exposure value: ${exposureValude}`); -}) -``` - -### isFocusModeSupported - -isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void - -Checks whether a specified focus mode is supported. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | -| callback | AsyncCallback | Yes | Callback used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.| - -**Example** - -```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { - if (err) { - console.error(`Failed to check whether the focus mode is supported. ${err.message}`); - return; - } - console.log(`Callback returned with the focus mode support status: ${status}`); -}) -``` - -### isFocusModeSupported - -isFocusModeSupported(afMode: FocusMode): Promise - -Checks whether a specified focus mode is supported. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------ | ----------------------- | ---- | ------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| - -**Return value** - -| Type | Description | -| ----------------- | --------------------------------------------------- | -| Promise | Promise used to return the focus mode support status. The value **true** means that the focus mode is supported, and **false** means the opposite.| - -**Example** - -```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { - console.log(`Promise returned with focus mode support status ${status}.`); -}) -``` - -### setFocusMode - -setFocusMode(afMode: FocusMode, callback: AsyncCallback): void - -Sets a focus mode. This API uses an asynchronous callback to return the result. - -Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode. | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { - if (err) { - console.error(`Failed to set the focus mode ${err.message}`); - return; - } - console.log('Callback returned with the successful execution of setFocusMode.'); -}) -``` - -### setFocusMode - -setFocusMode(afMode: FocusMode): Promise - -Sets a focus mode. This API uses a promise to return the result. - -Before the setting, use **[isFocusModeSupported](#isfocusmodesupported)** to check whether the focus mode is supported. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------ | ----------------------- | ---- | ------------- | -| afMode | [FocusMode](#focusmode) | Yes | Focus mode.| - -**Return value** - -| Type | Description | -| -------------- | ------------------------ | -| Promise| Promise used to return the result.| - -**Example** - -```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { - console.log('Promise returned with the successful execution of setFocusMode.'); -}) -``` - -### getFocusMode - -getFocusMode(callback: AsyncCallback): void - -Obtains the focus mode in use. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------- | ---- | ------------------------------- | -| callback | AsyncCallback<[FocusMode](#focusmode)\> | Yes | Callback used to return the focus mode.| - -**Example** - -```js -cameraInput.getFocusMode((err, afMode) => { - if (err) { - console.error(`Failed to get the focus mode ${err.message}`); - return; - } - console.log(`Callback returned with current focus mode: ${afMode}`); -}) -``` - -### getFocusMode - -getFocusMode(): Promise - -Obtains the focus mode in use. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ------------------- | -------------------------------- | -| Promise | Promise used to return the focus mode.| - -**Example** - -```js -cameraInput.getFocusMode().then((afMode) => { - console.log(`Promise returned with current focus mode : ${afMode}`); -}) -``` - -### setFocusPoint - -setFocusPoint(point: Point, callback: AsyncCallback): void - -Sets a focus point. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------- | -| point | [Point](#point) | Yes | Focus point. | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -const Point1 = {x: 1, y: 1}; - -cameraInput.setFocusPoint(Point1, (err) => { - if (err) { - console.error(`Failed to set the focus point ${err.message}`); - return; - } - console.log('Callback returned with the successful execution of setFocusPoint.'); -}) -``` - -### setFocusPoint - -setFocusPoint(point: Point): Promise - -Sets a focal point. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | ------------------- | -| point | [Point](#point) | Yes | Focal point. | - -**Return value** - -| Type | Description | -| -------------- | ----------------------- | -| Promise| Promise used to return the result.| - -**Example** - -```js -const Point2 = {x: 2, y: 2}; - -cameraInput.setFocusPoint(Point2).then(() => { - console.log('Promise returned with the successful execution of setFocusPoint.'); -}) -``` - -### getFocusPoint - -getFocusPoint(callback: AsyncCallback): void - -Obtains the focal point. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------- | ---- | ----------------------- | -| callback | AsyncCallback<[Point](#point)\> | Yes | Callback used to return the focal point.| - -**Example** - -```js -cameraInput.getFocusPoint((err, point) => { - if (err) { - console.error(`Failed to get the current focus point ${err.message}`); - return; - } - console.log('Callback returned with the current focus point: ' + JSON.stringify(point)); -}) -``` - -### getFocusPoint - -getFocusPoint(): Promise - -Obtains the focal point. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| --------------- | --------------------------- | -| Promise | Promise used to return the focal point.| - -**Example** - -```js -cameraInput.getFocusPoint().then((point) => { - console.log('Promise returned with the current focus point: ' + JSON.stringify(point)); -}) -``` - -### getFocalLength - -getFocalLength(callback: AsyncCallback): void - -Obtains the focal length. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ----------------------- | -| callback | AsyncCallback | Yes | Callback used to return the focal length.| - -**Example** - -```js -cameraInput.getFocalLength((err, focalLength) => { - if (err) { - console.error(`Failed to get the current focal length ${err.message}`); - return; - } - console.log(`Callback returned with the current focal length: ${focalLength}`); -}) -``` - -### getFocalLength - -getFocalLength(): Promise - -Obtains the focal length. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ---------------- | ----------------------- | -| Promise | Promise used to return the focal length.| - -**Example** - -```js -cameraInput.getFocalLength().then((focalLength) => { - console.log(`Promise returned with the current focal length: ${focalLength}`); -}) -``` - -### getZoomRatioRange - -getZoomRatioRange\(callback: AsyncCallback\>\): void - -Obtains the zoom ratio range. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------ | ---- | ------------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the result.| - -**Example** - -```js -cameraInput.getZoomRatioRange((err, zoomRatioRange) => { - if (err) { - console.error(`Failed to get the zoom ratio range. ${err.message}`); - return; - } - console.log(`Callback returned with zoom ratio range: ${zoomRatioRange.length}`); -}) -``` - -### getZoomRatioRange - -getZoomRatioRange\(\): Promise\> - -Obtains the zoom ratio range. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ------------------------ | --------------------------- | -| Promise\> | Promise used to return the zoom ratio range.| - -**Example** - -```js -cameraInput.getZoomRatioRange().then((zoomRatioRange) => { - console.log(`Promise returned with zoom ratio range: ${zoomRatioRange.length}`); -}) -``` - -### setZoomRatio - -setZoomRatio(zoomRatio: number, callback: AsyncCallback): void - -Sets a zoom ratio. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | -------------------- | ---- | ------------------- | -| zoomRatio | number | Yes | Zoom ratio. | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -cameraInput.setZoomRatio(1, (err) => { - if (err) { - console.error(`Failed to set the zoom ratio value ${err.message}`); - return; - } - console.log('Callback returned with the successful execution of setZoomRatio.'); -}) -``` - -### setZoomRatio - -setZoomRatio(zoomRatio: number): Promise - -Sets a zoom ratio. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | --------- | -| zoomRatio | number | Yes | Zoom ratio.| - -**Return value** - -| Type | Description | -| -------------- | ----------------------- | -| Promise| Promise used to return the result.| - -**Example** - -```js -cameraInput.setZoomRatio(1).then(() => { - console.log('Promise returned with the successful execution of setZoomRatio.'); -}) -``` - -### getZoomRatio - -getZoomRatio(callback: AsyncCallback): void - -Obtains the zoom ratio in use. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -cameraInput.getZoomRatio((err, zoomRatio) => { - if (err) { - console.error(`Failed to get the zoom ratio ${err.message}`); - return; - } - console.log(`Callback returned with current zoom ratio: ${zoomRatio}`); -}) -``` - -### getZoomRatio - -getZoomRatio(): Promise - -Obtains the zoom ratio in use. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ---------------- | ----------------------- | -| Promise | Promise used to return the zoom ratio.| - -**Example** - -```js -cameraInput.getZoomRatio().then((zoomRatio) => { - console.log(`Promise returned with current zoom ratio : ${zoomRatio}`); -}) -``` - -### isVideoStablizationModeSupported - -isVideoStablizationModeSupported(vsMode: VideoStabilizationMode, callback: AsyncCallback): void - -Checks whether the specified video stabilization mode is supported. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------------ | -| vsMode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | -| callback | AsyncCallback | Yes | Callback used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite. | - -**Example** - -```js -captureSession.isVideoStablizationModeSupported(camera.VideoStabilizationMode.OFF, (err, isSupported) => { - if (err) { - console.error(`Failed to check whether video stabilization mode supported. ${err.message}`); - return; - } - console.log(`Callback returned with the successful execution of isVideoStabilizationModeSupported: ${status}`); -}) -``` - -### isVideoStablizationModeSupported - -isVideoStablizationModeSupported(vsMode: VideoStabilizationMode): Promise - -Checks whether the specified video stabilization mode is supported. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ----------------- | --------------------------------------------- | -| Promise | Promise used to return whether the video stabilization mode is supported. The value **true** means that the video stabilization mode is supported, and **false** means the opposite.| - -**Example** - -```js -captureSession.isVideoStablizationModeSupported(camera.VideoStabilizationMode.OFF).then((isSupported) => { - console.log(`Promise returned with video stabilization mode supported: ${isSupported}`); -}) -``` - -### getActiveVideoStabilizationMode - -getActiveVideoStabilizationMode(callback: AsyncCallback): void - -Obtains the video stabilization mode in use. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the video stabilization mode. | - -**Example** - -```js -captureSession.getActiveVideoStabilizationMode((err, vsMode) => { - if (err) { - console.error(`Failed to get active video stabilization mode ${err.message}`); - return; - } - console.log('Callback returned with the successful execution of getActiveVideoStabilizationMode.'); -}) -``` - -### getActiveVideoStabilizationMode - -getActiveVideoStabilizationMode(): Promise - -Obtains the video stabilization mode in use. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| -------------------------------- | ------------------------------------------------- | -| Promise | Promise used to return the video stabilization mode. | - -**Example** - -```js -captureSession.getActiveVideoStabilizationMode().then((vsMode) => { - console.log(`Promise returned with the current video stabilization mode: ${vsMode}`); -}) -``` - -### setVideoStabilizationMode - -setVideoStabilizationMode(mode: VideoStabilizationMode, callback: AsyncCallback): void - -Sets a video stabilization mode. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | --------------------- | -| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | -| callback | AsyncCallback | Yes | Callback used to return the result. | - -**Example** - -```js -captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF, (err) => { - if (err) { - console.error(`Failed to set the video stabilization mode ${err.message}`); - return; - } - console.log('Callback returned with the successful execution of setVideoStabilizationMode.'); -}) -``` - -### setVideoStabilizationMode - -setVideoStabilizationMode(mode: VideoStabilizationMode): Promise - -Sets a video stabilization mode. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | --------------------- | -| mode | [VideoStabilizationMode](#videostabilizationmode) | Yes | Video stabilization mode. | - -**Return value** - -| Type | Description | -| -------------- | ------------------------------------------------- | -| Promise| Promise used to return the result. | - -**Example** - -```js -captureSession.setVideoStabilizationMode(camera.VideoStabilizationMode.OFF).then(() => { - console.log('Promise returned with the successful execution of setVideoStabilizationMode.'); -}) -``` - -### on('focusStateChange') - -on(type: 'focusStateChange', callback: AsyncCallback): void - -Listens for focus state changes. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------ | -| type | string | Yes | Event type. The value is fixed at **'focusStateChange'**, indicating the focus state change event.| -| callback | AsyncCallback<[FocusState](#focusstate)\> | Yes | Callback used to return the focus state change. | - -**Example** - -```js -cameraInput.on('focusStateChange', (focusState) => { - console.log(`Focus state : ${focusState}`); -}) -``` - -### on('exposureStateChange') - -on(type: 'exposureStateChange', callback: AsyncCallback): void - -Listens for exposure state changes. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ---------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'exposureStateChange'**, indicating the exposure state change event.| -| callback | AsyncCallback<[ExposureState](#exposurestate)\> | Yes | Callback used to return the exposure state change. | - -**Example** - -```js -cameraInput.on('exposureStateChange', (exposureState) => { - console.log(`Exposuer state : ${exposureState}`); -}) -``` - -### on('error') - -on(type: 'error', callback: ErrorCallback): void - -Listens for **CaptureSession** errors. This API uses a callback to return the errors. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the capture session error event.| -| callback | ErrorCallback<[CaptureSessionError](#capturesessionerror)\> | Yes | Callback used to return the error information. | - -**Example** - -```js -captureSession.on('error', (captureSessionError) => { - console.log(`Capture session error code: ${captureSessionError.code}`); -}) -``` - -## CaptureSessionErrorCode - -Enumerates the error codes used in a **CaptureSession**. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ----------------------------- | ---- | -------- | -| ERROR_UNKNOWN | -1 | Unknown error.| -| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| -| ERROR_TIMEOUT | 1 | Timeout.| - -## CaptureSessionError - -Defines a **CaptureSession** error. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name| Type | Description | -| ---- | ------------------------------------------- | -------------------------- | -| code | [CaptureSessionError](#capturesessionerror) | **CaptureSession** error code.| - -## CameraOutput - -Implements output information used in a **[CaptureSession](#capturesession)**. It is the base class of **output**. - -### release - -release(callback: AsyncCallback): void - -Releases output resources. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -previewOutput.release((err) => { - if (err) { - console.error(`Failed to release the PreviewOutput instance ${err.message}`); - return; - } - console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); -}); -``` - -### release - -release(): Promise - -Releases output resources. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| -------------- | ----------------------- | -| Promise| Promise used to return the result.| - -**Example** - -```js -previewOutput.release().then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); -}) -``` - -## PreviewOutput - -Implements preview output. It inherits **[CameraOutput](#cameraoutput)**. - -### addDeferredSurface - -addDeferredSurface(surfaceId: string, callback: AsyncCallback): void - -Adds a surface after a **PreviewOutput** instance is created. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------------------------------------------------------- | -| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)**.| -| callback | AsyncCallback | Yes | Callback used to return the result. | - -**Example** - -```js -previewOutput.addDeferredSurface('surfaceId', (err) => { - if (err) { - console.error(`Failed to add deferredSurface. ${err.message}`); - return; - } - console.log('Callback returned with deferredSurface added.'); -}) -``` - -### addDeferredSurface - -addDeferredSurface(surfaceId: string): Promise - -Adds a surface after a **PreviewOutput** instance is created. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -----------| ---- | ------------------------------------------------------------------------------ | -| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)**.| - -**Return value** - -| Type | Description | -| -------------- | ----------------------- | -| Promise| Promise used to return the result.| - -**Example** - -```js -previewOutput.addDeferredSurface('surfaceId').then(() => { - console.log('Promise returned with deferredSurface added.'); -}) -``` - -### start - -start(callback: AsyncCallback): void - -Starts to output preview streams. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -previewOutput.start((err) => { - if (err) { - console.error(`Failed to start the previewOutput. ${err.message}`); - return; - } - console.log('Callback returned with previewOutput started.'); -}) -``` - -### start - -start(): Promise - -Starts to output preview streams. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| -------------- | ----------------------- | -| Promise| Promise used to return the result.| - -**Example** - -```js -previewOutput.start().then(() => { - console.log('Promise returned with previewOutput started.'); -}) -``` - -### stop - -stop(callback: AsyncCallback): void - -Stops outputting preview streams. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -previewOutput.stop((err) => { - if (err) { - console.error(`Failed to stop the previewOutput. ${err.message}`); - return; - } - console.log('Callback returned with previewOutput stoped.'); -}) -``` - -### stop - -stop(): Promise - -Stops outputting preview streams. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| -------------- | ------------------------ | -| Promise| Promise used to return the result.| - -**Example** - -```js -previewOutput.stop().then(() => { - console.log('Callback returned with previewOutput stoped.'); -}) -``` - -### on('frameStart') - -on(type: 'frameStart', callback: AsyncCallback): void - -Listens for preview frame start events. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | --------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'frameStart'**, indicating the preview frame start event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | - -**Example** - -```js -previewOutput.on('frameStart', () => { - console.log('Preview frame started'); -}) -``` - -### on('frameEnd') - -on(type: 'frameEnd', callback: AsyncCallback): void - -Listens for preview frame end events. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'frameEnd'**, indicating the preview frame end event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | - -**Example** - -```js -previewOutput.on('frameEnd', () => { - console.log('Preview frame ended'); -}) -``` - -### on('error') - -on(type: 'error', callback: ErrorCallback): void - -Listens for **PreviewOutput** errors. This API uses a callback to return the errors. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------------- | ---- | ------------------------ | -| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the preview output error event.| -| callback | ErrorCallback<[PreviewOutputErrorCode](#previewoutputerrorcode)\> | Yes | Callback used to return the error information. | - -**Example** - -```js -previewOutput.on('error', (previewOutputError) => { - console.log(`Preview output error code: ${previewOutputError.code}`); -}) -``` - -## PreviewOutputErrorCode - -Enumerates the error codes used for preview output. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ------------- | ---- | -------- | -| ERROR_UNKNOWN | -1 | Unknown error.| - -## PreviewOutputError - -Defines the preview output error. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name| Type | Description | -| ---- | ------------------------------------------------- | ---------------------- | -| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | **PreviewOutput** error code.| - -## ImageRotation - -Enumerates the image rotation angles. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ------------ | ---- | ------------- | -| ROTATION_0 | 0 | The image rotates 0 degrees. | -| ROTATION_90 | 90 | The image rotates 90 degrees. | -| ROTATION_180 | 180 | The image rotates 180 degrees.| -| ROTATION_270 | 270 | The image rotates 270 degrees.| - -## Location - -Defines geolocation information. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Mandatory|Description | -| ------------ | ------ | --- |------------ | -| latitude | number | Yes |Latitude, in degrees. | -| longitude | number | Yes |Longitude, in degrees. | -| altitude | number | Yes |Altitude, in meters. | - -## QualityLevel - -Enumerates the image quality levels. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| -------------------- | ---- | ------------ | -| QUALITY_LEVEL_HIGH | 0 | High image quality. | -| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| -| QUALITY_LEVEL_LOW | 2 | Low image quality. | - - -## PhotoCaptureSetting - -Defines the settings for photo capture. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Mandatory | Default Value | Description | -| -------- | ------------------------------- | ---- | ----------------- | -----------------| -| quality | [QualityLevel](#qualitylevel) | No | QUALITY_LEVEL_HIGH| Photo quality. | -| rotation | [ImageRotation](#imagerotation) | No | ROTATION_0 | Rotation angle of the photo. | -| location | [Location](#location) | No | (0,0,0) | Geolocation information of the photo. | -| mirror | boolean | No | false |Whether mirroring is enabled. By default, mirroring is disabled.| - -## PhotoOutput - -Implements output information used in a **CaptureSession**. - -### getDefaultCaptureSetting - -getDefaultCaptureSetting(callback: AsyncCallback): void - -Obtains the default shooting parameters. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | -------------------- | -| callback | AsyncCallback<[PhotoCaptureSetting](#photocapturesetting)\> | Yes | Callback used to return the result.| - -**Example** - -```js -photoOutput.getDefaultCaptureSetting((err, photocapturesetting) => { - if (err) { - console.error(`Failed to get the defaultCaptureSetting. ${err.message}`); - return; - } - console.log('Callback returned with an array of defaultCaptureSetting.'); -}) -``` - -### getDefaultCaptureSetting - -getDefaultCaptureSetting(): Promise - -Obtains the default shooting parameters. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ----------------------------------------------------- | ----------------------- | -| Promise<[PhotoCaptureSetting](#photocapturesetting)\> | Promise used to return the result.| - -**Example** - -```js -photoOutput.getDefaultCaptureSetting().then((photocapturesetting) => { - console.log('Callback returned with an array of defaultCaptureSetting.'); -}) -``` - -### capture - -capture(callback: AsyncCallback): void - -Captures a photo with the default shooting parameters. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| - -**Example** - -```js -photoOutput.capture((err) => { - if (err) { - console.error(`Failed to capture the photo ${err.message}`); - return; - } - console.log('Callback invoked to indicate the photo capture request success.'); -}); -``` - -### capture - -capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void - -Captures a photo with the specified shooting parameters. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------- | ---- | -------------------- | -| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | -| callback | AsyncCallback | Yes | Callback used to return the result. | - -**Example** - -```js -let settings:PhotoCaptureSetting = { - quality = 1, - rotation = 0 -} -photoOutput.capture(settings, (err) => { - if (err) { - console.error(`Failed to capture the photo ${err.message}`); - return; - } - console.log('Callback invoked to indicate the photo capture request success.'); -}); -``` - -### capture - -capture(setting?: PhotoCaptureSetting): Promise - -Captures a photo with the specified shooting parameters. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------------- | ---- | -------- | -| setting | [PhotoCaptureSetting](#photocapturesetting) | No | Shooting settings.| - -**Return value** - -| Type | Description | -| -------------- | ------------------------ | -| Promise| Promise used to return the result.| - - -**Example** - -```js -photoOutput.capture().then(() => { - console.log('Promise returned to indicate that photo capture request success.'); -}) -``` - -### isMirrorSupported - -isMirrorSupported(callback: AsyncCallback): void - -Checks whether mirroring is supported. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | -------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite. | - -**Example** - -```js -captureSession.isMirrorSupported((err, isSupported) => { - if (err) { - console.error(`Failed to check mirror is supported ${err.message}`); - return; - } - console.log('Callback returned with the successful execution of isMirrorSupported.'); -}) -``` - -### isMirrorSupported - -isMirrorSupported(): Promise - -Checks whether mirroring is supported. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Return value** - -| Type | Description | -| ----------------- | ------------------------------------------- | -| Promise | Promise used to return the mirroring support status. The value **true** means that mirroring is supported, and **false** means the opposite. | - -**Example** - -```js -captureSession.isMirrorSupported().then((isSupported) => { - console.log(`Promise returned with mirror supported: ${isSupported}`); -}) -``` - -### on('captureStart') - -on(type: 'captureStart', callback: AsyncCallback): void - -Listens for shooting start events. This API uses an asynchronous callback to return the capture ID. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'captureStart'**, indicating the shooting start event.| -| callback | AsyncCallback | Yes | Callback used to return the capture ID. | - -**Example** - -```js -photoOutput.on('captureStart', (err, captureId) => { - console.log(`photo capture stated, captureId : ${captureId}`); -}) -``` - -### on('frameShutter') - -on(type: 'frameShutter', callback: AsyncCallback): void - -Listens for frame shutter events. This API uses an asynchronous callback to return the event information. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | --- | ------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'frameShutter'**, indicating the frame shutter event.| -| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. | - -**Example** - -```js -photoOutput.on('frameShutter', (err, frameShutterInfo) => { - console.log(`photo capture end, captureId : ${frameShutterInfo.captureId}`); - console.log(`Timestamp for frame : ${frameShutterInfo.timestamp}`); -}) -``` - -### on('captureEnd') - -on(type: 'captureEnd', callback: AsyncCallback): void - -Listens for shooting end events. This API uses an asynchronous callback to return the event information. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'captureEnd'**, indicating the shooting end event.| -| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. | - -**Example** - -```js -photoOutput.on('captureEnd', (err, captureEndInfo) => { - console.log(`photo capture end, captureId : ${captureEndInfo.captureId}`); - console.log(`frameCount : ${captureEndInfo.frameCount}`); -}) -``` - -### on('error') - -on(type: 'error', callback: ErrorCallback): void - -Listens for **PhotoOutput** errors. This API uses a callback to return the errors. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ----------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the photo output error event.| -| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | Yes | Callback used to return the error information. | - -**Example** - -```js -photoOutput.on('error', (err, photoOutputError) => { - console.log(`Photo output error code: ${photoOutputError.code}`); -}) -``` +**System capability**: SystemCapability.Multimedia.Camera.Core -## FrameShutterInfo +| Name | Value | Description | +| ------------ | ---- | --------------- | +| ROTATION_0 | 0 | The image rotates 0 degrees. | +| ROTATION_90 | 90 | The image rotates 90 degrees. | +| ROTATION_180 | 180 | The image rotates 180 degrees.| +| ROTATION_270 | 270 | The image rotates 270 degrees.| -Defines the frame shutter information. +## QualityLevel + +Enumerates the image quality levels. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ---------- | -| captureId | number | Yes | ID of this capture action. | -| timestamp | number | Yes | Timestamp when the frame shutter event is triggered.| +| Name | Value | Description | +| -------------------- | ---- | -------------- | +| QUALITY_LEVEL_HIGH | 0 | High image quality. | +| QUALITY_LEVEL_MEDIUM | 1 | Medium image quality.| +| QUALITY_LEVEL_LOW | 2 | Low image quality. | -## CaptureEndInfo -Defines the capture end information. +## PhotoCaptureSetting + +Defines the settings for photo capture. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ---------| -| captureId | number | Yes | ID of this capture action.| -| frameCount | number | Yes | Number of frames captured. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | -------------- | +| quality | [QualityLevel](#qualitylevel) | No | Photo quality. | +| rotation | [ImageRotation](#imagerotation) | No | Rotation angle of the photo.| -## PhotoOutputErrorCode -Enumerates the error codes used for photo output. +## PhotoOutput -**System capability**: SystemCapability.Multimedia.Camera.Core +Implements photo output. -| Name | Value | Description | -| ----------------------------- | ---- | --------------- | -| ERROR_UNKNOWN | -1 | Unknown error. | -| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| -| ERROR_INSUFFICIENT_RESOURCES | 1 | Insufficient resources. | -| ERROR_TIMEOUT | 2 | Timeout. | +### capture -## PhotoOutputError +capture(callback: AsyncCallback): void -Defines a photo output error. +Captures a photo with the default shooting settings. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | **PhotoOutput** error code.| +**Parameters** -## VideoOutput +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| -Implements output information used in a video recording session. +**Example** -### start +```js +photoOutput.capture((err) => { + if (err) { + console.error('Failed to capture the photo ${err.message}'); + return; + } + console.log('Callback invoked to indicate the photo capture request success.'); +}); +``` -start(callback: AsyncCallback): void +### capture -Starts video recording. This API uses an asynchronous callback to return the result. +capture(setting: PhotoCaptureSetting, callback: AsyncCallback): void + +Captures a photo with the specified shooting settings. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------ | +| setting | [PhotoCaptureSetting](#photocapturesetting) | Yes | Shooting settings. | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -videoOutput.start((err) => { +let settings:PhotoCaptureSetting = { + quality = 1, + rotation = 0 +} +photoOutput.capture(settings, (err) => { if (err) { - console.error(`Failed to start the video output ${err.message}`); + console.error('Failed to capture the photo ${err.message}'); return; } - console.log('Callback invoked to indicate the video output start success.'); + console.log('Callback invoked to indicate the photo capture request success.'); }); ``` -### start +### capture -start(): Promise +capture(setting?: PhotoCaptureSetting): Promise -Starts video recording. This API uses a promise to return the result. +Captures a photo with the specified shooting settings. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------- | ---- | ---------- | +| setting | [PhotoCaptureSetting](#photocapturesetting) | No | Shooting settings.| + **Return value** -| Type | Description | -| -------------- | ----------------------- | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| **Example** ```js -videoOutput.start().then(() => { - console.log('Promise returned to indicate that start method execution success.'); +photoOutput.capture().then(() => { + console.log('Promise returned to indicate that photo capture request success.'); }) ``` -### stop +### release -stop(callback: AsyncCallback): void +release(callback: AsyncCallback): void -Stops video recording. This API uses an asynchronous callback to return the result. +Releases this **PhotoOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -4106,465 +2290,465 @@ Stops video recording. This API uses an asynchronous callback to return the resu **Example** ```js -videoOutput.stop((err) => { +photoOutput.release((err) => { if (err) { - console.error(`Failed to stop the video output ${err.message}`); + console.error('Failed to release the PhotoOutput instance ${err.message}'); return; } - console.log('Callback invoked to indicate the video output stop success.'); + console.log('Callback invoked to indicate that the PhotoOutput instance is released successfully.'); }); ``` -### stop +### release -stop(): Promise +release(): Promise -Stops video recording. This API uses a promise to return the result. +Releases this **PhotoOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| -------------- | ----------------------- | +| Type | Description | +| -------------- | --------------------------- | | Promise| Promise used to return the result.| + **Example** ```js -videoOutput.stop().then(() => { - console.log('Promise returned to indicate that stop method execution success.'); +photoOutput.release().then(() => { + console.log('Promise returned to indicate that the PhotoOutput instance is released successfully.'); }) -``` +``` -### on('frameStart') +### on('captureStart') -on(type: 'frameStart', callback: AsyncCallback): void +on(type: 'captureStart', callback: AsyncCallback): void -Listens for video recording start events. This API uses an asynchronous callback to return the result. +Listens for shooting start events. This API uses an asynchronous callback to return the capture ID. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ----------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **frameStart**, indicating the video recording start event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------- | :--- | :----------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'captureStart'**, indicating the shooting start event.| +| callback | AsyncCallback | Yes | Callback used to return the capture ID. | **Example** ```js -videoOutput.on('frameStart', () => { - console.log('Video frame started'); +photoOutput.on('captureStart', (err, captureId) => { + console.log('photo capture stated, captureId : ' + captureId); }) ``` -### on('frameEnd') +### on('frameShutter') -on(type: 'frameEnd', callback: AsyncCallback): void +on(type: 'frameShutter', callback: AsyncCallback): void -Listens for video recording stop events. This API uses an asynchronous callback to return the result. +Listens for frame shutter events. This API uses an asynchronous callback to return the event information. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'frameEnd'**, indicating the video recording stop event.| -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------------------- | :--- | :--------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'frameShutter'**, indicating the frame shutter event.| +| callback | AsyncCallback<[FrameShutterInfo](#frameshutterinfo)\> | Yes | Callback used to return the result. | **Example** ```js -videoOutput.on('frameEnd', () => { - console.log('Video frame ended'); +photoOutput.on('frameShutter', (err, frameShutterInfo) => { + console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); + console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); }) ``` -### on('error') +### on('captureEnd') -on(type: 'error', callback: ErrorCallback): void +on(type: 'captureEnd', callback: AsyncCallback): void -Listens for errors that occur during video recording. This API uses a callback to return the result. +Listens for shooting end events. This API uses an asynchronous callback to return the event information. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | -------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the video output error event.| -| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| :------- | :------------------------------------------------ | :--- | :--------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'captureEnd'**, indicating the shooting end event.| +| callback | AsyncCallback<[CaptureEndInfo](#captureendinfo)\> | Yes | Callback used to return the result. | **Example** ```js -videoOutput.on('error', (VideoOutputError) => { - console.log(`Video output error code: ${VideoOutputError.code}`); +photoOutput.on('captureEnd', (err, captureEndInfo) => { + console.log('photo capture end, captureId : ' + captureEndInfo.captureId); + console.log('frameCount : ' + captureEndInfo.frameCount); }) ``` -## VideoOutputErrorCode +### on('error') + +on(type: 'error', callback: ErrorCallback): void -Enumerates the error codes used for video recording. +Listens for **PhotoOutput** errors. This API uses a callback to return the errors. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| --------------------- | ---- | ------------ | -| ERROR_UNKNOWN | -1 | Unknown error. | -| ERROR_DRIVER_ERROR | 0 | The driver or hardware is faulty.| +**Parameters** + +| Name | Type | Mandatory| Description | +| :------- | :---------------------------------------------------- | :--- | :---------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the photo output error event.| +| callback | ErrorCallback<[PhotoOutputError](#photooutputerror)\> | Yes | Callback used to return the error information. | + +**Example** -## VideoOutputError +```js +photoOutput.on('error', (err, photoOutputError) => { + console.log('Photo output error code: ' + photoOutputError.code); +}) +``` -Defines a video output error. +## FrameShutterInfo + +Defines the frame shutter information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputError](#photooutputerror) | **VideoOutput** error code.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ----------------------------- | +| captureId | number | Yes | ID of this capture action.| +| timestamp | number | Yes | Timestamp when the frame shutter event is triggered. | -## MetadataObjectType +## CaptureEndInfo -Enumerates metadata streams. +Defines the capture end information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------- | ---- | ----------------- | -| FACE_DETECTION | 0 | Metadata object type.| +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ----------------------------- | +| captureId | number | Yes | ID of this capture action.| +| frameCount | number | Yes | Number of frames captured. | -## Rect +## PhotoOutputErrorCode -Defines a rectangle. +Enumerates the error codes used in a **PhotoOutput** instance. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Description | -| -------- | ------ | -------------------- | -| topLeftX | number | X-axis coordinate of the upper left corner of the rectangle. | -| topLeftY | number | Y-axis coordinate of the upper left corner of the rectangle. | -| width | number | Width of the rectangle. | -| height | number | Height of the rectangle. | +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| + +## PhotoOutputError + +Defines a **PhotoOutput** error. -## MetadataObject +**System capability**: SystemCapability.Multimedia.Camera.Core -Implements camera metadata, which is the data source of **[CameraInput](#camerainput)**. +| Name| Type | Description | +| ---- | ------------------------------------- | ----------------------- | +| code | [PhotoOutputError](#photooutputerror) | **PhotoOutput** error code.| -### getType +## camera.createVideoOutput -getType(callback: AsyncCallback): void +createVideoOutput(surfaceId: string, callback: AsyncCallback): void -Obtains the metadata object type. This API uses an asynchronous callback to return the result. +Creates a **VideoOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------------- | --- | -------------------- | -| callback | AsyncCallback<[MetadataObjectType](#metadataobjecttype)\> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------- | ---- | ----------------------------------- | +| surfaceId | string | Yes | Surface ID, which is obtained from **VideoRecorder**. | +| callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance.| **Example** ```js -metadataObject.getType((err, metadataObjectType) => { +camera.createVideoOutput(("surfaceId"), (err, videoOutput) => { if (err) { - console.error(`Failed to get type. ${err.message}`); + console.error('Failed to create the VideoOutput instance. ${err.message}'); return; } - console.log('Callback returned with an array of metadataObjectType.'); -}) + console.log('Callback returned with the VideoOutput instance'); +}); ``` -### getType +## camera.createVideoOutput -getType(): Promise +createVideoOutput(surfaceId: string): Promise -Obtains the metadata object type. This API uses a promise to return the result. +Creates a **VideoOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------------------------------- | +| surfaceId | string | Yes | Surface ID, which is obtained from **VideoRecorder**.| + **Return value** -| Type | Description | -| --------------------------------------------------- | --------------------------- | -| Promise<[MetadataObjectType](#metadataobjecttype)\> | Promise used to return the result.| +| Type | Description | +| ------------------------------------- | -------------------------------------- | +| Promise<[VideoOutput](#videooutput)\> | Promise used to return the **VideoOutput** instance.| **Example** ```js -metadataObject.getType().then((metadataObjectType) => { - console.log('Callback returned with an array of metadataObjectType.'); +camera.createVideoOutput("surfaceId" +).then((videoOutput) => { + console.log('Promise returned with the VideoOutput instance'); }) ``` -### getTimestamp +## VideoOutput + +Implements output information used in a video recording session. + +### start -getTimestamp(callback: AsyncCallback): void +start(callback: AsyncCallback): void -Obtains the metadata timestamp. This API uses an asynchronous callback to return the result. +Starts video recording. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -metadataObject.getTimestamp((err) => { +videoOutput.start((err) => { if (err) { - console.error(`Failed to get timestamp. ${err.message}`); + console.error('Failed to start the video output ${err.message}'); return; } - console.log('Callback returned with timestamp getted.'); -}) + console.log('Callback invoked to indicate the video output start success.'); +}); ``` -### getTimestamp +### start -getTimestamp(): Promise +start(): Promise -Obtains the metadata timestamp. This API uses a promise to return the result. +Starts video recording. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ---------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| + **Example** ```js -metadataObject.getTimestamp().then(() => { - console.log('Callback returned with timestamp getted.'); +videoOutput.start().then(() => { + console.log('Promise returned to indicate that start method execution success.'); }) ``` -### getBoundingBox +### stop -getBoundingBox(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -Obtains the bounding box of metadata. This API uses an asynchronous callback to return the result. +Stops video recording. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback<[Rect](#rect)\> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -metadataObject.getBoundingBox((err, rect) => { +videoOutput.stop((err) => { if (err) { - console.error(`Failed to get boundingBox. ${err.message}`); + console.error('Failed to stop the video output ${err.message}'); return; } - console.log('Callback returned with boundingBox getted.'); -}) + console.log('Callback invoked to indicate the video output stop success.'); +}); ``` -### getBoundingBox +### stop -getBoundingBox(): Promise +stop(): Promise -Obtains the bounding box of metadata. This API uses a promise to return the result. +Stops video recording. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ---------------------- | --------------------------- | -| Promise<[Rect](#rect)\> | Promise used to return the result.| +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| **Example** ```js -metadataObject.getBoundingBox().then((rect) => { - console.log('Callback returned with boundingBox getted.'); +videoOutput.start().then(() => { + console.log('Promise returned to indicate that stop method execution success.'); }) ``` -## MetadataFaceObject - -Implements the face object of metadata. It inherits [MetadataObject](#metadataobject). - -## MetadataOutput - -Implements metadata streams. It inherits **[CameraOutput](#cameraoutput)**. - -### start +### release -start(callback: AsyncCallback): void +release(callback: AsyncCallback): void -Starts to output metadata. This API uses an asynchronous callback to return the result. +Releases this **VideoOutput** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -metadataOutput.start((err) => { +videoOutput.release((err) => { if (err) { - console.error(`Failed to start metadataOutput. ${err.message}`); + console.error('Failed to release the VideoOutput instance ${err.message}'); return; } - console.log('Callback returned with metadataOutput started.'); -}) + console.log('Callback invoked to indicate that the VideoOutput instance is released successfully.'); +}); ``` -### start +### release -start(): Promise +release(): Promise -Starts to output metadata. This API uses a promise to return the result. +Releases this **VideoOutput** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ---------------------- | ------------------------ | -| Promise | Promise used to return the result.| - -**Example** - -```js -metadataOutput.start().then(() => { - console.log('Callback returned with metadataOutput started.'); -}) -``` - -### stop - -stop(callback: AsyncCallback): void - -Stops outputting metadata. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -**Parameters** +| Type | Description | +| -------------- | --------------------------- | +| Promise| Promise used to return the result.| -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -metadataOutput.stop((err) => { - if (err) { - console.error(`Failed to stop the metadataOutput. ${err.message}`); - return; - } - console.log('Callback returned with metadataOutput stoped.'); +videoOutput.release().then(() => { + console.log('Promise returned to indicate that the VideoOutput instance is released successfully.'); }) ``` -### stop +### on('frameStart') -stop(): Promise +on(type: 'frameStart', callback: AsyncCallback): void -Stops outputting metadata. This API uses a promise to return the result. +Listens for video recording start events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** +**Parameters** -| Type | Description | -| ---------------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :----------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **`frameStart`**, indicating the video recording start event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -metadataOutput.stop().then(() => { - console.log('Callback returned with metadataOutput stoped.'); +videoOutput.on('frameStart', () => { + console.log('Video frame started'); }) ``` -### on('metadataObjectsAvailable') +### on('frameEnd') -on(type: 'metadataObjectsAvailable', callback: AsyncCallback\>): void +on(type: 'frameEnd', callback: AsyncCallback): void -Listens for metadata objects. This API uses an asynchronous callback to return the result. +Listens for video recording end events. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- - | ---- | ------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**, that is, the metadata object.| -| callback | Callback\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| :------- | :------------------- | :--- | :--------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **`frameEnd`**, indicating the video frame end event.| +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -metadataOutput.on('metadataObjectsAvailable', (metadataObject) => { - console.log(`metadata output error code: ${metadataObject.code}`); +videoOutput.on('frameEnd', () => { + console.log('Video frame ended'); }) ``` ### on('error') -on(tuype: 'error', callback: ErrorCallback): void +on(type: 'error', callback: ErrorCallback): void -Listens for metadata errors. This API uses an asynchronous callback to return the result. +Listens for **VideoOutput** errors. This API uses a callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | --------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**, that is, the metadata error.| -| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| :------- | :----------------------------------------------- | :--- | :-------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, indicating the video output error event.| +| callback | Callback<[VideoOutputError](#videooutputerror)\> | Yes | Callback used to return the error information. | **Example** ```js -metadataOutput.on('error', (metadataOutputError) => { - console.log(`Metadata output error code: ${metadataOutputError.code}`); +videoOutput.on('error', (VideoOutputError) => { + console.log('Video output error code: ' + VideoOutputError.code); }) ``` -## MetadataOutputErrorCode +## VideoOutputErrorCode -Enumerates the codes used for metadata output errors. +Enumerates the error codes used in a **VideoOutput** instance. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Value | Description | -| ------------------------------- | ---- | -------- | -| ERROR_UNKNOWN | -1 | Unknown error.| -| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| +| Name | Value | Description | +| ------------- | ---- | ---------- | +| ERROR_UNKNOWN | -1 | Unknown error.| -## MetadataOutputError +## VideoOutputError -Defines a metadata output error. +Defines a **VideoOutput** error. **System capability**: SystemCapability.Multimedia.Camera.Core | Name| Type | Description | | ---- | ------------------------------------- | ----------------------- | -| code | [MetadataOutputErrorCode](#metadataoutputerrorcode) | **MetadataOutput** error code.| +| code | [PhotoOutputError](#photooutputerror) | **VideoOutput** error code.| diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 710d6ccb8820e88ed98e3519c36824efdd5e5b17..0bf80dbbd39095bdce908faad30f90da0461e08b 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -71,10 +71,6 @@ Provides the event types supported by the **CommonEvent** module. The name and v | COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | | COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_USERS | Indicates the common event that the user is going to be stopped. | | COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. | -| COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | - | Indicates the common event about a HUAWEI ID login. | -| COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | - | Indicates the common event about a HUAWEI ID logout. | -| COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | - | Indicates the common event that the HUAWEI ID is invalid. | -| COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | - | Indicates the common event about a HUAWEI ID logoff. | | COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. | | COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | | COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md index 499dafec721fd280beee9e9ccfcab76ae895bd14..4c04dd7a835c647889d70dff754d6baf14730efb 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -119,6 +119,25 @@ Subscribes to device connection events. This API uses an asynchronous callback t > This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect9) instead. +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **deviceConnect**.| + | callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | Yes| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.| + +**Example** + + ```js + continuationManager.on("deviceConnect", (data) => { + console.info('onDeviceConnect deviceId: ' + JSON.stringify(data.id)); + console.info('onDeviceConnect deviceType: ' + JSON.stringify(data.type)); + console.info('onDeviceConnect deviceName: ' + JSON.stringify(data.name)); + }); + ``` + ## continuationManager.on("deviceDisconnect")(deprecated) on(type: "deviceDisconnect", callback: Callback\): void; @@ -127,6 +146,23 @@ Subscribes to device disconnection events. This API uses an asynchronous callbac > This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect9) instead. +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.| + | callback | Callback\ | Yes| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.| + +**Example** + + ```js + continuationManager.on("deviceDisconnect", (data) => { + console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data)); + }); + ``` + ## continuationManager.off("deviceConnect")(deprecated) off(type: "deviceConnect", callback?: Callback\): void; @@ -135,6 +171,25 @@ Unsubscribes from device connection events. This API uses an asynchronous callba > This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect9) instead. +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **deviceConnect**.| + | callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | No| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.| + +**Example** + + ```js + continuationManager.off("deviceConnect", (data) => { + console.info('onDeviceConnect deviceId: ' + JSON.stringify(data.id)); + console.info('onDeviceConnect deviceType: ' + JSON.stringify(data.type)); + console.info('onDeviceConnect deviceName: ' + JSON.stringify(data.name)); + }); + ``` + ## continuationManager.off("deviceDisconnect")(deprecated) off(type: "deviceDisconnect", callback?: Callback\): void; @@ -143,6 +198,23 @@ Unsubscribes from device disconnection events. This API uses an asynchronous cal > This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect9) instead. +**System capability**: SystemCapability.Ability.DistributedAbilityManager + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.| + | callback | Callback\ | No| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.| + +**Example** + + ```js + continuationManager.off("deviceDisconnect", (data) => { + console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data)); + }); + ``` + ## continuationManager.on("deviceConnect")9+ on(type: "deviceConnect", token: number, callback: Callback\>): void; diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md index 82941689b8d2d511ca1878b0b03fac2e1c32dafd..3a2f046c36b3c17bca7c87c71e18c69971b5683c 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -55,8 +55,8 @@ let options = {trim : false, declarationKey:"_declaration", commentKey : "_comment", parentKey : "_parent", typeKey : "_type", nameKey : "_name", elementsKey : "_elements"} let result = JSON.stringify(conv.convert(xml, options)); -console.log(result) -// Output(Non compact) +console.log(result); +// Output (non-compact) // {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]} ``` diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md index 3860be1f4cd4fae2b432c7286ae5aca1c2b44868..5d393653ce602b60438df2b6f9e54f6ba9cb9fe6 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -13,13 +13,10 @@ import dataAbility from '@ohos.data.dataAbility'; ``` - ## dataAbility.createRdbPredicates - createRdbPredicates(name: string, dataAbilityPredicates: DataAbilityPredicates): rdb.RdbPredicates - Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -32,93 +29,93 @@ Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | **Return value** + | Type| Description| | -------- | -------- | | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let dataAbilityPredicates = new dataAbility.DataAbilityPredicates() - dataAbilityPredicates.equalTo("NAME", "Rose").between("AGE", 16, 30) + dataAbilityPredicates.equalTo("NAME", "Rose") let predicates = dataAbility.createRdbPredicates("EMPLOYEE", dataAbilityPredicates) ``` - ## DataAbilityPredicates Provides predicates for implementing diverse query methods. - ### equalTo - equalTo(field: string, value: ValueType): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.equalTo("NAME", "lisi") ``` - ### notEqualTo - notEqualTo(field: string, value: ValueType): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.notEqualTo("NAME", "lisi") ``` - ### beginWrap - beginWrap(): DataAbilityPredicates - Adds a left parenthesis to this **DataAbilityPredicates**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| **Example** + ```js dataAbilityPredicates.equalTo("NAME", "lisi") .beginWrap() @@ -128,23 +125,22 @@ Adds a left parenthesis to this **DataAbilityPredicates**. .endWrap() ``` - ### endWrap - endWrap(): DataAbilityPredicates - Adds a right parenthesis to this **DataAbilityPredicates**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| **Example** + ```js dataAbilityPredicates.equalTo("NAME", "lisi") .beginWrap() @@ -154,251 +150,247 @@ Adds a right parenthesis to this **DataAbilityPredicates**. .endWrap() ``` - ### or - or(): DataAbilityPredicates - Adds the OR condition to this **DataAbilityPredicates**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| **Example** + ```js dataAbilityPredicates.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") ``` - ### and - and(): DataAbilityPredicates - Adds the AND condition to this **DataAbilityPredicates**. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| **Example** + ```js dataAbilityPredicates.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) ``` - ### contains - contains(field: string, value: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match a string containing the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.contains("NAME", "os") ``` - ### beginsWith - beginsWith(field: string, value: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match a string that starts with the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.beginsWith("NAME", "os") ``` - ### endsWith - endsWith(field: string, value: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match a string that ends with the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ``` dataAbilityPredicates.endsWith("NAME", "se") ``` - ### isNull - isNull(field: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field whose value is null. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.isNull("NAME") ``` - ### isNotNull - isNotNull(field: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field whose value is not null. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.isNotNull("NAME") ``` - ### like - like(field: string, value: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match a string that is similar to the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.like("NAME", "%os%") ``` - ### glob - glob(field: string, value: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the specified string. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.glob("NAME", "?h*g") ``` - ### between - between(field: string, low: ValueType, high: ValueType): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match a field whose data type is **ValueType** and value is within the specified range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| @@ -406,27 +398,27 @@ Sets a **DataAbilityPredicates** object to match a field whose data type is **Va | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.between("AGE", 10, 50) ``` - ### notBetween - notBetween(field: string, low: ValueType, high: ValueType): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| @@ -434,244 +426,245 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.notBetween("AGE", 10, 50) ``` - ### greaterThan - greaterThan(field: string, value: ValueType): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value greater than the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.greaterThan("AGE", 18) ``` - ### lessThan - lessThan(field: string, value: ValueType): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value less than the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.lessThan("AGE", 20) ``` - ### greaterThanOrEqualTo - greaterThanOrEqualTo(field: string, value: ValueType): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value greater than or equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.greaterThanOrEqualTo("AGE", 18) ``` - ### lessThanOrEqualTo - lessThanOrEqualTo(field: string, value: ValueType): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type **ValueType** and value less than or equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.lessThanOrEqualTo("AGE", 20) ``` - ### orderByAsc - orderByAsc(field: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the column with values sorted in ascending order. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.orderByAsc("NAME") ``` - ### orderByDesc - orderByDesc(field: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the column with values sorted in descending order. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.orderByDesc("AGE") ``` - ### distinct - distinct(): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| **Example** + ```js dataAbilityPredicates.equalTo("NAME", "Rose").distinct() ``` - ### limitAs - limitAs(value: number): DataAbilityPredicates - Set a **DataAbilityPredicates** object to specify the maximum number of records. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | number | Yes| Maximum number of records.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| **Example** + ```js dataAbilityPredicates.equalTo("NAME", "Rose").limitAs(3) ``` - ### offsetAs - offsetAs(rowOffset: number): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to specify the start position of the returned result. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| **Example** + ```js dataAbilityPredicates.equalTo("NAME", "Rose").offsetAs(3) ``` @@ -679,66 +672,66 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret ### groupBy - groupBy(fields: Array<string>): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to group rows that have the same value into summary rows. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fields | Array<string> | Yes| Names of columns to group.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| **Example** + ```js dataAbilityPredicates.groupBy(["AGE", "NAME"]) ``` ### indexedBy - indexedBy(field: string): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to specify the index column. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | indexName | string | Yes| Name of the index column.| **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| **Example** + ```js dataAbilityPredicates.indexedBy("SALARY_INDEX") ``` - ### in - in(field: string, value: Array<ValueType>): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type Array and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| @@ -746,39 +739,40 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.in("AGE", [18, 20]) ``` - ### notIn - notIn(field: string, value: Array<ValueType>): DataAbilityPredicates - Sets a **DataAbilityPredicates** object to match the field with data type Array and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the table.| | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| - **Return value** + | Type| Description| | -------- | -------- | | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** + ```js dataAbilityPredicates.notIn("NAME", ["Lisa", "Rose"]) ``` diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 6803d4edf50fc219bc37c4be79fc71687dd91457..5d649c2f28ebd158da0abe963095c9202fdf6c25 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -39,8 +39,8 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | | context | [Context](js-apis-ability-context.md) | Yes | Application context. | -| name | string | Yes | Name of the **Preferences** instance. | -| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| +| name | string | Yes | Name of the **Preferences** instance. | +| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined and the **Preferences** instance obtained is returned. Otherwise, **err** is an error code.| **Example** @@ -66,12 +66,14 @@ Obtains a **Preferences** instance. This API uses a promise to return the result **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | | name | string | Yes | Name of the **Preferences** instance.| **Return value** + | Type | Description | | ------------------------------------------ | ---------------------------------- | | Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| @@ -103,6 +105,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | context | [Context](js-apis-ability-context.md) | Yes | Application context. | @@ -110,6 +113,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js data_preferences.deletePreferences(this.context, 'mystore', function (err) { if (err) { @@ -134,17 +138,20 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | | name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = data_preferences.deletePreferences(this.context, 'mystore') promise.then(() => { @@ -166,6 +173,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | | context | [Context](js-apis-ability-context.md) | Yes | Application context. | @@ -173,6 +181,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { if (err) { @@ -195,17 +204,20 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | | name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore') promise.then(() => { @@ -232,6 +244,7 @@ Obtains the value of a key. This API uses an asynchronous callback to return the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | @@ -260,6 +273,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | @@ -272,6 +286,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the | Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| **Example** + ```js let promise = preferences.get('startup', 'default'); promise.then((data) => { @@ -290,6 +305,7 @@ Obtains an **Object** instance that contains all KV pairs. This API uses an asyn **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | callback | AsyncCallback<Object> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** is the **Object** instance obtained. Otherwise, **err** is an error code.| @@ -318,11 +334,13 @@ Obtains an **Object** instance that contains all KV pairs. This API uses a promi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | --------------------- | ------------------------------------------- | | Promise<Object> | Promise used to return the **Object** instance obtained.| **Example** + ```js let promise = preferences.getAll(); promise.then((value) => { @@ -343,6 +361,7 @@ Writes data to this **Preferences** instance. This API uses an asynchronous call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data. It cannot be empty. | @@ -350,6 +369,7 @@ Writes data to this **Preferences** instance. This API uses an asynchronous call | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined. Otherwise, **err** is an error code. | **Example** + ```js preferences.put('startup', 'auto', function (err) { if (err) { @@ -370,17 +390,20 @@ Writes data to this **Preferences** instance. This API uses a promise to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data. It cannot be empty. | | value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.put('startup', 'auto'); promise.then(() => { @@ -400,12 +423,14 @@ Checks whether this **Preferences** instance contains a KV pair of the given key **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to check. It cannot be empty. | | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| **Example** + ```js preferences.has('startup', function (err, isExist) { if (err) { @@ -430,11 +455,13 @@ Checks whether this **Preferences** instance contains data with the given key. T **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------- | | key | string | Yes | Key of the data to check. It cannot be empty.| **Return value** + | Type | Description | | ---------------------- | ------------------------------------------------------------ | | Promise<boolean> | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| @@ -464,12 +491,14 @@ Deletes a KV pair from this **Preferences** instance. This API uses an asynchron **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | key | string | Yes | Key of the KV pair to delete. It cannot be empty. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.delete('startup', function (err) { if (err) { @@ -490,16 +519,19 @@ Deletes a KV pair from this **Preferences** instance. This API uses a promise to **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------- | | key | string | Yes | Key of the KV pair to delete. It cannot be empty.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.delete('startup'); promise.then(() => { @@ -514,16 +546,18 @@ promise.then(() => { flush(callback: AsyncCallback<void>): void -Saves the data of the **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result. +Asynchronously stores data of this **Preferences** instance to its persistent file. This API uses a asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.flush(function (err) { if (err) { @@ -539,16 +573,18 @@ preferences.flush(function (err) { flush(): Promise<void> -Saves the data of the **Preferences** instance to a file asynchronously. This API uses a promise to return the result. +Asynchronously stores data of this **Preferences** instance to its persistent file. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.flush(); promise.then(() => { @@ -568,11 +604,13 @@ Clears this **Preferences** instance. This API uses an asynchronous callback to **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.clear(function (err) { if (err) { @@ -593,11 +631,13 @@ Clears this **Preferences** instance. This API uses a promise to return the resu **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.clear() promise.then(() => { @@ -617,56 +657,14 @@ Subscribes to data changes. A callback will be triggered to return the new value **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Event type to subscribe to. The value **change** indicates data change events.| | callback | Callback<{ key : string }> | Yes | Callback invoked to return data changes. | **Example** -```js -data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { - if (err) { - console.info("Failed to get the preferences."); - return; - } - var observer = function (key) { - console.info("The key " + key + " changed."); - } - preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { - if (err) { - console.info("Failed to put the value of 'startup'. Cause: " + err); - return; - } - console.info("Put the value of 'startup' successfully."); - preferences.flush(function (err) { - if (err) { - console.info("Failed to flush data. Cause: " + err); - return; - } - console.info("Flushed data successfully."); // The observer will be called. - }) - }) -}) -``` - - -### off('change') - -off(type: 'change', callback?: Callback<{ key : string }>): void - -Unsubscribes from data changes. - -**System capability**: SystemCapability.DistributedDataManager.Preferences.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | -| callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.| - -**Example** ```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 296b8a58c2e89677eed23ee377c7568603429646..87c75a024fb144c72c0942e44b114a7d250a8008 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -36,9 +36,16 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext() + +// Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db"} -data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { +data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { if (err) { console.info("Failed to get RdbStore, err: " + err) return @@ -47,6 +54,28 @@ data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability' +var context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call getRdbStore. +const STORE_CONFIG = { name: "RdbTest.db"} +data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { + if (err) { + console.info("Failed to get RdbStore, err: " + err) + return + } + console.log("Got RdbStore successfully.") +}) +``` ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> @@ -71,9 +100,38 @@ Obtains an RDB store. This API uses a promise to return the result. You can set **Example** +FA model: + ```js +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext() + +// Call getRdbStore. +const STORE_CONFIG = { name: "RdbTest.db" } +let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1); +promise.then(async (rdbStore) => { + console.log("Got RdbStore successfully.") +}).catch((err) => { + console.log("Failed to get RdbStore, err: " + err) +}) +``` + +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability' +var context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db" } -let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1); +let promise = data_rdb.getRdbStore(context, STORE_CONFIG, 1); promise.then(async (rdbStore) => { console.log("Got RdbStore successfully.") }).catch((err) => { @@ -90,6 +148,7 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| @@ -97,8 +156,38 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** + +FA model: + ```js -data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext() + +// Call deleteRdbStore. +data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { + if (err) { + console.info("Failed to delete RdbStore, err: " + err) + return + } + console.log("Deleted RdbStore successfully.") +}) +``` + +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability' +var context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call deleteRdbStore. +data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { if (err) { console.info("Failed to delete RdbStore, err: " + err) return @@ -116,19 +205,29 @@ Deletes an RDB store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | name | string | Yes| Name of the RDB store to delete.| **Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| **Example** + +FA model: + ```js -let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext() + +// Call deleteRdbStore. +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") promise.then(()=>{ console.log("Deleted RdbStore successfully.") }).catch((err) => { @@ -136,6 +235,26 @@ promise.then(()=>{ }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability' +var context +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context + } +} + +// Call deleteRdbStore. +let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") +promise.then(()=>{ + console.log("Deleted RdbStore successfully.") +}).catch((err) => { + console.info("Failed to delete RdbStore, err: " + err) +}) +``` ## RdbPredicates @@ -152,11 +271,13 @@ A constructor used to create an **RdbPredicates** object. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | name | string | Yes| Database table name.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ``` @@ -166,21 +287,24 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates -Connects to the specified remote devices on the network during distributed database synchronization. +Sets an **RdbPredicates** to specify the remote devices on the network to connect during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | devices | Array<string> | Yes| IDs of the remote devices in the same network.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.inDevices(['12345678abcde']) @@ -191,16 +315,18 @@ predicates.inDevices(['12345678abcde']) inAllDevices(): RdbPredicates -Connects to all remote devices on the network during distributed database synchronization. +Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.inAllDevices() @@ -216,17 +342,20 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -243,17 +372,20 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notEqualTo("NAME", "lisi") @@ -270,11 +402,13 @@ Adds a left parenthesis to the **RdbPredicates**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a left parenthesis.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -285,22 +419,22 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` - ### endWrap endWrap(): RdbPredicates - Adds a right parenthesis to the **RdbPredicates**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with a right parenthesis.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") @@ -311,22 +445,22 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` - ### or or(): RdbPredicates - Adds the OR condition to the **RdbPredicates**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the OR condition.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") @@ -334,22 +468,22 @@ predicates.equalTo("NAME", "Lisa") .equalTo("NAME", "Rose") ``` - ### and and(): RdbPredicates - Adds the AND condition to the **RdbPredicates**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** with the AND condition.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") @@ -357,7 +491,6 @@ predicates.equalTo("NAME", "Lisa") .equalTo("SALARY", 200.5) ``` - ### contains contains(field: string, value: string): RdbPredicates @@ -367,193 +500,200 @@ Sets an **RdbPredicates** to match a string containing the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | string | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.contains("NAME", "os") ``` - ### beginsWith beginsWith(field: string, value: string): RdbPredicates - Sets an **RdbPredicates** to match a string that starts with the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | string | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.beginsWith("NAME", "os") ``` - ### endsWith endsWith(field: string, value: string): RdbPredicates - Sets an **RdbPredicates** to match a string that ends with the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | string | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.endsWith("NAME", "se") ``` - ### isNull isNull(field: string): RdbPredicates - Sets an **RdbPredicates** to match the field whose value is null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| -- Example +**Example** ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.isNull("NAME") ``` - ### isNotNull isNotNull(field: string): RdbPredicates - Sets an **RdbPredicates** to match the field whose value is not null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.isNotNull("NAME") ``` - ### like like(field: string, value: string): RdbPredicates - Sets an **RdbPredicates** to match a string that is similar to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | string | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.like("NAME", "%os%") ``` - ### glob glob(field: string, value: string): RdbPredicates - Sets an **RdbPredicates** to match the specified string. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | string | Yes| Value to match the **RdbPredicates**.

Wildcards are supported. * indicates zero, one, or multiple digits or characters. **?** indicates a single digit or character.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.glob("NAME", "?h*g") ``` - ### between between(field: string, low: ValueType, high: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| @@ -561,27 +701,28 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va | high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.between("AGE", 10, 50) ``` - ### notBetween notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| @@ -589,17 +730,18 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va | high | [ValueType](#valuetype) | Yes| Maximum value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notBetween("AGE", 10, 50) ``` - ### greaterThan greaterThan(field: string, value: ValueType): RdbPredicates @@ -609,259 +751,265 @@ Sets an **RdbPredicates** to match the field with data type **ValueType** and va **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThan("AGE", 18) ``` - ### lessThan lessThan(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThan("AGE", 20) ``` - ### greaterThanOrEqualTo - greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThanOrEqualTo("AGE", 18) ``` - ### lessThanOrEqualTo - lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | [ValueType](#valuetype) | Yes| Value to match the **RdbPredicates**.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThanOrEqualTo("AGE", 20) ``` - ### orderByAsc - orderByAsc(field: string): RdbPredicates - Sets an **RdbPredicates** to match the column with values sorted in ascending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByAsc("NAME") ``` - ### orderByDesc - orderByDesc(field: string): RdbPredicates - Sets an **RdbPredicates** to match the column with values sorted in descending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByDesc("AGE") ``` - ### distinct distinct(): RdbPredicates - Sets an **RdbPredicates** to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that can filter out duplicate records.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("NAME", "Rose").distinct("NAME") +predicates.equalTo("NAME", "Rose").distinct() ``` - ### limitAs limitAs(value: number): RdbPredicates - Sets an **RdbPredicates** to specify the maximum number of records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | number | Yes| Maximum number of records.| **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the maximum number of records.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").limitAs(3) ``` - ### offsetAs offsetAs(rowOffset: number): RdbPredicates - Sets an **RdbPredicates** to specify the start position of the returned result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the start position of the returned result.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").offsetAs(3) ``` - ### groupBy groupBy(fields: Array<string>): RdbPredicates - Sets an **RdbPredicates** to group rows that have the same value into summary rows. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fields | Array<string> | Yes| Names of columns to group.| **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that groups rows with the same value.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.groupBy(["AGE", "NAME"]) ``` - ### indexedBy indexedBy(field: string): RdbPredicates @@ -871,86 +1019,87 @@ Sets an **RdbPredicates** object to specify the index column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Name of the index column.| **Return value** + | Type| Description| | -------- | -------- | | [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that specifies the index column.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.indexedBy("SALARY_INDEX") ``` - ### in in(field: string, value: Array<ValueType>): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| - **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.in("AGE", [18, 20]) ``` - ### notIn notIn(field: string, value: Array<ValueType>): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | field | string | Yes| Column name in the database table.| | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| - **Return value** + | Type| Description| | -------- | -------- | -| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object that matches the specified field.| +| [RdbPredicates](#rdbpredicates) | **RdbPredicates** object created.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notIn("NAME", ["Lisa", "Rose"]) ``` - ## RdbStore Provides methods to manage an RDB store. Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). - ### insert insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void @@ -960,6 +1109,7 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| @@ -967,6 +1117,7 @@ Inserts a row of data into a table. This API uses an asynchronous callback to re | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| **Example** + ```js const valueBucket = { "NAME": "Lisa", @@ -983,7 +1134,6 @@ rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { }) ``` - ### insert insert(table: string, values: ValuesBucket):Promise<number> @@ -993,17 +1143,20 @@ Inserts a row of data into a table. This API uses a promise to return the result **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Row of data to insert.| **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Promise used to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| **Example** + ```js const valueBucket = { "NAME": "Lisa", @@ -1028,6 +1181,7 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| @@ -1035,6 +1189,7 @@ Batch inserts data into a table. This API uses an asynchronous callback to retur | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| **Example** + ```js const valueBucket1 = { "NAME": "Lisa", @@ -1074,17 +1229,20 @@ Batch inserts data into a table. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| | values | Array<[ValuesBucket](#valuesbucket)> | Yes| An array of data to insert.| **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| **Example** + ```js const valueBucket1 = { "NAME": "Lisa", @@ -1123,13 +1281,15 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** + ```js const valueBucket = { "NAME": "Rose", @@ -1148,7 +1308,6 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { }) ``` - ### update update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> @@ -1158,17 +1317,20 @@ Updates data based on the specified **RdbPredicates** object. This API uses a pr **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update in the RDB store. The key-value pair is associated with the column name in the target table.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Promise used to return the number of rows updated.| **Example** + ```js const valueBucket = { "NAME": "Rose", @@ -1191,9 +1353,12 @@ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.Data Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| @@ -1202,6 +1367,7 @@ Updates data in the RDB store based on the specified **DataSharePredicates** obj | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** + ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' const valueBucket = { @@ -1220,15 +1386,19 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { console.log("Updated row count: " + ret) }) ``` + ### update9+ update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| @@ -1236,11 +1406,13 @@ Updates data in the RDB store based on the specified **DataSharePredicates** obj | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Promise used to return the number of rows updated.| **Example** + ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' const valueBucket = { @@ -1263,18 +1435,19 @@ promise.then(async (ret) => { delete(predicates: RdbPredicates, callback: AsyncCallback<number>):void - Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") @@ -1287,7 +1460,6 @@ rdbStore.delete(predicates, function (err, rows) { }) ``` - ### delete delete(predicates: RdbPredicates):Promise<number> @@ -1297,16 +1469,19 @@ Deletes data from the RDB store based on the specified **RdbPredicates** object. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | predicates | [RdbPredicates](#rdbpredicates) | Yes| Conditions specified by the **RdbPredicates** object for deleting data.| **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Promise used to return the number of rows updated.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") @@ -1322,12 +1497,14 @@ promise.then((rows) => { delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| @@ -1335,6 +1512,7 @@ Deletes data from the RDB store based on the specified **DataSharePredicates** o | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| **Example** + ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() @@ -1347,26 +1525,32 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { console.log("Deleted rows: " + rows) }) ``` + ### delete9+ delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| | predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Promise used to return the number of rows updated.| **Example** + ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() @@ -1388,6 +1572,7 @@ Queries data from the RDB store based on specified conditions. This API uses an **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| @@ -1395,6 +1580,7 @@ Queries data from the RDB store based on specified conditions. This API uses an | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") @@ -1408,7 +1594,6 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e }) ``` - ### query query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> @@ -1418,17 +1603,20 @@ Queries data from the RDB store based on specified conditions. This API uses a p **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| | columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| **Return value** + | Type| Description| | -------- | -------- | | Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** + ```js let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") @@ -1447,9 +1635,12 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| @@ -1479,9 +1670,12 @@ query(table: string, predicates: dataSharePredicates.DataSharePredicates, column Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | table | string | Yes| Name of the target table.| @@ -1495,6 +1689,7 @@ Queries data from the RDB store based on specified conditions. This API uses a p | Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** + ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() @@ -1529,9 +1724,10 @@ Queries data from the RDB store of a remote device based on specified conditions **Example** ```js -let predicates = new rdb.RdbPredicates('EPLOYEE') +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EPLOYEE", predicates, function(err, resultSet){ +rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], + function(err, resultSet){ if (err) { console.info("Failed to remoteQuery, err: " + err) return @@ -1567,9 +1763,9 @@ Queries data from the RDB store of a remote device based on specified conditions **Example** ```js -let predicates = new rdb.RdbPredicates('EPLOYEE') +let predicates = new data_rdb.RdbPredicates('EMPLOYEE') predicates.greaterThan("id", 0) -let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates) +let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) promise.then((resultSet) => { console.info("ResultSet column names: " + resultSet.columnNames) console.info("ResultSet column count: " + resultSet.columnCount) @@ -1587,6 +1783,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| @@ -1594,6 +1791,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** + ```js rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo'], function (err, resultSet) { if (err) { @@ -1605,7 +1803,6 @@ rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", }) ``` - ### querySql8+ querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> @@ -1615,17 +1812,20 @@ Queries data in the RDB store using the specified SQL statement. This API uses a **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| | bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| **Return value** + | Type| Description| | -------- | -------- | | Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** + ```js let promise = rdbStore.querySql("SELECT * FROM EMPLOYEE CROSS JOIN BOOK WHERE BOOK.NAME = ?", ['sanguo']) promise.then((resultSet) => { @@ -1636,7 +1836,6 @@ promise.then((resultSet) => { }) ``` - ### executeSql executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void @@ -1646,6 +1845,7 @@ Executes an SQL statement that contains specified arguments but returns no value **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| @@ -1653,6 +1853,7 @@ Executes an SQL statement that contains specified arguments but returns no value | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** + ```js const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { @@ -1664,7 +1865,6 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { }) ``` - ### executeSql executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> @@ -1674,17 +1874,20 @@ Executes an SQL statement that contains specified arguments but returns no value **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| | bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| **Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| **Example** + ```js const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" let promise = rdbStore.executeSql(SQL_CREATE_TABLE) @@ -1704,19 +1907,24 @@ Starts the transaction before executing an SQL statement. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Example** + ```js -rdbStore.beginTransaction() -const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), -} -await rdbStore.insert("test", valueBucket) -rdbStore.commit() +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db"} +data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() +}) ``` - ### commit8+ commit():void @@ -1726,20 +1934,24 @@ Commits the executed SQL statements. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Example** -```js -rdbStore.beginTransaction() -const valueBucket = { - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), -} -await rdbStore.insert("test", valueBucket) -rdbStore.commit() +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db"} +data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { + rdbStore.beginTransaction() + const valueBucket = { + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() +}) ``` - ### rollBack8+ rollBack():void @@ -1749,21 +1961,27 @@ Rolls back the SQL statements that have been executed. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Example** + ```js -try { - rdbStore.beginTransaction() - const valueBucket = { - "id": 1, - "name": "lisi", - "age": 18, - "salary": 100.5, - "blobType": new Uint8Array([1, 2, 3]), - } - await rdbStore.insert("test", valueBucket) - rdbStore.commit() -} catch (e) { - rdbStore.rollBack() -} +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext() +const STORE_CONFIG = { name: "RdbTest.db"} +data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { + try { + rdbStore.beginTransaction() + const valueBucket = { + "id": 1, + "name": "lisi", + "age": 18, + "salary": 100.5, + "blobType": new Uint8Array([1, 2, 3]), + } + await rdbStore.insert("test", valueBucket) + rdbStore.commit() + } catch (e) { + rdbStore.rollBack() + } +}) ``` ### backup9+ @@ -1775,12 +1993,14 @@ Backs up an RDB store. This API uses an asynchronous callback to return the resu **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | destName | string | Yes| Name of the RDB store backup file.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** + ```js rdbStore.backup("dbBackup.db", function(err) { if (err) { @@ -1800,16 +2020,19 @@ Backs up an RDB store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | destName | string | Yes| Name of the RDB store backup file.| **Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| **Example** + ```js let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(()=>{ @@ -1828,12 +2051,14 @@ Restores an RDB store from a backup file. This API uses an asynchronous callback **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | srcName | string | Yes| Name of the RDB store backup file.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** + ```js rdbStore.restore("dbBackup.db", function(err) { if (err) { @@ -1853,16 +2078,19 @@ Restores an RDB store from a backup file. This API uses a promise to return the **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | srcName | string | Yes| Name of the RDB store backup file.| **Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| **Example** + ```js let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(()=>{ @@ -1883,12 +2111,14 @@ Sets distributed tables. This API uses an asynchronous callback to return the re **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | tables | Array<string> | Yes| Names of the distributed tables to set.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** + ```js rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { if (err) { @@ -1899,7 +2129,6 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { }) ``` - ### setDistributedTables8+ setDistributedTables(tables: Array<string>): Promise<void> @@ -1911,22 +2140,25 @@ Sets distributed tables. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | tables | Array<string> | Yes| Names of the distributed tables to set.| **Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| **Example** + ```js let promise = rdbStore.setDistributedTables(["EMPLOYEE"]) promise.then(() => { console.info("Set distributed tables successfully.") }).catch((err) => { - console.info('Failed to set distributed tables, err: ' + err) + console.info("Failed to set distributed tables, err: " + err) }) ``` @@ -1941,6 +2173,7 @@ Obtains the distributed table name for a remote device based on the local table **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | device | string | Yes| Remote device.| @@ -1948,6 +2181,7 @@ Obtains the distributed table name for a remote device based on the local table | callback | AsyncCallback<string> | Yes| Callback invoked to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| **Example** + ```js rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, tableName) { if (err) { @@ -1958,7 +2192,6 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, }) ``` - ### obtainDistributedTableName8+ obtainDistributedTableName(device: string, table: string): Promise<string> @@ -1970,17 +2203,20 @@ Obtains the distributed table name for a remote device based on the local table **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | device | string | Yes| Remote device.| | table | string | Yes| Local table name.| **Return value** + | Type| Description| | -------- | -------- | | Promise<string> | Promise used to return the result. If the operation succeeds, the distributed table name of the remote device is returned.| **Example** + ```js let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") promise.then((tableName) => { @@ -2001,6 +2237,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| @@ -2008,6 +2245,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret | callback | AsyncCallback<Array<[string, number]>> | Yes| Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | **Example** + ```js let predicates = new data_rdb.RdbPredicates('EMPLOYEE') predicates.inDevices(['12345678abcde']) @@ -2023,7 +2261,6 @@ rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicates, function (err, resul }) ``` - ### sync8+ sync(mode: SyncMode, predicates: RdbPredicates): Promise<Array<[string, number]>> @@ -2035,6 +2272,7 @@ Synchronizes data between devices. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| @@ -2047,6 +2285,7 @@ Synchronizes data between devices. This API uses a promise to return the result. | Promise<Array<[string, number]>> | Promise used to return the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | **Example** + ```js let predicates = new data_rdb.RdbPredicates('EMPLOYEE') predicates.inDevices(['12345678abcde']) @@ -2080,6 +2319,7 @@ Registers an observer for this RDB store. When the data in the RDB store changes | observer | Callback<Array<string>> | Yes| Observer that listens for the data changes in the RDB store.| **Example** + ```js function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { @@ -2112,6 +2352,7 @@ Unregisters the observer of the specified type from the RDB store. This API uses | observer | Callback<Array<string>> | Yes| Data change observer registered.| **Example** + ```js function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { @@ -2127,14 +2368,14 @@ try { ## StoreConfig -Manages the configuration of an RDB store. +Defines the RDB store configuration. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | name | string | Yes| Database file name.| - +| encrypt9+ | boolean | No| Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store, and the value **false** means the opposite.| ## ValueType diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md index cd1535b43bfe4e5d13a6460b066a082e31db8020..ff9f8d69e48847bd60741f174af4dbe92a19e2ee 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -55,7 +55,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); let storage = data_storage.getStorageSync(path + '/mystore'); @@ -88,7 +88,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.getStorage(path + '/mystore', function (err, storage) { @@ -131,7 +131,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); let getPromise = data_storage.getStorage(path + '/mystore'); @@ -167,7 +167,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.deleteStorageSync(path + '/mystore'); @@ -198,7 +198,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.deleteStorage(path + '/mystore', function (err) { @@ -239,7 +239,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); let promisedelSt = data_storage.deleteStorage(path + '/mystore'); @@ -274,7 +274,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.removeStorageFromCacheSync(path + '/mystore'); @@ -305,7 +305,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); data_storage.removeStorageFromCache(path + '/mystore', function (err) { @@ -347,7 +347,7 @@ var path; var context = featureAbility.getContext(); context.getFilesDir().then((filePath) => { path = filePath; - console.info("======================>getFilesDirPromsie====================>"); + console.info("======================>getFilesDirPromise====================>"); }); let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index 8d9a9c1b42bef6ce74fdfb21a8033b80e68c1868..ea8803f444dca95990cb00a015bfbad12f590639 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -8,7 +8,7 @@ Double-ended queue (deque) is a sequence container implemented based on the queu **Queue** follows the principle of FIFO only and allows element removal at the front and insertion at the rear. -**Vector** supports insertion and deletion of elements in between, as well asat both the ends. When compared with **Vector**, **Deque** is more efficient in inserting and removing header elements, but less efficient in accessing elements. +**Vector** supports insertion and deletion of elements in between, as well as at both the ends. When compared with **Vector**, **Deque** is more efficient in inserting and removing header elements, but less efficient in accessing elements. **Recommended use case**: Use **Deque** when you need to frequently insert or remove elements at both the ends of a container. diff --git a/en/application-dev/reference/apis/js-apis-dispatchInfo.md b/en/application-dev/reference/apis/js-apis-dispatchInfo.md index 5f476f34bd9ed8c08fc0e033243c1f4fb55ca23c..749ff83e51d077e066bc426c78a5e329510bf0c8 100644 --- a/en/application-dev/reference/apis/js-apis-dispatchInfo.md +++ b/en/application-dev/reference/apis/js-apis-dispatchInfo.md @@ -10,7 +10,9 @@ The **DispatchInfo** module provides dispatch information. **System capability**: SystemCapability.BundleManager.BundleFramework +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Readable| Writable| Description | | ----------- | ------ | ---- | ---- | ------------------------ | -| verison | string | Yes | No | Version of the API to dispatch.| +| version | string | Yes | No | Version of the API to dispatch.| | dispatchAPI | string | Yes | No | API to dispatch. | 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 46b962bb7e0dfbb16ea2ef4ba6a0bf2ac37ec5e0..efb9ce6224f75f0f56638fd209f888e45a65290c 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -19,6 +19,8 @@ getDistributedAccountAbility(): DistributedAccountAbility Obtains a **DistributedAccountAbility** instance. +**System capability**: SystemCapability.Account.OsAccount + - Return value | Type| Description| | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index 5682921badad9367817fd3e421b1afb823970425..7ad7cfe126f1186189c62cd525098aad770cdabd 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -61,7 +61,7 @@ export default class MyAbilityStage extends AbilityStage { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; } - console.log("Created KVManager"); + console.log("Created KVManager successfully"); kvManager = manager; }); } @@ -89,7 +89,7 @@ export default class MyAbilityStage extends AbilityStage { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; } - console.log("Created KVManager"); + console.log("Created KVManager successfully"); kvManager = manager; }); } @@ -139,7 +139,7 @@ export default class MyAbilityStage extends AbilityStage { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; } - console.log("Created KVManager"); + console.log("Created KVManager successfully"); kvManager = manager; }); } @@ -167,7 +167,7 @@ export default class MyAbilityStage extends AbilityStage { console.log("Failed to create KVManager: " + JSON.stringify(err)); return; } - console.log("Created KVManager"); + console.log("Created KVManager successfully"); kvManager = manager; }); } @@ -304,7 +304,7 @@ try { } ``` -### closeKVStore8+ ### +### closeKVStore8+ closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void @@ -350,7 +350,7 @@ const options = { ``` -### closeKVStore8+ ### +### closeKVStore8+ closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void> @@ -404,7 +404,7 @@ const options = { ``` -### deleteKVStore8+ ### +### deleteKVStore8+ deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void @@ -447,7 +447,7 @@ try { } ``` -### deleteKVStore8+ ### +### deleteKVStore8+ deleteKVStore(appId: string, storeId: string): Promise<void> @@ -501,7 +501,7 @@ try { ``` -### getAllKVStoreId8+ ### +### getAllKVStoreId8+ getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void @@ -531,7 +531,7 @@ try { ``` -### getAllKVStoreId8+ ### +### getAllKVStoreId8+ getAllKVStoreId(appId: string): Promise<string[]> @@ -570,7 +570,7 @@ try { ``` -### on('distributedDataServiceDie')8+ ### +### on('distributedDataServiceDie')8+ on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void @@ -582,8 +582,8 @@ Subscribes to service status changes. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates service status changes.| -| deathCallback | Callback<void> | Yes | Callback invoked to return service status changes.| +| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | Yes | Callback invoked to return a service status change event.| **Example** @@ -602,11 +602,11 @@ try { ``` -### off('distributedDataServiceDie')8+ ### +### off('distributedDataServiceDie')8+ off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void -Unsubscribes from the service status changes. +Unsubscribes from service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -614,8 +614,8 @@ Unsubscribes from the service status changes. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates service status changes.| -| deathCallback | Callback<void> | No | Callback used to return service status changes.| +| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | No | Callback used to return a service status change event.| **Example** @@ -706,7 +706,7 @@ Defines the schema of a KV store. You can create a **Schema** object and place i | mode8+ | number | Schema mode. | | skip8+ | number | Size of a skip of the schema. | -### constructor8+ ### +### constructor8+ constructor() @@ -726,7 +726,7 @@ Represents a **Schema** instance, which provides the methods for defining the va | default8+ | string | Default value of a **FieldNode**.| | type8+ | number | Value of the data type corresponding to the specified node.| -### constructor8+ ### +### constructor8+ constructor(name: string) @@ -740,7 +740,7 @@ A constructor used to create a **FieldNode** instance with a string field. | ------ | -------- | ---- | --------------- | | name | string | Yes | Value of **FieldNode**.| -### appendChild8+ ### +### appendChild8+ appendChild(child: FieldNode): boolean @@ -790,7 +790,7 @@ Provides methods to obtain the KV store result sets, and query and move the data Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. -### getCount8+ ### +### getCount8+ getCount(): number @@ -823,7 +823,7 @@ try { } ``` -### getPosition8+ ### +### getPosition8+ getPosition(): number @@ -857,7 +857,7 @@ try { ``` -### moveToFirst8+ ### +### moveToFirst8+ moveToFirst(): boolean @@ -891,7 +891,7 @@ try { ``` -### moveToLast8+ ### +### moveToLast8+ moveToLast(): boolean @@ -925,7 +925,7 @@ try { ``` -### moveToNext8+ ### +### moveToNext8+ moveToNext(): boolean @@ -959,7 +959,7 @@ try { ``` -### moveToPrevious8+ ### +### moveToPrevious8+ moveToPrevious(): boolean @@ -993,7 +993,7 @@ try { ``` -### move8+ ### +### move8+ move(offset: number): boolean @@ -1033,7 +1033,7 @@ try { ``` -### moveToPosition8+ ### +### moveToPosition8+ moveToPosition(position: number): boolean @@ -1073,7 +1073,7 @@ try { ``` -### isFirst8+ ### +### isFirst8+ isFirst(): boolean @@ -1107,7 +1107,7 @@ try { ``` -### isLast8+ ### +### isLast8+ isLast(): boolean @@ -1140,7 +1140,7 @@ try { } ``` -### isBeforeFirst8+ ### +### isBeforeFirst8+ isBeforeFirst(): boolean @@ -1174,7 +1174,7 @@ try { ``` -### isAfterLast8+ ### +### isAfterLast8+ isAfterLast(): boolean @@ -1208,7 +1208,7 @@ try { ``` -### getEntry8+ ### +### getEntry8+ getEntry(): Entry @@ -1248,7 +1248,7 @@ Provides methods to create a **Query** object, which defines different data quer **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -### constructor8+ ### +### constructor8+ constructor() @@ -1257,7 +1257,7 @@ A constructor used to create a **Schema** instance. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -### reset8+ ### +### reset8+ reset(): Query @@ -1288,7 +1288,7 @@ try { ``` -### equalTo8+ ### +### equalTo8+ equalTo(field: string, value: number|string|boolean): Query @@ -1323,7 +1323,7 @@ try { ``` -### notEqualTo8+ ### +### notEqualTo8+ notEqualTo(field: string, value: number|string|boolean): Query @@ -1358,7 +1358,7 @@ try { ``` -### greaterThan8+ ### +### greaterThan8+ greaterThan(field: string, value: number|string|boolean): Query @@ -1393,7 +1393,7 @@ try { ``` -### lessThan8+ ### +### lessThan8+ lessThan(field: string, value: number|string): Query @@ -1428,7 +1428,7 @@ try { ``` -### greaterThanOrEqualTo8+ ### +### greaterThanOrEqualTo8+ greaterThanOrEqualTo(field: string, value: number|string): Query @@ -1463,7 +1463,7 @@ try { ``` -### lessThanOrEqualTo8+ ### +### lessThanOrEqualTo8+ lessThanOrEqualTo(field: string, value: number|string): Query @@ -1498,7 +1498,7 @@ try { ``` -### isNull8+ ### +### isNull8+ isNull(field: string): Query @@ -1532,7 +1532,7 @@ try { ``` -### inNumber8+ ### +### inNumber8+ inNumber(field: string, valueList: number[]): Query @@ -1568,7 +1568,7 @@ try { ``` -### inString8+ ### +### inString8+ inString(field: string, valueList: string[]): Query @@ -1603,7 +1603,7 @@ try { ``` -### notInNumber8+ ### +### notInNumber8+ notInNumber(field: string, valueList: number[]): Query @@ -1638,7 +1638,7 @@ try { ``` -### notInString8+ ### +### notInString8+ notInString(field: string, valueList: string[]): Query @@ -1673,7 +1673,7 @@ try { ``` -### like8+ ### +### like8+ like(field: string, value: string): Query @@ -1708,7 +1708,7 @@ try { ``` -### unlike8+ ### +### unlike8+ unlike(field: string, value: string): Query @@ -1743,7 +1743,7 @@ try { ``` -### and8+ ### +### and8+ and(): Query @@ -1773,7 +1773,7 @@ try { ``` -### or8+ ### +### or8+ or(): Query @@ -1803,7 +1803,7 @@ try { ``` -### orderByAsc8+ ### +### orderByAsc8+ orderByAsc(field: string): Query @@ -1838,7 +1838,7 @@ try { ``` -### orderByDesc8+ ### +### orderByDesc8+ orderByDesc(field: string): Query @@ -1873,7 +1873,7 @@ try { ``` -### limit8+ ### +### limit8+ limit(total: number, offset: number): Query @@ -1911,7 +1911,7 @@ try { ``` -### isNotNull8+ ### +### isNotNull8+ isNotNull(field: string): Query @@ -1945,7 +1945,7 @@ try { ``` -### beginGroup8+ ### +### beginGroup8+ beginGroup(): Query @@ -1975,7 +1975,7 @@ try { ``` -### endGroup8+ ### +### endGroup8+ endGroup(): Query @@ -2005,7 +2005,7 @@ try { ``` -### prefixKey8+ ### +### prefixKey8+ prefixKey(prefix: string): Query @@ -2040,7 +2040,7 @@ try { ``` -### setSuggestIndex8+ ### +### setSuggestIndex8+ setSuggestIndex(index: string): Query @@ -2075,7 +2075,7 @@ try { ``` -### deviceId8+ ### +### deviceId8+ deviceId(deviceId:string):Query @@ -2109,7 +2109,7 @@ try { ``` -### getSqlLike8+ ### +### getSqlLike8+ getSqlLike():string @@ -2303,7 +2303,9 @@ try { delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) -Deletes KV pairs that meet the specified predicates. This API uses an asynchronous callback to return the result. +Deletes KV pairs that meet the specified conditions. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2337,7 +2339,9 @@ try { delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> -Deletes KV pairs that meet the specified predicates. This API uses a promise to return the result. +Deletes KV pairs that meet the specified conditions. This API uses a promise to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2352,7 +2356,7 @@ Deletes KV pairs that meet the specified predicates. This API uses a promise to | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2379,11 +2383,224 @@ try { ``` +### backup9+ + +backup(file:string, callback: AsyncCallback<void>):void + +Backs up an RDB store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is the error object. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file, (err, data) => { + if (err) { + console.info("backup err : " + err); + } else { + console.info("backup data : " + data); + } + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### backup9+ + +backup(file:string): Promise<void> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database. This parameter cannot be empty and its length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file).then((data) => { + console.info("backup data : " + data); + }).catch((err) => { + console.info("backup err : " + err); + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### restore9+ + +restore(file:string, callback: AsyncCallback<void>):void + +Restores an RDB store from a database file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file, (err, data) => { + if (err) { + console.info("restore err : " + err); + } else { + console.info("restore data : " + data); + } + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### restore9+ + +restore(file:string): Promise<void> + +Restores an RDB store from a database file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file).then((data) => { + console.info("restore data : " + data); + }).catch((err) => { + console.info("restore err : " + err); + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### deleteBackup9+ + +deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void + +Deletes a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | +| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files, (err, data) => { + if (err) { + console.info("deleteBackup err : " + err); + } else { + console.info("deleteBackup data : " + data); + } + }); +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + +### deleteBackup9+ + +deleteBackup(files:Array<string>): Promise<Array<[string, number]>> + +Deletes a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------------------------------------- | ----------------------------------------------- | +| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files).then((data) => { + console.info("deleteBackup data : " + data); + }).catch((err) => { + console.info("deleteBackup err : " + err); + }) +} catch (e) { + console.log("An unexpected error occurred. Error : " + e); +} + +``` + ### on('dataChange') on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data change notifications of the specified type. +Subscribes to data changes of the specified type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2391,9 +2608,9 @@ Subscribes to data change notifications of the specified type. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | +| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return a data change event.| **Example** @@ -2409,7 +2626,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to data synchronization complete events. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2417,8 +2634,8 @@ Subscribes to data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return the data synchronization result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback used to return a synchronization complete event. | **Example** @@ -2433,7 +2650,7 @@ kvStore.on('syncComplete', function (data) { off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from data change notifications. +Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2441,26 +2658,35 @@ Unsubscribes from data change notifications. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return a data change event.| **Example** ```js let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); +class KvstoreModel { + call(data) { + console.log("dataChange: " + data); + } + subscribeDataChange() { + if (kvStore != null) { + kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } + unsubscribeDataChange() { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } +} ``` ### off('syncComplete')9+ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from data change events. This API uses a synchronous callback to return the result. +Unsubscribes from data changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2468,21 +2694,27 @@ Unsubscribes from data change events. This API uses a synchronous callback to re | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return a synchronization complete event. | **Example** ```js let kvStore; -try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); -}catch(e) { - console.log('syncComplete e ' + e); +class KvstoreModel { + call(data) { + console.log("syncComplete: " + data); + } + subscribeSyncComplete() { + if (kvStore != null) { + kvStore.on('syncComplete', this.call); + } + } + unsubscribeSyncComplete() { + if (kvStore != null) { + kvStore.off('syncComplete', this.call); + } + } } ``` @@ -2592,7 +2824,9 @@ try { putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void -Writes data to this KV store. This API uses an asynchronous callback to return the result. +Writes data to this KV store. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2631,7 +2865,9 @@ try { putBatch(value: Array<ValuesBucket>): Promise<void> -Writes data of the **valuesbucket** type to this KV store. This API uses a promise to return the result. +Write data to this KV store. This API uses a promise to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2645,7 +2881,7 @@ Writes data of the **valuesbucket** type to this KV store. This API uses a promi | Type | Description | | ------ | ------- | -| Promise<void> |Promise used to return the result.| +| Promise<void> |Promise that returns no value.| **Example** @@ -2719,7 +2955,7 @@ try { ``` -### deleteBatch8+ ### +### deleteBatch8+ deleteBatch(keys: string[]): Promise<void> @@ -2775,7 +3011,7 @@ try { ``` -### startTransaction8+ ### +### startTransaction8+ startTransaction(callback: AsyncCallback<void>): void @@ -2827,7 +3063,7 @@ try { ``` -### startTransaction8+ ### +### startTransaction8+ startTransaction(): Promise<void> @@ -2862,7 +3098,7 @@ try { ``` -### commit8+ ### +### commit8+ commit(callback: AsyncCallback<void>): void @@ -2894,7 +3130,7 @@ try { ``` -### commit8+ ### +### commit8+ commit(): Promise<void> @@ -2924,7 +3160,7 @@ try { ``` -### rollback8+ ### +### rollback8+ rollback(callback: AsyncCallback<void>): void @@ -2956,7 +3192,7 @@ try { ``` -### rollback8+ ### +### rollback8+ rollback(): Promise<void> @@ -2986,7 +3222,7 @@ try { ``` -### enableSync8+ ### +### enableSync8+ enableSync(enabled: boolean, callback: AsyncCallback<void>): void @@ -3019,7 +3255,7 @@ try { ``` -### enableSync8+ ### +### enableSync8+ enableSync(enabled: boolean): Promise<void> @@ -3055,7 +3291,7 @@ try { ``` -### setSyncRange8+ ### +### setSyncRange8+ setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void @@ -3087,7 +3323,7 @@ try { ``` -### setSyncRange8+ ### +### setSyncRange8+ setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> @@ -3279,7 +3515,7 @@ try { } ``` -### getEntries8+ ### +### getEntries8+ getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void @@ -3325,7 +3561,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(keyPrefix: string): Promise<Entry[]> @@ -3383,7 +3619,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void @@ -3434,7 +3670,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(query: Query): Promise<Entry[]> @@ -3492,7 +3728,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void @@ -3541,7 +3777,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(keyPrefix: string): Promise<KvStoreResultSet> @@ -3601,7 +3837,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void @@ -3649,7 +3885,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(query: Query): Promise<KvStoreResultSet> @@ -3705,12 +3941,14 @@ try { } ``` -### getResultSet9+ ### +### getResultSet9+ getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** @@ -3740,12 +3978,14 @@ try { console.log('An unexpected error occurred. Error:' + e); } ``` -### getResultSet9+ ### +### getResultSet9+ getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** @@ -3758,7 +3998,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **DataSharePred | Type | Description | | ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise that returns no value.| **Example** @@ -3780,7 +4020,7 @@ try { console.log('An unexpected error occurred. Error:' + e); } ``` -### closeResultSet8+ ### +### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void @@ -3814,7 +4054,7 @@ try { ``` -### closeResultSet8+ ### +### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet): Promise<void> @@ -3851,7 +4091,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(query: Query, callback: AsyncCallback<number>): void @@ -3897,7 +4137,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(query: Query): Promise<number> @@ -3952,7 +4192,7 @@ try { ``` -### removeDeviceData8+ ### +### removeDeviceData8+ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void @@ -3994,7 +4234,7 @@ try { ``` -### removeDeviceData8+ ### +### removeDeviceData8+ removeDeviceData(deviceId: string): Promise<void> @@ -4043,11 +4283,11 @@ try { ``` -### on('syncComplete')8+ ### +### on('syncComplete')8+ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to the data synchronization complete events. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4055,8 +4295,8 @@ Subscribes to the data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called to return the synchronization result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return a synchronization complete event. | **Example** @@ -4079,11 +4319,11 @@ try { ``` -### off('syncComplete')8+ ### +### off('syncComplete')8+ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the data synchronization complete events. +Unsubscribes from synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4091,25 +4331,31 @@ Unsubscribes from the data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates completion of a data synchronization. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return the synchronization result. | +| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | +| syncCallback |Callback<Array<[string, number]>> | No |Callback used to return a synchronization complete event. | **Example** ```js let kvStore; -try { - const func = function (data) { - console.log('syncComplete ' + data) - }; - kvStore.on('syncComplete', func); - kvStore.off('syncComplete', func); -}catch(e) { - console.log('syncComplete e ' + e); +class KvstoreModel { + call(data) { + console.log("syncComplete: " + data); + } + subscribeSyncComplete() { + if (kvStore != null) { + kvStore.on('syncComplete', this.call); + } + } + unsubscribeSyncComplete() { + if (kvStore != null) { + kvStore.off('syncComplete', this.call); + } + } } ``` -### on('dataChange')9+ ### +### on('dataChange')9+ on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void @@ -4121,9 +4367,9 @@ Subscribes to data changes of the specified type. This API returns the result sy | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | +| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| **Example** @@ -4135,11 +4381,11 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun ``` -### off('dataChange')9+ ### +### off('dataChange')9+ off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API returns the result synchronously. +Unsubscribes from data changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4147,19 +4393,28 @@ Unsubscribes from the data change events. This API returns the result synchronou | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return a data change event.| **Example** ```js let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); +class KvstoreModel { + call(data) { + console.log("dataChange: " + data); + } + subscribeDataChange() { + if (kvStore != null) { + kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } + unsubscribeDataChange() { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } +} ``` ### sync7+ @@ -4229,7 +4484,7 @@ try { } ``` -### setSyncParam8+ ### +### setSyncParam8+ setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void @@ -4259,7 +4514,7 @@ try { ``` -### setSyncParam8+ ### +### setSyncParam8+ setSyncParam(defaultAllowedDelayMs: number): Promise<void> @@ -4297,7 +4552,7 @@ try { ``` -### getSecurityLevel8+ ### +### getSecurityLevel8+ getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void @@ -4325,7 +4580,7 @@ try { ``` -### getSecurityLevel8+ ### +### getSecurityLevel8+ getSecurityLevel(): Promise<SecurityLevel> @@ -4365,7 +4620,7 @@ For example, a device KV store can be used to implement image sharing between de Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. -### get8+ ### +### get8+ get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void @@ -4400,7 +4655,7 @@ try{ ``` -### get8+ ### +### get8+ get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> @@ -4444,7 +4699,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void @@ -4492,7 +4747,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> @@ -4551,7 +4806,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(query: Query, callback: AsyncCallback<Entry[]>): void @@ -4603,7 +4858,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(query: Query): Promise<Entry[]> @@ -4661,7 +4916,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void @@ -4714,7 +4969,7 @@ try { ``` -### getEntries8+ ### +### getEntries8+ getEntries(deviceId: string, query: Query): Promise<Entry[]> @@ -4774,7 +5029,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void @@ -4809,7 +5064,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> @@ -4853,7 +5108,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void @@ -4905,7 +5160,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(query: Query): Promise<KvStoreResultSet> @@ -4969,7 +5224,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void @@ -5021,7 +5276,7 @@ try { ``` -### getResultSet8+ ### +### getResultSet8+ getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> @@ -5087,7 +5342,7 @@ try { ``` -### closeResultSet8+ ### +### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void @@ -5122,7 +5377,7 @@ try { ``` -### closeResultSet8+ ### +### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet): Promise<void> @@ -5160,7 +5415,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(query: Query, callback: AsyncCallback<number>): void @@ -5207,7 +5462,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(query: Query): Promise<number> @@ -5263,7 +5518,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; @@ -5310,7 +5565,7 @@ try { ``` -### getResultSize8+ ### +### getResultSize8+ getResultSize(deviceId: string, query: Query): Promise<number> @@ -5366,7 +5621,7 @@ try { ``` -### removeDeviceData8+ ### +### removeDeviceData8+ removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void @@ -5408,7 +5663,7 @@ try { ``` -### removeDeviceData8+ ### +### removeDeviceData8+ removeDeviceData(deviceId: string): Promise<void> @@ -5457,7 +5712,7 @@ try { ``` -### sync8+ ### +### sync8+ sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void @@ -5496,7 +5751,7 @@ try { } ``` -### sync9+ ### +### sync9+ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void @@ -5538,11 +5793,11 @@ try { } ``` -### on('syncComplete')8+ ### +### on('syncComplete')8+ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to the data synchronization complete events. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5550,8 +5805,8 @@ Subscribes to the data synchronization complete events. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates the data synchronization complete event.| -| syncCallback |Callback | Yes |Callback used to return the synchronization result. | +| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback |Callback | Yes |Callback invoked to return a synchronization complete event. | **Example** @@ -5574,11 +5829,11 @@ try { ``` -### off('syncComplete')8+ ### +### off('syncComplete')8+ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization complete events. This API returns the result synchronously. +Unsubscribes from synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5586,25 +5841,31 @@ Unsubscribes from the synchronization complete events. This API returns the resu | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates the data synchronization complete event.| -| syncCallback |Callback9+ ### +### on('dataChange')9+ on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void @@ -5616,9 +5877,9 @@ Subscribes to data changes of the specified type. This API returns the result sy | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | -| type |[SubscribeType](#subscribetype) | Yes |Subscription type. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the result.| +| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | +| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| **Example** @@ -5630,11 +5891,11 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun ``` -### off('dataChange')9+ ### +### off('dataChange')9+ off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API returns the result synchronously. +Unsubscribes from data changes. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5642,19 +5903,28 @@ Unsubscribes from the data change events. This API returns the result synchronou | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the result.| +| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return a data change event.| **Example** ```js let kvStore; -kvStore.on('dataChange', function (data) { - console.log("callback call data: " + data); -}); -kvStore.off('dataChange', function (data) { - console.log("callback call data: " + data); -}); +class KvstoreModel { + call(data) { + console.log("dataChange: " + data); + } + subscribeDataChange() { + if (kvStore != null) { + kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } + unsubscribeDataChange() { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } +} ``` ## SyncMode @@ -5668,4 +5938,3 @@ Enumerates the synchronization modes. | PULL_ONLY |0 |Pull data from the peer end to the local end only.| | PUSH_ONLY |1 |Push data from the local end to the peer end only.| | PUSH_PULL |2 |Push data from the local end to the peer end and then pull data from the peer end to the local end.| - diff --git a/en/application-dev/reference/apis/js-apis-effectKit.md b/en/application-dev/reference/apis/js-apis-effectKit.md index 089bf96cb239204c4b52c3ce71848f15141d76a4..498bc3beb398e1f7b3b6fc20657ef01fec0b8bb1 100644 --- a/en/application-dev/reference/apis/js-apis-effectKit.md +++ b/en/application-dev/reference/apis/js-apis-effectKit.md @@ -40,13 +40,14 @@ Creates a **Filter** instance based on the pixel map. **Example** ```js -import image from "@ohos.multimedia.image" +import image from "@ohos.multimedia.image"; + const color = new ArrayBuffer(96); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; -image.createPixelMap(color, opts) - .then((pixelMap) => { - let headFilter = effectKit.createEffect(pixelMap) - }) +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelMap) => { + let headFilter = effectKit.createEffect(pixelMap); +}) ``` ## effectKit.createColorPicker @@ -67,19 +68,20 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses a promi | Type | Description | | ---------------------- | -------------- | -| Promisse\<[ColorPicker](#colorpicker)> | Promise used to return the **ColorPicker** instance created.| +| Promise\<[ColorPicker](#colorpicker)> | Promise used to return the **ColorPicker** instance created.| **Example** ```js -import image from "@ohos.multimedia.image" +import image from "@ohos.multimedia.image"; + const color = new ArrayBuffer(96); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; -image.createPixelMap(color, opts, (pixelMap) => { - effectKit.createColorPicker(pixelMap).then(colorPicker => { - console.info("color picker=" + colorPicker); - }) - .catch(ex => console.error(".error=" + ex.toString())) +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelMap) => { + effectKit.createColorPicker(pixelMap).then(colorPicker => { + console.info("color picker=" + colorPicker); + }).catch(ex => console.error(".error=" + ex.toString())) }) ``` @@ -101,17 +103,19 @@ Creates a **ColorPicker** instance based on the pixel map. This API uses an asyn **Example** ```js -import image from "@ohos.multimedia.image" +import image from "@ohos.multimedia.image"; + const color = new ArrayBuffer(96); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; -image.createPixelMap(color, opts, (pixelMap) => { - effectKit.createColorPicker(pixelMap, (error, colorPicker) => { - if(error) { - console.log('Failed to create color picker.'); - } else { - console.log('Succeeded in creating color picker.'); - } - }) +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelMap) => { + effectKit.createColorPicker(pixelMap, (error, colorPicker) => { + if (error) { + console.log('Failed to create color picker.'); + } else { + console.log('Succeeded in creating color picker.'); + } + }) }) ``` @@ -150,7 +154,7 @@ Obtains the main color of the image and writes the result to a **[Color](#color) ```js colorPicker.getMainColor().then(color => { - console.log('Succeeded in getting main color.') + console.log('Succeeded in getting main color.'); console.info("color[ARGB]=" + color.alpha + "," + color.red + "," + color.green + "," + color.blue); }).catch(error => { console.log('Failed to get main color.'); @@ -205,17 +209,17 @@ Adds the blur effect to the filter linked list, and returns the head node of the **Example** ```js -import image from "@ohos.multimedia.image" +import image from "@ohos.multimedia.image"; + const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; -image.createPixelMap(color, opts) - .then((pixelMap) => { - let radius = 5; - let headFilter = effectKit.createEffect(pixelMap) - if (headFilter != null) { - headFilter.blur(radius) - } - }) +image.createPixelMap(color, opts).then((pixelMap) => { + let radius = 5; + let headFilter = effectKit.createEffect(pixelMap); + if (headFilter != null) { + headFilter.blur(radius); + } +}) ``` ### brightness @@ -241,17 +245,17 @@ Adds the brightness effect to the filter linked list, and returns the head node **Example** ```js -import image from "@ohos.multimedia.image" +import image from "@ohos.multimedia.image"; + const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; -image.createPixelMap(color, opts) - .then((pixelMap) => { - let bright = 0.5; - let headFilter = effectKit.createEffect(pixelMap) - if (headFilter != null) { - headFilter.brightness(bright) - } - }) +image.createPixelMap(color, opts).then((pixelMap) => { + let bright = 0.5; + let headFilter = effectKit.createEffect(pixelMap); + if (headFilter != null) { + headFilter.brightness(bright); + } +}) ``` ### grayscale @@ -271,16 +275,16 @@ Adds the grayscale effect to the filter linked list, and returns the head node o **Example** ```js -import image from "@ohos.multimedia.image" +import image from "@ohos.multimedia.image"; + const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; -image.createPixelMap(color, opts) - .then((pixelMap) => { - let headFilter = effectKit.createEffect(pixelMap) - if (headFilter != null) { - headFilter.grayscale() - } - }) +image.createPixelMap(color, opts).then((pixelMap) => { + let headFilter = effectKit.createEffect(pixelMap); + if (headFilter != null) { + headFilter.grayscale(); + } +}) ``` ### getPixelMap @@ -300,11 +304,11 @@ Obtains **image.PixelMap** of the source image to which the filter linked list i **Example** ```js -import image from "@ohos.multimedia.image" +import image from "@ohos.multimedia.image"; + const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } }; -image.createPixelMap(color, opts) - .then((pixelMap) => { - let pixel = effectKit.createEffect(pixelMap).grayscale().getPixelMap() - }) +image.createPixelMap(color, opts).then((pixelMap) => { + let pixel = effectKit.createEffect(pixelMap).grayscale().getPixelMap(); +}) ``` diff --git a/en/application-dev/reference/apis/js-apis-errorManager.md b/en/application-dev/reference/apis/js-apis-errorManager.md index 69d3c3bf8240d370a364294d4089aa445f3809cc..4a39fdd6b0031be7e3fcbdfc7a570609ba217a1b 100644 --- a/en/application-dev/reference/apis/js-apis-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-errorManager.md @@ -33,8 +33,7 @@ var observer = { console.log('onUnhandledException, errorMsg: ', errorMsg) } } -const registerErrorObserverNumber=errorManager.registerErrorObserver(observer) -console.info(registerErrorObserverNumber) +errorManager.registerErrorObserver(observer) ``` ## ErrorManager.unregisterErrorObserver @@ -123,11 +122,4 @@ var observer = { } } errorManager.registerErrorObserver(observer) - .then((data) => { - console.log('----------- registerErrorObserver success ----------', data); - }) - .catch((err) => { - console.log('----------- registerErrorObserver fail ----------', err); - }) - ``` diff --git a/en/application-dev/reference/apis/js-apis-eventhub.md b/en/application-dev/reference/apis/js-apis-eventhub.md index ca1b1500dcb8836b73abd13e837a0255a78a3a5f..9ae7db735cbc61fa55a764cb285801297452c5d8 100644 --- a/en/application-dev/reference/apis/js-apis-eventhub.md +++ b/en/application-dev/reference/apis/js-apis-eventhub.md @@ -9,10 +9,10 @@ The **EventHub** module provides APIs to subscribe to, unsubscribe from, and tri ## Usage -​Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. +Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. ```js -import Ability from '@ohos.application.Ability' +import Ability from '@ohos.application.Ability'; export default class MainAbility extends Ability { func1(){ console.log("func1 is called"); @@ -34,15 +34,15 @@ Subscribes to an event. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | callback | Function | Yes| Callback invoked when the event is triggered.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| callback | Function | Yes| Callback invoked when the event is triggered.| **Example** ```js - import Ability from '@ohos.application.Ability' + import Ability from '@ohos.application.Ability'; export default class MainAbility extends Ability { onForeground() { @@ -72,15 +72,15 @@ Unsubscribes from an event. If **callback** is specified, this API unsubscribes **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| **Example** ```js - import Ability from '@ohos.application.Ability' + import Ability from '@ohos.application.Ability'; export default class MainAbility extends Ability { onForeground() { @@ -110,15 +110,15 @@ Triggers an event. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | string | Yes| Event name.| - | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| **Example** ```js - import Ability from '@ohos.application.Ability' + import Ability from '@ohos.application.Ability'; export default class MainAbility extends Ability { onForeground() { diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md index 66b794234a41c9e57977946adbf02a9f35182b60..841f7755273489a570865b41c63c5103c3af0c9a 100644 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md @@ -12,9 +12,9 @@ The **ExtensionRunningInfo** module provides running information and states for The Extension ability running information is obtained through an **abilityManager** instance. ```js -import abilitymanager from '@ohos.application.abilityManager'; +import abilityManager from '@ohos.application.abilityManager'; let upperLimit=1 -abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { +abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-formInfo.md b/en/application-dev/reference/apis/js-apis-formInfo.md index eace629fc87a608f2235f9887c4b0e075ce38b4e..950da73f21bd3ac1ee8e8fe8a57989714a95d6dd 100644 --- a/en/application-dev/reference/apis/js-apis-formInfo.md +++ b/en/application-dev/reference/apis/js-apis-formInfo.md @@ -105,7 +105,7 @@ Enumerates the widget parameters. | TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | | ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | Ability name. | | DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID.
This is a system API. | -| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.
This is a system API. | +| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| ## FormDimension diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index 022682c82230162ebb586898aed0b54ac6a59e30..e3c08ce24cf92eda9534812d664aa466c4b7c1ef 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -89,7 +89,7 @@ Writes event information to the event file. This API uses a promise to return th | Name | Type | Mandatory| Description| | --------- | ----------------------- | ---- | --------------- | -| eventType | [EventType](#eventtype) | Yes | Application event type.| +| info | [SysEventInfo](#syseventinfo) | Yes | System event information.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-huks.md b/en/application-dev/reference/apis/js-apis-huks.md index 6cd14aeb285b3ec93581dbc7f425d06eda1907c5..2d66bc9c61a54f3bfa88d6e7f27aa93fabd49a2d 100644 --- a/en/application-dev/reference/apis/js-apis-huks.md +++ b/en/application-dev/reference/apis/js-apis-huks.md @@ -59,8 +59,8 @@ Enumerates the error codes. | HUKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST | -36 |New root key material exists.| | HUKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL | -37 |Failed to update the root key material.| | HUKS_ERROR_VERIFICATION_FAILED | -38 |Failed to verify the certificate chain.| -| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the current user.| -| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the current user.| +| HUKS_ERROR_GET_USERIAM_SECINFO_FAILED9+ | -40 |Failed to obtain the security attribute information of the user.| +| HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED9+ | -41 |Failed to obtain the authentication information of the user.| | HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT9+ | -42 |The access control of the current authentication type is not supported.| | HUKS_ERROR_KEY_AUTH_FAILED9+ | -43 |The access control authentication has failed.| | HUKS_ERROR_DEVICE_NO_CREDENTIAL9+ | -44 |No credential has been enrolled for the device.| @@ -154,7 +154,7 @@ Enumerates the cipher modes. | Name | Value | Description | | ------------- | ---- | --------------------- | -| HUKS_MODE_ECB | 1 | Electronic Code bLock (ECB) mode| +| HUKS_MODE_ECB | 1 | Electronic Code BLock (ECB) mode| | HUKS_MODE_CBC | 2 | Cipher Block Chaining (CBC) mode| | HUKS_MODE_CTR | 3 | Counter (CTR) mode| | HUKS_MODE_OFB | 4 | Output Feedback (OFB) mode| @@ -297,7 +297,7 @@ Enumerates the user authentication types. ## HuksAuthAccessType9+ -Enumerates access control types. +Enumerates the access control types. **System capability**: SystemCapability.Security.Huks @@ -320,7 +320,7 @@ Enumerates the types of the challenges generated when a key is used. ## HuksChallengePosition9+ -Enumerates the positions of the 8-byte custom challenges. +Enumerates the positions of the 8-byte valid value in a custom challenge generated. **System capability**: SystemCapability.Security.Huks @@ -363,90 +363,90 @@ Enumerates the tags used to invoke parameters. **System capability**: SystemCapability.Security.Huks -| Name | Value | Description | -| -------------------------------------------- | ---------------------------------------- | ------------------------------------------------------------ | -| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | -| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | -| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. | -| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | -| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | -| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | -| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | -| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | -| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | -| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | -| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | -| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | -| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | -| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | -| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | -| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | -| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | -| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | -| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | -| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | -| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | -| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | -| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | -| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | -| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | -| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite used when a wrapped key is imported. | -| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | -| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | -| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | -| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | -| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | -| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | -| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | -| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set two of **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, and **HKS_USER_AUTH_TYPE_FACE**. | -| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | -| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | -| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9). | -| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported. | -| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9). | -| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-bypte custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9). | -| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | +| Name | Value | Description | +| -------------------------------------------- | ---------------------------------------- | -------------------------------------- | +| HUKS_TAG_INVALID | HuksTagType.HUKS_TAG_TYPE_INVALID \| 0 | Invalid tag. | +| HUKS_TAG_ALGORITHM | HUKS_TAG_TYPE_UINT \| 1 | Algorithm. | +| HUKS_TAG_PURPOSE | HuksTagType.HUKS_TAG_TYPE_UINT \| 2 | Purpose of a key. | +| HUKS_TAG_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 3 | Key size. | +| HUKS_TAG_DIGEST | HuksTagType.HUKS_TAG_TYPE_UINT \| 4 | Digest algorithm. | +| HUKS_TAG_PADDING | HuksTagType.HUKS_TAG_TYPE_UINT \| 5 | Padding algorithm. | +| HUKS_TAG_BLOCK_MODE | HuksTagType.HUKS_TAG_TYPE_UINT \| 6 | Cipher mode. | +| HUKS_TAG_KEY_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 7 | Key type. | +| HUKS_TAG_ASSOCIATED_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 8 | Associated authentication data. | +| HUKS_TAG_NONCE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 9 | Field for key encryption and decryption. | +| HUKS_TAG_IV | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10 | IV. | +| HUKS_TAG_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 11 | Information generated during key derivation. | +| HUKS_TAG_SALT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 12 | Salt value used for key derivation. | +| HUKS_TAG_PWD | HuksTagType.HUKS_TAG_TYPE_BYTES \| 13 | Password used for key derivation. | +| HUKS_TAG_ITERATION | HuksTagType.HUKS_TAG_TYPE_UINT \| 14 | Number of iterations for key derivation. | +| HUKS_TAG_KEY_GENERATE_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 15 | Key generation type. | +| HUKS_TAG_DERIVE_MAIN_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 16 | Main key for key derivation. | +| HUKS_TAG_DERIVE_FACTOR | HuksTagType.HUKS_TAG_TYPE_BYTES \| 17 | Factor for key derivation. | +| HUKS_TAG_DERIVE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 18 | Type of the algorithm used for key derivation. | +| HUKS_TAG_AGREE_ALG | HuksTagType.HUKS_TAG_TYPE_UINT \| 19 | Type of the algorithm used for key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 20 | Public key alias used in key agreement. | +| HUKS_TAG_AGREE_PRIVATE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 21 | Private key alias used in key agreement. | +| HUKS_TAG_AGREE_PUBLIC_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 22 | Public key used in key agreement. | +| HUKS_TAG_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 23 | Key alias. | +| HUKS_TAG_DERIVE_KEY_SIZE | HuksTagType.HUKS_TAG_TYPE_UINT \| 24 | Size of the derived key. | +| HUKS_TAG_IMPORT_KEY_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 25 | Type of the imported key. | +| HUKS_TAG_UNWRAP_ALGORITHM_SUITE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 26 | Algorithm suite used when a wrapped key is imported. | +| HUKS_TAG_ACTIVE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 201 | Reserved. | +| HUKS_TAG_ORIGINATION_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 202 | Reserved. | +| HUKS_TAG_USAGE_EXPIRE_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 203 | Reserved. | +| HUKS_TAG_CREATION_DATETIME | HuksTagType.HUKS_TAG_TYPE_ULONG \| 204 | Reserved. | +| HUKS_TAG_ALL_USERS | ksTagType.HUKS_TAG_TYPE_BOOL \| 301 | Reserved. | +| HUKS_TAG_USER_ID | HuksTagType.HUKS_TAG_TYPE_UINT \| 302 | Reserved. | +| HUKS_TAG_NO_AUTH_REQUIRED | HuksTagType.HUKS_TAG_TYPE_BOOL \| 303 | Reserved. | +| HUKS_TAG_USER_AUTH_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 304 | User authentication type. For details, see [HuksUserAuthType](#huksuserauthtype9). This parameter must be set together with [HuksAuthAccessType](#huksauthaccesstype9). You can set a maximum of two user authentication types at a time. For example, if **HuksAuthAccessType** is **HKS_SECURE_ACCESS_INVALID_NEW_BIO_ENROLL**, you can set the authentication type to **HKS_USER_AUTH_TYPE_FACE**, **HKS_USER_AUTH_TYPE_FINGERPRINT**, or their combination.| +| HUKS_TAG_AUTH_TIMEOUT | HuksTagType.HUKS_TAG_TYPE_UINT \| 305 | Reserved. | +| HUKS_TAG_AUTH_TOKEN | HuksTagType.HUKS_TAG_TYPE_BYTES \| 306 | Reserved. | +| HUKS_TAG_KEY_AUTH_ACCESS_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 307 | Access control type. For details, see [HuksAuthAccessType](#huksauthaccesstype9). This parameter must be set together with [HuksUserAuthType](#huksuserauthtype9).| +| HUKS_TAG_KEY_SECURE_SIGN_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 308 | Signature type of the key generated or imported.| +| HUKS_TAG_CHALLENGE_TYPE9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 309 | Type of the challenge generated for a key. For details, see [HuksChallengeType](#hukschallengetype9).| +| HUKS_TAG_CHALLENGE_POS9+ | HuksTagType.HUKS_TAG_TYPE_UINT \| 310 | Position of the 8-byte valid value in a custom challenge. For details, see [HuksChallengePosition](#hukschallengeposition9).| +| HUKS_TAG_ATTESTATION_CHALLENGE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 501 | Challenge value used in the attestation. | | HUKS_TAG_ATTESTATION_APPLICATION_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 502 | Application ID used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | -| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device ID. | -| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | -| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Device SN. | -| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Device IMEI. | -| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Device MEID. | -| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Device manufacturer. | -| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | -| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Device SOCID. | -| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. | -| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. | -| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | -| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation. | -| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | -| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | -| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | -| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | -| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | -| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | -| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | -| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | -| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | -| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | -| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | -| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | -| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | -| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | -| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | -| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | -| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | -| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | -| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | -| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | -| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | -| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | -| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | -| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | +| HUKS_TAG_ATTESTATION_ID_BRAND | HuksTagType.HUKS_TAG_TYPE_BYTES \| 503 | Brand of the device. | +| HUKS_TAG_ATTESTATION_ID_DEVICE | HuksTagType.HUKS_TAG_TYPE_BYTES \| 504 | Device ID. | +| HUKS_TAG_ATTESTATION_ID_PRODUCT | HuksTagType.HUKS_TAG_TYPE_BYTES \| 505 | Product name of the device. | +| HUKS_TAG_ATTESTATION_ID_SERIAL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 506 | Device SN. | +| HUKS_TAG_ATTESTATION_ID_IMEI | HuksTagType.HUKS_TAG_TYPE_BYTES \| 507 | Device IMEI. | +| HUKS_TAG_ATTESTATION_ID_MEID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 508 | Device MEID. | +| HUKS_TAG_ATTESTATION_ID_MANUFACTURER | HuksTagType.HUKS_TAG_TYPE_BYTES \| 509 | Device manufacturer. | +| HUKS_TAG_ATTESTATION_ID_MODEL | HuksTagType.HUKS_TAG_TYPE_BYTES \| 510 | Device model. | +| HUKS_TAG_ATTESTATION_ID_ALIAS | HuksTagType.HUKS_TAG_TYPE_BYTES \| 511 | Key alias used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_SOCID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 512 | Device SOCID. | +| HUKS_TAG_ATTESTATION_ID_UDID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 513 | Device UDID. | +| HUKS_TAG_ATTESTATION_ID_SEC_LEVEL_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 514 | Security credential used in the attestation. | +| HUKS_TAG_ATTESTATION_ID_VERSION_INFO | HuksTagType.HUKS_TAG_TYPE_BYTES \| 515 | Version information used in the attestation. | +| HUKS_TAG_IS_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1001 | Whether to use the alias passed in during key generation.| +| HUKS_TAG_KEY_STORAGE_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1002 | Key storage mode. | +| HUKS_TAG_IS_ALLOWED_WRAP | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1003 | Reserved. | +| HUKS_TAG_KEY_WRAP_TYPE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1004 | Reserved. | +| HUKS_TAG_KEY_AUTH_ID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1005 | Reserved. | +| HUKS_TAG_KEY_ROLE | HuksTagType.HUKS_TAG_TYPE_UINT \| 1006 | Reserved. | +| HUKS_TAG_KEY_FLAG | HuksTagType.HUKS_TAG_TYPE_UINT \| 1007 | Flag of the key. | +| HUKS_TAG_IS_ASYNCHRONIZED | HuksTagType.HUKS_TAG_TYPE_UINT \| 1008 | Reserved. | +| HUKS_TAG_SECURE_KEY_ALIAS | HuksTagType.HUKS_TAG_TYPE_BOOL \| 1009 | Reserved. | +| HUKS_TAG_SECURE_KEY_UUID | HuksTagType.HUKS_TAG_TYPE_BYTES \| 1010 | Reserved. | +| HUKS_TAG_KEY_DOMAIN | HuksTagType.HUKS_TAG_TYPE_UINT \| 1011 | Reserved. | +| HUKS_TAG_PROCESS_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10001 | Process name. | +| HUKS_TAG_PACKAGE_NAME | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10002 | Reserved. | +| HUKS_TAG_ACCESS_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10003 | Reserved. | +| HUKS_TAG_USES_TIME | HuksTagType.HUKS_TAG_TYPE_UINT \| 10004 | Reserved. | +| HUKS_TAG_CRYPTO_CTX | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10005 | Reserved. | +| HUKS_TAG_KEY | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10006 | Reserved. | +| HUKS_TAG_KEY_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10007 | Key version. | +| HUKS_TAG_PAYLOAD_LEN | HuksTagType.HUKS_TAG_TYPE_UINT \| 10008 | Reserved. | +| HUKS_TAG_AE_TAG | HuksTagType.HUKS_TAG_TYPE_BYTES \| 10009 | Reserved. | +| HUKS_TAG_IS_KEY_HANDLE | HuksTagType.HUKS_TAG_TYPE_ULONG \| 10010 | Reserved. | +| HUKS_TAG_OS_VERSION | HuksTagType.HUKS_TAG_TYPE_UINT \| 10101 | OS version. | +| HUKS_TAG_OS_PATCHLEVEL | HuksTagType.HUKS_TAG_TYPE_UINT \| 10102 | OS patch level. | +| HUKS_TAG_SYMMETRIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20001 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20002 | Reserved. | +| HUKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA | HuksTagType.HUKS_TAG_TYPE_BYTES \| 20003 | Reserved. | ## huks.generateKey @@ -502,7 +502,7 @@ huks.generateKey(keyAlias, options, function (err, data){}); generateKey(keyAlias: string, options: HuksOptions) : Promise\ -Generates a key. This API uses a promise to return the result asynchronously. +Generates a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -580,7 +580,7 @@ huks.deleteKey(keyAlias, emptyOptions, function (err, data) {}); deleteKey(keyAlias: string, options: HuksOptions) : Promise\ -Deletes a key. This API uses a promise to return the result asynchronously. +Deletes a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -700,7 +700,7 @@ huks.importKey(keyAlias, options, function (err, data){}); importKey(keyAlias: string, options: HuksOptions) : Promise\ -Imports a key in plaintext. This API uses a promise to return the result asynchronously. +Imports a key in plaintext. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -773,7 +773,7 @@ Obtains the certificate used to verify a key. This API uses an asynchronous call | Name | Type | Mandatory| Description | | ---------------- | ----------------------------------------- | ---- | -------------------------------------------------- | -| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | +| keyAlias | string | Yes | Alias of the key. The certificate to be obtained stores the key. | | options | [HuksOptions](#huksoptions) | Yes | Parameters and data required for obtaining the certificate. | | callback | AsyncCallback\<[HuksResult](#huksresult)> | Yes | Callback used to return the result. If the operation is successful, **HUKS_SUCCESS** will be returned. If the operation fails, an error code will be returned.| @@ -798,6 +798,51 @@ function printLog(...data) { console.error(data.toString()); } +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + await huks.generateKey(alias, options).then(async (data) => { + console.error(`generateKey data ${JSON.stringify(data)}`); + }).catch((err) => { + console.error(`generateKey err: " + ${JSON.stringify(err)}`); + });; +} + async function attestKey() { let aliasString = keyAliasString; let aliasUint8 = stringToUint8Array(aliasString); @@ -821,7 +866,7 @@ async function attestKey() { let options = { properties: properties }; - generateKey(aliasString); + await generateKey(aliasString); huks.attestKey(aliasString, options, function (err, data) { printLog(`key attest result : ${JSON.stringify(data)}`); }); @@ -870,6 +915,51 @@ function printLog(...data) { console.error(data.toString()); } +async function generateKey(alias) { + let properties = new Array(); + properties[0] = { + tag: huks.HuksTag.HUKS_TAG_ALGORITHM, + value: huks.HuksKeyAlg.HUKS_ALG_RSA + }; + properties[1] = { + tag: huks.HuksTag.HUKS_TAG_KEY_STORAGE_FLAG, + value: huks.HuksKeyStorageType.HUKS_STORAGE_PERSISTENT + }; + properties[2] = { + tag: huks.HuksTag.HUKS_TAG_KEY_SIZE, + value: huks.HuksKeySize.HUKS_RSA_KEY_SIZE_2048 + }; + properties[3] = { + tag: huks.HuksTag.HUKS_TAG_PURPOSE, + value: huks.HuksKeyPurpose.HUKS_KEY_PURPOSE_VERIFY + }; + properties[4] = { + tag: huks.HuksTag.HUKS_TAG_DIGEST, + value: huks.HuksKeyDigest.HUKS_DIGEST_SHA256 + }; + properties[5] = { + tag: huks.HuksTag.HUKS_TAG_PADDING, + value: huks.HuksKeyPadding.HUKS_PADDING_PSS + }; + properties[6] = { + tag: huks.HuksTag.HUKS_TAG_KEY_GENERATE_TYPE, + value: huks.HuksKeyGenerateType.HUKS_KEY_GENERATE_TYPE_DEFAULT + }; + properties[7] = { + tag: huks.HuksTag.HUKS_TAG_BLOCK_MODE, + value: huks.HuksCipherMode.HUKS_MODE_ECB + }; + let options = { + properties: properties + }; + + await huks.generateKey(alias, options).then(async (data) => { + console.error(`generateKey data ${JSON.stringify(data)}`); + }).catch((err) => { + console.error(`generateKey err: " + ${JSON.stringify(err)}`); + });; +} + async function attestKey() { let aliasString = keyAliasString; let aliasUint8 = stringToUint8Array(aliasString); @@ -893,7 +983,7 @@ async function attestKey() { let options = { properties: properties }; - generateKey(aliasString); + await generateKey(aliasString); huks.attestKey(aliasString, options) .then((data) => { console.log(`test attestKey data: ${JSON.stringify(data)}`); @@ -1096,7 +1186,7 @@ function huksImportWrappedKey() { importWrappedKey(keyAlias: string, wrappingKeyAlias: string, options: HuksOptions) : Promise\ -Imports a wrapped key. This API uses a promise to return the result asynchronously. +Imports a wrapped key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1159,7 +1249,7 @@ huks.exportKey(keyAlias, emptyOptions, function (err, data){}); exportKey(keyAlias: string, options: HuksOptions) : Promise\ -Exports a key. This API uses a promise to return the result asynchronously. +Exports a key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1218,7 +1308,7 @@ huks.getKeyProperties(keyAlias, emptyOptions, function (err, data){}); getKeyProperties(keyAlias: string, options: HuksOptions) : Promise\ -Obtains key properties. This API uses a promise to return the result asynchronously. +Obtains key properties. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1277,7 +1367,7 @@ huks.isKeyExist(keyAlias, emptyOptions, function (err, data){}); isKeyExist(keyAlias: string, options: HuksOptions) : Promise\ -Checks whether a key exists. This API uses a promise to return the result asynchronously. +Checks whether a key exists. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1311,7 +1401,7 @@ var result = huks.isKeyExist(keyAlias, emptyOptions); init(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void -Initializes a key. This API uses an asynchronous callback to return the result. +Initializes the data for a key operation. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks @@ -1328,7 +1418,7 @@ Initializes a key. This API uses an asynchronous callback to return the result. init(keyAlias: string, options: HuksOptions) : Promise\ -Initializes a key. This API uses a promise to return the result asynchronously. +Initializes the data for a key operation. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1345,9 +1435,9 @@ Initializes a key. This API uses a promise to return the result asynchronously. update(handle: number, token?: Uint8Array, options: HuksOptions, callback: AsyncCallback\) : void -Updates a key. This API uses an asynchronous callback to return the result. +Updates the key operation data by segment. This API uses an asynchronous callback to return the result. -> **NOTE**
This API is discarded since API version 9. You are advised to use [huks.update9+]. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [huks.update9+](#huksupdate9-1). **System capability**: SystemCapability.Security.Huks @@ -1364,9 +1454,9 @@ Updates a key. This API uses an asynchronous callback to return the result. update(handle: number, token?: Uint8Array, options: HuksOptions) : Promise\ -Updates a key. This API uses a promise to return the result asynchronously. +Updates the key operation data by segment. This API uses a promise to return the result. -> **NOTE**
This API is discarded since API version 9. You are advised to use [huks.update9+](#huksupdate9). +> **NOTE**
This API is discarded since API version 9. You are advised to use [huks.update9+](#huksupdate9-2). **System capability**: SystemCapability.Security.Huks @@ -1383,7 +1473,7 @@ Updates a key. This API uses a promise to return the result asynchronously. update(handle: number, options: HuksOptions, callback: AsyncCallback\) : void -Updates a key. This API uses an asynchronous callback to return the result. +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks @@ -1400,7 +1490,7 @@ Updates a key. This API uses an asynchronous callback to return the result. update(handle: number, options: HuksOptions, token: Uint8Array, callback: AsyncCallback\) : void -Updates a key. This API uses an asynchronous callback to return the result. +Updates the key operation by segment. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.Huks @@ -1417,7 +1507,7 @@ Updates a key. This API uses an asynchronous callback to return the result. update(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ -Updates a key. This API uses a promise to return the result asynchronously. +Updates the key operation by segment. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1451,7 +1541,7 @@ Completes the key operation and releases resources. This API uses an asynchronou finish(handle: number, options: HuksOptions) : Promise\ -Completes the key operation and releases resources. This API uses a promise to return the result asynchronously. +Completes the key operation and releases resources. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1485,7 +1575,7 @@ Completes the key operation and releases resources. This API uses an asynchronou finish(handle: number, options: HuksOptions, token?: Uint8Array) : Promise\ -Completes the key operation and releases resources. This API uses a promise to return the result asynchronously. +Completes the key operation and releases resources. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1722,7 +1812,7 @@ struct Index { abort(handle: number, options: HuksOptions) : Promise\; -Aborts the use of the key. This API uses a promise to return the result asynchronously. +Aborts the use of the key. This API uses a promise to return the result. **System capability**: SystemCapability.Security.Huks @@ -1976,7 +2066,7 @@ Defines the HUKS handle structure. | ---------- | ---------------- | ---- | -------- | | errorCode | number | Yes | Error code.| | handle | number | Yes| Value of the handle.| -| token | Uint8Array | No| Challenge information obtained after the [init](#huksinit) operation.| +| token | Uint8Array | No| Challenge obtained after the [init](#huksinit) operation.| ## HuksResult diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index b68a5b15487f310dd6b05058c68af75840098062..dc6d5ed6e1c8589733ee79c22cf3b413d7f80141 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,10 +1,13 @@ # Internationalization – I18N +This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. + +The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. + + > **NOTE** > -> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N interfaces that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md). +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index efd8277b83ac1cbe39a19ebad0fbf49cdf020190..bcbf619bf7173a405eee37f5dac86c5e87a023e9 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -92,7 +92,7 @@ Provides APIs to read or write image pixel map data and obtain image pixel map i readPixelsToBuffer(dst: ArrayBuffer): Promise\ -Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. If the pixel map is created in the BGRA_8888 format, the pixel map data read is the same as the original data. +Reads data of this pixel map and writes the data to an **ArrayBuffer**. This API uses a promise to return the result. If this pixel map is created in the BGRA_8888 format, the data read is the same as the original data. **System capability**: SystemCapability.Multimedia.Image.Core @@ -123,7 +123,7 @@ pixelmap.readPixelsToBuffer(readBuffer).then(() => { readPixelsToBuffer(dst: ArrayBuffer, callback: AsyncCallback\): void -Reads image pixel map data and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. If the pixel map is created in the BGRA_8888 format, the pixel map data read is the same as the original data. +Reads data of this pixel map and writes the data to an **ArrayBuffer**. This API uses an asynchronous callback to return the result. If this pixel map is created in the BGRA_8888 format, the data read is the same as the original data. **System capability**: SystemCapability.Multimedia.Image.Core @@ -170,7 +170,12 @@ Reads image pixel map data in an area. This API uses a promise to return the dat **Example** ```js -const area = new ArrayBuffer(400); +const area = { + pixels: new ArrayBuffer(8), + offset: 0, + stride: 8, + region: { size: { height: 1, width: 2 }, x: 0, y: 0 } +} pixelmap.readPixels(area).then(() => { console.log('Succeeded in reading the image data in the area.'); // Called if the condition is met. }).catch(error => { @@ -810,7 +815,7 @@ Crops this image based on the input size. This API uses an asynchronous callback ```js async function () { - await pixelMap.crop(3x3); + await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -838,7 +843,7 @@ Crops this image based on the input size. This API uses a promise to return the ```js async function () { - await pixelMap.crop(3x3); + await pixelMap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -910,7 +915,7 @@ Creates an **ImageSource** instance based on the URI. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------------------- | -| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.| +| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.| **Return value** @@ -937,7 +942,7 @@ Creates an **ImageSource** instance based on the URI. | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ----------------------------------- | -| uri | string | Yes | Image path. Currently, only the application sandbox path is supported. | +| uri | string | Yes | Image path. Currently, only the application sandbox path is supported.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.| | options | [SourceOptions](#sourceoptions9) | Yes | Image properties, including the image index and default property value.| **Return value** @@ -1569,7 +1574,7 @@ Packs an image. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ---------------------------------- | ---- | ---------------------------------- | | source | [ImageSource](#imagesource) | Yes | Image to pack. | -| option | [PackingOption](#packingoption) | Yes | Option for image packing. | +| option | [PackingOption](#packingoption) | Yes | Option for image packing. | | callback | AsyncCallback\ | Yes | Callback used to return the packed data.| **Example** @@ -2166,7 +2171,7 @@ Enumerates the scale modes of images. | Name | Default 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 | 2 | Reduces the image size to the dimensions of the target. | +| FIT_TARGET_SIZE | 0 | Reduces the image size to the dimensions of the target. | ## SourceOptions9+ @@ -2231,7 +2236,7 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | --------------------------------------------------- | -| format | string | Yes | Yes | Format of the packed image. | +| format | string | Yes | Yes | Format of the packed image.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp. | | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| ## GetImagePropertyOptions7+ diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 3060af2da4bd047461f0cce0d866753bd8caf36a..cae08502ee91872765050fbb53fe6701bc2cbb9b 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,9 +1,13 @@ # Internationalization – Intl -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> - This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402. For details about the enhanced I18N capabilities, see [I18N](js-apis-i18n.md). +This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. + +The [I18N](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 66af65d60b482342733fcc149c8b7b4078eeb851..96b190f1f7f9166c68ef1fda64bb9a98bf6b269d 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -45,7 +45,7 @@ let audioPlayer = media.createAudioPlayer(); createVideoPlayer(callback: AsyncCallback\<[VideoPlayer](#videoplayer8)>): void -Creates a **VideoPlayer** instance in asynchronous mode. This API uses a callback to return the result. +Creates a **VideoPlayer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -65,7 +65,7 @@ media.createVideoPlayer((error, video) => { videoPlayer = video; console.info('video createVideoPlayer success'); } else { - console.info(`video createVideoPlayer fail, error:${error.message}`); + console.info(`video createVideoPlayer fail, error:${error}`); } }); ``` @@ -74,7 +74,7 @@ media.createVideoPlayer((error, video) => { createVideoPlayer(): Promise<[VideoPlayer](#videoplayer8)> -Creates a **VideoPlayer** instance in asynchronous mode. This API uses a promise to return the result. +Creates a **VideoPlayer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -97,7 +97,7 @@ media.createVideoPlayer().then((video) => { console.info('video createVideoPlayer fail'); } }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -126,7 +126,7 @@ let audioRecorder = media.createAudioRecorder(); createVideoRecorder(callback: AsyncCallback\<[VideoRecorder](#videorecorder9)>): void -Creates a **VideoRecorder** instance in asynchronous mode. This API uses a callback to return the result. +Creates a **VideoRecorder** instance. This API uses an asynchronous callback to return the result. Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -147,7 +147,7 @@ media.createVideoRecorder((error, video) => { videoRecorder = video; console.info('video createVideoRecorder success'); } else { - console.info(`video createVideoRecorder fail, error:${error.message}`); + console.info(`video createVideoRecorder fail, error:${error}`); } }); ``` @@ -156,7 +156,7 @@ media.createVideoRecorder((error, video) => { createVideoRecorder(): Promise<[VideoRecorder](#videorecorder9)> -Creates a **VideoRecorder** instance in asynchronous mode. This API uses a promise to return the result. +Creates a **VideoRecorder** instance. This API uses a promise to return the result. Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -180,7 +180,7 @@ media.createVideoRecorder().then((video) => { console.info('video createVideoRecorder fail'); } }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -277,10 +277,10 @@ For details about the audio playback demo, see [Audio Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------------- | ----------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.INTERNET (The latter is required only when online resources are used.)| -| fdSrc9+ | [AVFileDescriptor](#interruptmode9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
If the file is an independent music file, use **src=fd://xx**.

**Required permissions**: ohos.permission.READ_MEDIA| +| src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.INTERNET| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
If the file is an independent music file, use **src=fd://xx**.
| | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | -| audioInterruptMode9+ | [InterruptMode](#interruptmode9) | Yes | Yes | Audio interruption mode. | +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | | currentTime | number | Yes | No | Current audio playback position, in ms. | | duration | number | Yes | No | Audio duration, in ms. | | state | [AudioState](#audiostate) | Yes | No | Audio playback state. This state cannot be used as the condition for triggering the call of **play()**, **pause()**, or **stop()**.| @@ -421,7 +421,7 @@ audioPlayer = undefined; getTrackDescription(callback: AsyncCallback>): void -Obtains the audio track information. This API uses a callback to return the result. It can be called only after the [dataLoad](#audioplayer_on) event is triggered. +Obtains the audio track information. This API uses an asynchronous callback to return the result. It can be called only after the [dataLoad](#audioplayer_on) event is triggered. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -442,13 +442,13 @@ function printfDescription(obj) { } } -audioPlayer.getTrackDescription((error, arrlist) => { +audioPlayer.getTrackDescription((error, ) => { if (arrlist != null) { for (let i = 0; i < arrlist.length; i++) { printfDescription(arrlist[i]); } } else { - console.log(`audio getTrackDescription fail, error:${error.message}`); + console.log(`audio getTrackDescription fail, error:${error}`); } }); ``` @@ -477,7 +477,7 @@ function printfDescription(obj) { console.info('audio value is ' + property); } } - +let arrayDescription = null audioPlayer.getTrackDescription().then((arrlist) => { if (arrlist != null) { arrayDescription = arrlist; @@ -485,7 +485,7 @@ audioPlayer.getTrackDescription().then((arrlist) => { console.log('audio getTrackDescription fail'); } }).catch((error) => { - console.info(`audio catchCallback, error:${error.message}`); + console.info(`audio catchCallback, error:${error}`); }); for (let i = 0; i < arrayDescription.length; i++) { @@ -529,12 +529,14 @@ Subscribes to the audio playback events. | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The following events are supported:
- 'play': triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- 'pause': triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- 'stop': triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- 'reset': triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed. | +| type | string | Yes | Event type. The following events are supported:
- 'play': triggered when the [play()](#audioplayer_play) API is called and audio playback starts.
- 'pause': triggered when the [pause()](#audioplayer_pause) API is called and audio playback is paused.
- 'stop': triggered when the [stop()](#audioplayer_stop) API is called and audio playback stops.
- 'reset': triggered when the [reset()](#audioplayer_reset) API is called and audio playback is reset.
- 'dataLoad': triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- 'finish': triggered when the audio playback is finished.
- 'volumeChange': triggered when the [setVolume()](#audioplayer_setvolume) API is called and the playback volume is changed.| | callback | () => void | Yes | Callback invoked when the event is triggered. | **Example** ```js +import fileio from '@ohos.fileio' + let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); @@ -570,17 +572,15 @@ audioPlayer.on('finish', () => { // Set the 'finish' event callbac audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. }); audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); - console.info(`audio error called, errCode is ${error.code}`); - console.info(`audio error called, errMessage is ${error.message}`); + console.info(`audio error called, error: ${error}`); }); // Set the FD (local playback) of the video file selected by the user. -let fdPath = 'fd://' +let fdPath = 'fd://'; // The stream in the path can be pushed to the device by running the "hdc file send D:\xxx\01.mp3 /data/accounts/account_0/appdata" command. let path = '/data/accounts/account_0/appdata/ohos.xxx.xxx.xxx/01.mp3'; -fileIO.open(path).then(fdNumber) => { - fdPath = fdPath + '' + fdNumber; +fileio.open(path).then((fdValue) => { + fdPath = fdPath + '' + fdValue; console.info('open fd success fd is' + fdPath); }, (err) => { console.info('open fd failed err is' + err); @@ -602,20 +602,20 @@ Subscribes to the **'timeUpdate'** event. | Name | Type | Mandatory| Description | | -------- | ----------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is **'timeUpdate'** in this case.
The **'timeUpdate'** event is triggered when the [seek()](#audioplayer_seek) API is called.| -| callback | Callback\ | Yes | Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful. | +| type | string | Yes | Event type, which is **'timeUpdate'** in this case.
The **'timeUpdate'** event is triggered when the audio playback starts after an audio playback timestamp update.| +| callback | Callback\ | Yes | Callback invoked when the event is triggered. The input parameter is the updated timestamp. | **Example** ```js -audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. - if (seekDoneTime == null) { - console.info('audio seek fail'); +audioPlayer.on('timeUpdate', (newTime) => { // Set the 'timeUpdate' event callback. + if (newTime == null) { + console.info('audio timeUpadate fail'); return; } - console.log('audio seek success. seekDoneTime: ' + seekDoneTime); + console.log('audio timeUpadate success. seekDoneTime: ' + newTime); }); -audioPlayer.seek(30000); // Seek to 30000 ms. +audioPlayer.play(); // The 'timeUpdate' event is triggered when the playback starts. ``` ### on('error') @@ -637,9 +637,7 @@ Subscribes to audio playback error events. After an error event is reported, you ```js audioPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); // Print the error name. - console.info(`audio error called, errCode is ${error.code}`); // Print the error code. - console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type. + console.info(`audio error called, error: ${error}`); }); audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. ``` @@ -650,21 +648,19 @@ Enumerates the audio playback states. You can obtain the state through the **sta **System capability**: SystemCapability.Multimedia.Media.AudioPlayer -| Name | Type | Description | -| ------------------ | ------ | ---------------------------------------------- | -| idle | string | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.| -| playing | string | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered. | -| paused | string | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered. | -| stopped | string | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered. | -| error8+ | string | Audio playback is in the error state. | +| Name | Type | Description | +| ------- | ------ | ---------------------------------------------- | +| idle | string | No audio playback is in progress. The audio player is in this state after the **'dataload'** or **'reset'** event is triggered.| +| playing | string | Audio playback is in progress. The audio player is in this state after the **'play'** event is triggered. | +| paused | string | Audio playback is paused. The audio player is in this state after the **'pause'** event is triggered. | +| stopped | string | Audio playback is stopped. The audio player is in this state after the **'stop'** event is triggered. | +| error | string | Audio playback is in the error state. | ## AVFileDescriptor9+ Describes audio and video file resources. It is used to specify a particular resource for playback based on its offset and length within a file. -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer - -**Parameters** +**System capability**: SystemCapability.Multimedia.Media.Core | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | @@ -672,17 +668,6 @@ Describes audio and video file resources. It is used to specify a particular res | offset | number | Yes | Resource offset, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.| | length | number | Yes | Resource length, which needs to be entered based on the preset resource information. An invalid value causes a failure to parse audio and video resources.| -## InterruptMode9+ - -Describes the audio interruption mode. - -**System capability**: SystemCapability.Multimedia.Media.AudioPlayer - -| Name | Default Value| Description | -| ---------------------------- | ------ | ---------- | -| SHARE_MODE | 0 | Shared mode.| -| INDEPENDENT_MODE| 1 | Independent mode. | - ## VideoPlayer8+ Provides APIs to manage and play video. Before calling an API of **VideoPlayer**, you must call [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. @@ -695,11 +680,11 @@ For details about the video playback demo, see [Video Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA and ohos.permission.INTERNET (The latter is required only when online resources are used.)| -| fdSrc9+ | [AVFileDescriptor](#interruptmode9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use **src=fd://xx**.
**Note**:
**Required permissions**: ohos.permission.READ_MEDIA| +| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.INTERNET| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use **src=fd://xx**.
| | loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | -| audioInterruptMode9+ | [InterruptMode](#interruptmode9) | Yes | Yes | Audio interruption mode. | +| audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | | currentTime8+ | number | Yes | No | Current video playback position, in ms. | | duration8+ | number | Yes | No | Video duration, in ms. The value **-1** indicates the live mode. | | state8+ | [VideoPlayState](#videoplaystate8) | Yes | No | Video playback state. | @@ -710,7 +695,7 @@ For details about the video playback demo, see [Video Playback Development](../. setDisplaySurface(surfaceId: string, callback: AsyncCallback\): void -Sets **SurfaceId**. This API uses a callback to return the result. +Sets **SurfaceId**. This API uses an asynchronous callback to return the result. *Note: **SetDisplaySurface** must be called between the URL setting and the calling of **prepare**. A surface must be set for video streams without audio. Otherwise, the calling of **prepare** fails. @@ -726,6 +711,7 @@ Sets **SurfaceId**. This API uses a callback to return the result. **Example** ```js +let surfaceId = null; videoPlayer.setDisplaySurface(surfaceId, (err) => { if (err == null) { console.info('setDisplaySurface success!'); @@ -760,10 +746,11 @@ Sets **SurfaceId**. This API uses a promise to return the result. **Example** ```js +let surfaceId = null; videoPlayer.setDisplaySurface(surfaceId).then(() => { console.info('setDisplaySurface success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -771,7 +758,7 @@ videoPlayer.setDisplaySurface(surfaceId).then(() => { prepare(callback: AsyncCallback\): void -Prepares for video playback. This API uses a callback to return the result. +Prepares for video playback. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -813,7 +800,7 @@ Prepares for video playback. This API uses a promise to return the result. videoPlayer.prepare().then(() => { console.info('prepare success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -821,7 +808,7 @@ videoPlayer.prepare().then(() => { play(callback: AsyncCallback\): void; -Starts to play video resources. This API uses a callback to return the result. +Starts to play video resources. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -863,7 +850,7 @@ Starts to play video resources. This API uses a promise to return the result. videoPlayer.play().then(() => { console.info('play success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -871,7 +858,7 @@ videoPlayer.play().then(() => { pause(callback: AsyncCallback\): void -Pauses video playback. This API uses a callback to return the result. +Pauses video playback. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -913,7 +900,7 @@ Pauses video playback. This API uses a promise to return the result. videoPlayer.pause().then(() => { console.info('pause success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -921,7 +908,7 @@ videoPlayer.pause().then(() => { stop(callback: AsyncCallback\): void -Stops video playback. This API uses a callback to return the result. +Stops video playback. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -963,7 +950,7 @@ Stops video playback. This API uses a promise to return the result. videoPlayer.stop().then(() => { console.info('stop success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -971,7 +958,7 @@ videoPlayer.stop().then(() => { reset(callback: AsyncCallback\): void -Switches the video resource to be played. This API uses a callback to return the result. +Switches the video resource to be played. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1013,7 +1000,7 @@ Switches the video resource to be played. This API uses a promise to return the videoPlayer.reset().then(() => { console.info('reset success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -1021,7 +1008,7 @@ videoPlayer.reset().then(() => { seek(timeMs: number, callback: AsyncCallback\): void -Seeks to the specified playback position. The next key frame at the specified position is played. This API uses a callback to return the result. +Seeks to the specified playback position. The next key frame at the specified position is played. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1049,7 +1036,7 @@ videoPlayer.seek(seekTime, (err, result) => { seek(timeMs: number, mode:SeekMode, callback: AsyncCallback\): void -Seeks to the specified playback position. This API uses a callback to return the result. +Seeks to the specified playback position. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1066,8 +1053,7 @@ Seeks to the specified playback position. This API uses a callback to return the ```js import media from '@ohos.multimedia.media' let seekTime = 5000; -let seekMode = media.SeekMode.SEEK_NEXT_SYNC; -videoPlayer.seek(seekTime, seekMode, (err, result) => { +videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC, (err, result) => { if (err == null) { console.info('seek success!'); } else { @@ -1100,17 +1086,18 @@ Seeks to the specified playback position. If **mode** is not specified, the next **Example** ```js +import media from '@ohos.multimedia.media' let seekTime = 5000; videoPlayer.seek(seekTime).then((seekDoneTime) => { // seekDoneTime indicates the position after the seek operation is complete. console.info('seek success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); -videoPlayer.seek(seekTime, seekMode).then((seekDoneTime) => { +videoPlayer.seek(seekTime, media.SeekMode.SEEK_NEXT_SYNC).then((seekDoneTime) => { console.info('seek success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -1118,7 +1105,7 @@ videoPlayer.seek(seekTime, seekMode).then((seekDoneTime) => { setVolume(vol: number, callback: AsyncCallback\): void -Sets the volume. This API uses a callback to return the result. +Sets the volume. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1166,10 +1153,10 @@ Sets the volume. This API uses a promise to return the result. ```js let vol = 0.5; -videoPlayer.setVolume(vol).then() => { +videoPlayer.setVolume(vol).then(() => { console.info('setVolume success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -1177,7 +1164,7 @@ videoPlayer.setVolume(vol).then() => { release(callback: AsyncCallback\): void -Releases the video playback resource. This API uses a callback to return the result. +Releases the video playback resource. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1216,10 +1203,10 @@ Releases the video playback resource. This API uses a promise to return the resu **Example** ```js -videoPlayer.release().then() => { +videoPlayer.release().then(() => { console.info('release success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -1227,7 +1214,7 @@ videoPlayer.release().then() => { getTrackDescription(callback: AsyncCallback>): void -Obtains the video track information. This API uses a callback to return the result. +Obtains the video track information. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1249,12 +1236,12 @@ function printfDescription(obj) { } videoPlayer.getTrackDescription((error, arrlist) => { - if (arrlist) != null) { + if ((arrlist) != null) { for (let i = 0; i < arrlist.length; i++) { printfDescription(arrlist[i]); } } else { - console.log(`video getTrackDescription fail, error:${error.message}`); + console.log(`video getTrackDescription fail, error:${error}`); } }); ``` @@ -1292,7 +1279,7 @@ videoPlayer.getTrackDescription().then((arrlist) => { console.log('video getTrackDescription fail'); } }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); for (let i = 0; i < arrayDescription.length; i++) { printfDescription(arrayDescription[i]); @@ -1303,7 +1290,7 @@ for (let i = 0; i < arrayDescription.length; i++) { setSpeed(speed:number, callback: AsyncCallback\): void -Sets the video playback speed. This API uses a callback to return the result. +Sets the video playback speed. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1355,10 +1342,10 @@ Sets the video playback speed. This API uses a promise to return the result. import media from '@ohos.multimedia.media' let speed = media.PlaybackSpeed.SPEED_FORWARD_2_00_X; -videoPlayer.setSpeed(speed).then() => { +videoPlayer.setSpeed(speed).then(() => { console.info('setSpeed success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -1414,10 +1401,10 @@ Selects a bit rate from available ones, which can be obtained by calling [availa ```js let bitrate = 1024000; -videoPlayer.selectBitrate(bitrate).then() => { +videoPlayer.selectBitrate(bitrate).then(() => { console.info('selectBitrate success'); }).catch((error) => { - console.info(`video catchCallback, error:${error.message}`); + console.info(`video catchCallback, error:${error}`); }); ``` @@ -1534,9 +1521,7 @@ Subscribes to video playback error events. After an error event is reported, you ```js videoPlayer.on('error', (error) => { // Set the 'error' event callback. - console.info(`video error called, errName is ${error.name}`); // Print the error name. - console.info(`video error called, errCode is ${error.code}`); // Print the error code. - console.info(`video error called, errMessage is ${error.message}`);// Print the detailed description of the error type. + console.info(`video error called, error: ${error}`); }); videoPlayer.url = 'fd://error'; // Set an incorrect URL to trigger the 'error' event. ``` @@ -1619,33 +1604,27 @@ Enumerates the video scale modes. ## MediaDescription8+ -### [key : string] : Object - Defines media information in key-value mode. **System capability**: SystemCapability.Multimedia.Media.Core -| Name | Type | Description | -| ----- | ------ | ------------------------------------------------------------ | -| key | string | Key of the media information. For details about the keys, see [MediaDescriptionKey](#mediadescriptionkey8).| -| value | any | Value of the key. For details about the values, see [MediaDescriptionKey](#mediadescriptionkey8).| - **Example** ```js +import media from '@ohos.multimedia.media' function printfItemDescription(obj, key) { let property = obj[key]; - console.info('audio key is ' + key); - console.info('audio value is ' + property); + console.info('audio key is ' + key); // Specify a key. For details about the keys, see [MediaDescriptionKey]. + console.info('audio value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [MediaDescriptionKey]. } - +let audioPlayer = media.createAudioPlayer(); audioPlayer.getTrackDescription((error, arrlist) => { if (arrlist != null) { for (let i = 0; i < arrlist.length; i++) { - printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. + printfItemDescription(arrlist[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. } } else { - console.log(`audio getTrackDescription fail, error:${error.message}`); + console.log(`audio getTrackDescription fail, error:${error}`); } }); ``` @@ -1808,13 +1787,13 @@ Subscribes to the audio recording events. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The following events are supported:
- 'prepare': triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- 'start': triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- 'pause': triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- 'resume': triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- 'stop': triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- 'release': triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- 'reset': triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset. | +| type | string | Yes | Event type. The following events are supported:
- 'prepare': triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- 'start': triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- 'pause': triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- 'resume': triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- 'stop': triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- 'release': triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- 'reset': triggered when the [reset](#audiorecorder_reset) API is called and audio recording is reset.| | callback | ()=>void | Yes | Callback invoked when the event is triggered. | **Example** ```js -let audiorecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. +let audioRecorder = media.createAudioRecorder(); // Create an AudioRecorder instance. let audioRecorderConfig = { audioEncoder : media.AudioEncoder.AAC_LC, , audioEncodeBitRate : 22050, @@ -1825,9 +1804,7 @@ let audioRecorderConfig = { location : { latitude : 30, longitude : 130}, } audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); - console.info(`audio error called, errCode is ${error.code}`); - console.info(`audio error called, errMessage is ${error.message}`); + console.info(`audio error called, error: ${error}`); }); audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); @@ -1872,12 +1849,19 @@ Subscribes to audio recording error events. After an error event is reported, yo **Example** ```js +let audioRecorderConfig = { + audioEncoder : media.AudioEncoder.AAC_LC, , + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : media.AudioOutputFormat.AAC_ADTS, + uri : 'fd://xx', // The file must be created by the caller and granted with proper permissions. + location : { latitude : 30, longitude : 130}, +} audioRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); // Print the error name. - console.info(`audio error called, errCode is ${error.code}`); // Print the error code. - console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. + console.info(`audio error called, error: ${error}`); }); -audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. +audioRecorder.prepare(audioRecorderConfig); // Do no set any parameter in prepare and trigger the 'error' event callback. ``` ## AudioRecorderConfig @@ -1951,7 +1935,7 @@ For details about the video recording demo, see [Video Recording Development](.. prepare(config: VideoRecorderConfig, callback: AsyncCallback\): void; -Sets video recording parameters in asynchronous mode. This API uses a callback to return the result. +Sets video recording parameters. This API uses an asynchronous callback to return the result. **Required permissions:** ohos.permission.MICROPHONE @@ -2019,7 +2003,7 @@ media.createVideoRecorder((err, recorder) => { prepare(config: VideoRecorderConfig): Promise\; -Sets video recording parameters in asynchronous mode. This API uses a promise to return the result. +Sets video recording parameters. This API uses a promise to return the result. **Required permissions:** ohos.permission.MICROPHONE @@ -2068,18 +2052,17 @@ media.createVideoRecorder().then((recorder) => { if (recorder != null) { videoRecorder = recorder; console.info('createVideoRecorder success'); + videoRecorder.prepare(videoConfig).then(() => { + console.info('prepare success'); + }).catch((err) => { + console.info('prepare failed and catch error is ' + err.message); + }); } else { console.info('createVideoRecorder failed'); } }).catch((err) => { console.info('catch err error message is ' + err.message); }); - -videoRecorder.prepare(videoConfig).then(() => { - console.info('prepare success'); -}).catch((err) => { - console.info('prepare failed and catch error is ' + err.message); -}); ``` ### getInputSurface9+ @@ -2150,7 +2133,7 @@ videoRecorder.getInputSurface().then((surfaceId) => { start(callback: AsyncCallback\): void; -Starts video recording in asynchronous mode. This API uses a callback to return the result. +Starts video recording. This API uses an asynchronous callback to return the result. This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first. @@ -2179,7 +2162,7 @@ videoRecorder.start((err) => { start(): Promise\; -Starts video recording in asynchronous mode. This API uses a promise to return the result. +Starts video recording. This API uses a promise to return the result. This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) are called, because the data source must pass data to the surface first. @@ -2206,7 +2189,7 @@ videoRecorder.start().then(() => { pause(callback: AsyncCallback\): void; -Pauses video recording in asynchronous mode. This API uses a callback to return the result. +Pauses video recording. This API uses an asynchronous callback to return the result. This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). @@ -2235,7 +2218,7 @@ videoRecorder.pause((err) => { pause(): Promise\; -Pauses video recording in asynchronous mode. This API uses a promise to return the result. +Pauses video recording. This API uses a promise to return the result. This API can be called only after [start()](#videorecorder_start1) is called. You can resume recording by calling [resume()](#videorecorder_resume1). @@ -2262,7 +2245,7 @@ videoRecorder.pause().then(() => { resume(callback: AsyncCallback\): void; -Resumes video recording in asynchronous mode. This API uses a callback to return the result. +Resumes video recording. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2289,7 +2272,7 @@ videoRecorder.resume((err) => { resume(): Promise\; -Resumes video recording in asynchronous mode. This API uses a promise to return the result. +Resumes video recording. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2314,7 +2297,7 @@ videoRecorder.resume().then(() => { stop(callback: AsyncCallback\): void; -Stops video recording in asynchronous mode. This API uses a callback to return the result. +Stops video recording. This API uses an asynchronous callback to return the result. To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. @@ -2343,7 +2326,7 @@ videoRecorder.stop((err) => { stop(): Promise\; -Stops video recording in asynchronous mode. This API uses a promise to return the result. +Stops video recording. This API uses a promise to return the result. To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. @@ -2370,7 +2353,7 @@ videoRecorder.stop().then(() => { release(callback: AsyncCallback\): void; -Releases the video recording resource in asynchronous mode. This API uses a callback to return the result. +Releases the video recording resource. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2397,7 +2380,7 @@ videoRecorder.release((err) => { release(): Promise\; -Releases the video recording resource in asynchronous mode. This API uses a promise to return the result. +Releases the video recording resource. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2422,7 +2405,7 @@ videoRecorder.release().then(() => { reset(callback: AsyncCallback\): void; -Resets video recording in asynchronous mode. This API uses a callback to return the result. +Resets video recording. This API uses an asynchronous callback to return the result. To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. @@ -2451,7 +2434,7 @@ videoRecorder.reset((err) => { reset(): Promise\; -Resets video recording in asynchronous mode. This API uses a promise to return the result. +Resets video recording. This API uses a promise to return the result. To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. @@ -2493,11 +2476,10 @@ Subscribes to video recording error events. After an error event is reported, yo ```js videoRecorder.on('error', (error) => { // Set the 'error' event callback. - console.info(`audio error called, errName is ${error.name}`); // Print the error name. - console.info(`audio error called, errCode is ${error.code}`); // Print the error code. - console.info(`audio error called, errMessage is ${error.message}`); // Print the detailed description of the error type. -}); + console.info(`audio error called, error: ${error}`); +} // This event is reported when an error occurs during the retrieval of videoRecordState. +}); ``` ## VideoRecordState9+ @@ -2528,7 +2510,7 @@ Describes the video recording parameters. | profile | [VideoRecorderProfile](#videorecorderprofile9) | Yes | Video recording profile. | | rotation | number | No | Rotation angle of the recorded video. | | location | [Location](#location) | No | Geographical location of the recorded video. | -| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
**Required permissions**: ohos.permission.READ_MEDIA| +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png) | ## AudioSourceType9+ diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index b66eeec85c124ac083b27859849a86e1a5f1d4c2..e805a8d3172b2ec12f05a4fe39034be08d249905 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -1130,7 +1130,7 @@ async function example() { const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail((err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); }); } ``` @@ -1168,7 +1168,7 @@ async function example() { const fetchFileResult = await media.getFileAssets(getImageOp); const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size, (err, pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); }); } ``` @@ -1212,7 +1212,7 @@ async function example() { const asset = await fetchFileResult.getFirstObject(); asset.getThumbnail(size) .then((pixelmap) => { - console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + console.info('mediaLibraryTest : getThumbnail successful '+ pixelmap); }) .catch((err) => { console.info('mediaLibraryTest : getThumbnail fail'+ err); @@ -1502,7 +1502,7 @@ async function example() { asset.trash(true, istrashCallBack); } else { - console.info('mediaLibraryTest : ASSET_CALLBACK isTrash Unsuccessfull = ' + err); + console.info('mediaLibraryTest : ASSET_CALLBACK isTrash Unsuccessful = ' + err); console.info('mediaLibraryTest : ASSET_CALLBACK isTrash : FAIL'); } @@ -1736,7 +1736,7 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ----------------------------------------- | -| callbacke | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the next file asset.| +| callback | AsyncCallback<[FileAsset](#fileasset7)> | Yes | Callback used to return the next file asset.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 01315a62d6aecacea806cdecebc268ed1f571c84..5941d465a085a425ef7d10cb28d5fe4b621bc0b2 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,4 +1,4 @@ -# Standard NFC Tag +# NFC Tags The **nfcTag** module provides methods for managing Near-Field Communication (NFC) tags. diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md index eb7d01dda3b5bcf8c88a45981d661aacf6d4e4f4..d471510aeec29a3fce389284a54866a55b1ca507 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -1,9 +1,8 @@ -# Standard NFC Tag Technologies +# NFC Tag Technologies -The **nfctech** module provides methods for reading and writing tags that use different Near-Field Communication (NFC) technologies. +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** @@ -14,7 +13,7 @@ import tag from '@ohos.nfc.tag'; ## NfcATag -Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. **NfcATag** inherits from **TagSession**. +Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. 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). @@ -74,7 +73,7 @@ console.log("atqa:" +atqa); ## NfcBTag -Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. **NfcBTag** inherits from **TagSession**. +Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. 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). @@ -110,7 +109,7 @@ console.log("appData:" +appData); getRespProtocol(): number[] -Obtains protocol information of this NFC-B tag. +Obtains the protocol information of this NFC-B tag. **Required permissions**: ohos.permission.NFC_TAG @@ -134,7 +133,7 @@ console.log("appData:" +protocol); ## NfcFTag -Provides access to NFC-F(JIS 6319-4) properties and I/O operations. **NfcFTag** inherits from **TagSession**. +Provides access to NFC-F (JIS 6319-4) properties and I/O operations. 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). @@ -144,7 +143,7 @@ The following describes the unique interfaces of **NfcFTag**. getSystemCode(): number[] -Obtains the system code from the tag instance. +Obtains the system code from this NFC-F tag. **Required permissions**: ohos.permission.NFC_TAG @@ -170,7 +169,7 @@ console.log("systemCode:" +systemCode); getPmm(): number[] -Obtains the PMm (consisting of the IC code and manufacturer parameters) information from the tag instance. +Obtains the PMm (consisting of the IC code and manufacturer parameters) information from this NFC-F tag. **Required permissions**: ohos.permission.NFC_TAG @@ -194,7 +193,7 @@ console.log("pmm:" +pmm); ## NfcVTag -Provides access to NFC-V (ISO 15693) properties and I/O operations. **NfcVTag** inherits from **TagSession**. +Provides access to NFC-V (ISO 15693) properties and I/O operations. 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). @@ -204,7 +203,7 @@ The following describes the unique interfaces of **NfcVTag**. getResponseFlags(): number -Obtains the response flags from the tag instance. +Obtains the response flags from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG @@ -230,7 +229,7 @@ console.log("flags:" +flags); getDsfId(): number -Obtains the data storage format identifier (DSFID) from the tag instance. +Obtains the data storage format identifier (DSFID) from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG @@ -254,7 +253,7 @@ console.log("dsfId:" +dsfId); ## IsoDepTag9+ -Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. **IsoDepTag** inherits from **TagSession**. +Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. 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). @@ -343,7 +342,7 @@ tag.getIsoDepTag(taginfo).isExtendedApduSupported().then(function (has) { isExtendedApduSupported(callback: AsyncCallback\): void -Checks whether an extended application protocol data unit (APDU) is supported. This API uses an asynchronous callback to return the result. +Checks whether an extended APDU is supported. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -367,7 +366,7 @@ tag.getIsoDepTag(taginfo).isExtendedApduSupported(function (error, has) { ## NdefTag9+ -Provides access to the tags in the NFC Data Exchange Format (NDEF). **NdefTag** inherits from **TagSession**. +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). @@ -596,7 +595,7 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| +| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the NDEF message read.| **Example** @@ -641,7 +640,7 @@ tag.NdefTag(taginfo).readNdef(function (error, ndefMessage) { writeNdef(msg: NdefMessage): Promise\; -Write an NDEF message to this tag. This API uses a promise to return the result. +Writes an NDEF message to this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -674,7 +673,7 @@ NdefTag.writeNdef(msg).then(function (netHandle) { writeNdef(msg: NdefMessage, callback: AsyncCallback\): void -Write an NDEF message to this tag. This API uses an asynchronous callback to return the result. +Writes an NDEF message to this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -728,7 +727,7 @@ tag.NdefTag(taginfo).canSetReadOnly().then(function (has) { ### NdefTag.canSetReadOnly9+ -canSetReadOnly()(callback: AsyncCallback<boolean>): void; +canSetReadOnly(callback: AsyncCallback<boolean>): void; Checks whether this NDEF tag can be set to read-only. This API uses an asynchronous callback to return the result. @@ -813,7 +812,7 @@ tag.NdefTag(taginfo).setReadOnly(function (error, errcode) { getNdefTagTypeString(type: [NfcForumType](#nfcforumtype9)): string -Converts the NFC Forum Type to a byte array defined in the NFC Forum. +Converts an NFC Forum Type to a byte array defined in the NFC Forum. **Required permissions**: ohos.permission.NFC_TAG @@ -852,7 +851,7 @@ let ndefTypeString= tag.NdefTag(taginfo).getNdefTagTypeString(type); ## MifareClassicTag 9+ -Provides access to MIFARE Classic properties and I/O operations. **MifareClassicTag** inherits from **TagSession**. +Provides access to MIFARE Classic properties and I/O operations. 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). @@ -928,7 +927,7 @@ tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key, function (err readSingleBlock(blockIndex: number): Promise\ -Reads a block on the tag. The size of a block is 16 bytes. This API uses a promise to return the result. +Reads a block (16 bytes) on the tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -962,7 +961,7 @@ tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex).then(function (data){ readSingleBlock(blockIndex: number, callback: AsyncCallback\): void -Reads a block on the tag. The size of a block is 16 bytes. This API uses an asynchronous callback to return the result. +Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -992,7 +991,7 @@ tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex, function (error, data) writeSingleBlock(blockIndex: number, data: string): Promise\ -Writes data to a block on the tag. The size of a block is 16 bytes. This API uses a promise to return the result. +Writes data to a block on the tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -1027,7 +1026,7 @@ tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data).then(function ( writeSingleBlock(blockIndex: number, data: string, callback: AsyncCallback\): void -Writes data to a block on the tag. The size of a block is 16 bytes. This API uses an asynchronous callback to return the result. +Writes data to a block on the tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -1427,10 +1426,10 @@ let size = tag.MifareClassicTag(taginfo).getTagSize(); | **Name**| **Value**| **Description**| | -------- | -------- | -------- | -| MC_SIZE_MINI | 320 | Each tag has five sectors, and each sector has four blocks.| -| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has four blocks.| -| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has four blocks.| -| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has four blocks.| +| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| +| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.| +| 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.| ### MifareClassicTag.isEmulatedTag9+ @@ -1521,7 +1520,7 @@ let index = tag.MifareClassicTag(taginfo).getSectorIndex(blockIndex); ## MifareUltralightTag9+ -Provides access to MIFARE Ultralight properties and I/O operations. **MifareUltralightTag** inherits from **TagSession**. +Provides access to MIFARE Ultralight properties and I/O operations. 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). @@ -1531,7 +1530,7 @@ The following describes the unique interfaces of **MifareUltralightTag**. readMultiplePages(pageIndex: number): Promise\ -Reads multiple pages. The size of each page is 4 bytes. This API uses a promise to return the result. +Reads multiple pages (4 bytes per page). This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -1565,7 +1564,7 @@ tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex).then(function (dat readMultiplePages(pageIndex: number, callback: AsyncCallback\): void -Reads multiple pages. The size of each page is 4 bytes. This API uses an asynchronous callback to return the result. +Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -1594,7 +1593,7 @@ tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex, function (error, d writeSinglePages(pageIndex: number, data: string): Promise\ -Writes a page of data. The size of each page is 4 bytes. This API uses a promise to return the result. +Writes a page of data. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -1628,7 +1627,7 @@ tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data).then(function writeSinglePages(pageIndex: number, data: string, callback: AsyncCallback\): void -Writes a page of data. The size of each page is 4 bytes. This API uses an asynchronous callback to return the result. +Writes a page of data. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG @@ -1658,7 +1657,7 @@ tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data, function (err getType(): MifareUltralightType -Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](#mifareultralighttype9). +Obtains the MIFARE Ultralight tag type, in bytes. **Required permissions**: ohos.permission.NFC_TAG @@ -1689,7 +1688,7 @@ let type = tag.MifareUltralightType(taginfo).getType(); ## NdefFormatableTag9+ -Provides methods for operating NDEF formattable tags. **NdefFormatableTag** inherits from **TagSession**. +Provides APIs for operating 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). @@ -1709,7 +1708,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| +| 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).| **Return value** @@ -1742,8 +1741,8 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only.| +| callback | AsyncCallback\ |Yes|Callback invoked to return the result.| **Example** @@ -1771,7 +1770,7 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| +| 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).| **Return value** @@ -1804,8 +1803,8 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If it is **null**, the tag is formatted only and no data will be written.| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only.| +| callback | AsyncCallback\ |Yes|Callback invoked to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 58d29f74c3196918f08da1b8e12babc71efc5347..a4692039779fa40b82edb8de1dab204423ac957d 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,6 +1,6 @@ -# OS Account Management +# OS Account Management -The osAccount module provides basic capabilities for managing operating system (OS) accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account, and storing OS account data to disks. +The **osAccount** module provides basic capabilities for managing operating system (OS) accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account, and storing OS account data to disks. > **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. @@ -440,12 +440,10 @@ This is a system API and cannot be called by third-party applications. ```js const accountManager = account_osAccount.getAccountManager(); - var createIocalId; - osAccountManager.createOsAccount("testAccountName", osaccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ - createIocalId = osAccountInfo.localId; - }); - accountManager.removeOsAccount(createIocalId, (err)=>{ - console.log("removeOsAccount err:" + JSON.stringify(err)); + accountManager.createOsAccount("testAccountName", account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo) => { + accountManager.removeOsAccount(osAccountInfo.localId, (err)=>{ + console.log("removeOsAccount err:" + JSON.stringify(err)); + }); }); ``` @@ -477,15 +475,12 @@ This is a system API and cannot be called by third-party applications. ```js const accountManager = account_osAccount.getAccountManager(); - var createIocalId; - osAccountManager.createOsAccount("testAccountName", osaccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ - createIocalId = osAccountInfo.localId; - }); - createIocalId = osAccount.localId; - accountManager.removeOsAccount(createIocalId).then(() => { - console.log('removeOsAccount Success'); - }).catch(() => { - console.log("removeOsAccount err: " + JSON.stringify(err)); + accountManager.createOsAccount("testAccountName", account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ + accountManager.removeOsAccount(osAccountInfo.localId).then(() => { + console.log('removeOsAccount Success'); + }).catch(() => { + console.log("removeOsAccount err: " + JSON.stringify(err)); + }); }); ``` @@ -1097,7 +1092,7 @@ This is a system API and cannot be called by third-party applications. ```js const accountManager = account_osAccount.getAccountManager(); - accountManager.createOsAccount("testName", osaccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ + accountManager.createOsAccount("testName", account_osAccount.OsAccountType.NORMAL, (err, osAccountInfo)=>{ console.log("createOsAccount err:" + JSON.stringify(err)); console.log("createOsAccount osAccountInfo:" + JSON.stringify(osAccountInfo)); }); @@ -1132,7 +1127,7 @@ This is a system API and cannot be called by third-party applications. ```js const accountManager = account_osAccount.getAccountManager(); - accountManager.createOsAccount("testAccountName", osaccount.OsAccountType.NORMAL).then((accountInfo) => { + accountManager.createOsAccount("testAccountName", account_osAccount.OsAccountType.NORMAL).then((accountInfo) => { console.log("createOsAccount, accountInfo: " + JSON.stringify(accountInfo)); }).catch((err) => { console.log("createOsAccount err: " + JSON.stringify(err)); @@ -1164,7 +1159,7 @@ This is a system API and cannot be called by third-party applications. ```js const accountManager = account_osAccount.getAccountManager(); var domainInfo = {domain: "testDomain", accountName: "testAccountName"}; - accountManager.createOsAccountForDomain(osaccount.OsAccountType.NORMAL, domainInfo, (err, osAccountInfo)=>{ + accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo, (err, osAccountInfo)=>{ console.log("createOsAccountForDomain err:" + JSON.stringify(err)); console.log("createOsAccountForDomain osAccountInfo:" + JSON.stringify(osAccountInfo)); }); @@ -1200,7 +1195,7 @@ This is a system API and cannot be called by third-party applications. ```js const accountManager = account_osAccount.getAccountManager(); var domainInfo = {domain: "testDomain", accountName: "testAccountName"}; - accountManager.createOsAccountForDomain(osaccount.OsAccountType.NORMAL, domainInfo).then((accountInfo) => { + accountManager.createOsAccountForDomain(account_osAccount.OsAccountType.NORMAL, domainInfo).then((accountInfo) => { console.log("createOsAccountForDomain, account info: " + JSON.stringify(accountInfo)); }).catch((err) => { console.log("createOsAccountForDomain err: " + JSON.stringify(err)); @@ -1523,7 +1518,7 @@ This is a system API and cannot be called by third-party applications. "Cxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAACwSURBVDhPvZLBDYMwDEV/ugsXRjAT0EHCOuFIBwkbdIRewi6unbiAyoGgSn1SFH85+Y"+ "q/4ljARW62X+LHS8uIzjm4dXUYF+utzBikB52Jo5e5iEPKqpACk7R9NM2RvWm5tIkD2czLCUFNKLD6IjdMHFHDzws285MgGrT0xCtp3WOKHo"+ "+7q0mP0DZW9pNmoEFUzrQjp5cCnaen2kSJXLFD8ghbXyZCMQf/8e8Ns1XVAG/XAgqKzVnJFAAAAABJRU5ErkJggg==" - osAccountManager.setOsAccountProfilePhoto(localId, photo, (err)=>{ + accountManager.setOsAccountProfilePhoto(localId, photo, (err)=>{ console.log("setOsAccountProfilePhoto err:" + JSON.stringify(err)); }); ``` @@ -1765,8 +1760,9 @@ This is a system API and cannot be called by third-party applications. **Example** ```js + const accountManager = account_osAccount.getAccountManager(); var testUid = 1000000; - osAccountManager.getBundleIdFromUid(testUid,(err,bundleId)=>{ + accountManager.getBundleIdFromUid(testUid, (err, bundleId) => { console.info("getBundleIdFromUid errInfo:" + JSON.stringify(err)); console.info("getBundleIdFromUid bundleId:" + JSON.stringify(bundleId)); }); @@ -1796,10 +1792,13 @@ This is a system API and cannot be called by third-party applications. **Example** ```js + const accountManager = account_osAccount.getAccountManager(); var testUid = 1000000; - var bundleIdInfo = await osAccountManager.getBundleIdFromUid(testUid).catch((err)=>{ - console.info("getBundleIdFromUid errInfo:" + JSON.stringify(err));}) - console.info("getBundleIdFromUid bundleId:" + JSON.stringify(bundleIdInfo)); + accountManager.getBundleIdFromUid(testUid).then((result) => { + console.info("getBundleIdFromUid bundleId:" + JSON.stringify(result)); + }).catch((err)=>{ + console.info("getBundleIdFromUid errInfo:" + JSON.stringify(err)); + }); ``` ### isMainOsAccount9+ @@ -1810,6 +1809,8 @@ Checks whether the current process belongs to the main OS account. This API uses This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + **System capability**: SystemCapability.Account.OsAccount **Parameters** @@ -1821,7 +1822,8 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - osAccountManager.isMainOsAccount((err,result)=>{ + const accountManager = account_osAccount.getAccountManager(); + accountManager.isMainOsAccount((err,result)=>{ console.info("isMainOsAccount errInfo:" + JSON.stringify(err)); console.info("isMainOsAccount result:" + JSON.stringify(result)); }); @@ -1834,6 +1836,8 @@ Checks whether the current process belongs to the main OS account. This API uses This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS + **System capability**: SystemCapability.Account.OsAccount **Return value** @@ -1845,10 +1849,12 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - var result = await osAccountManager.isMainOsAccount().catch((err)=>{ + const accountManager = account_osAccount.getAccountManager(); + accountManager.isMainOsAccount().then((result) => { + console.info("isMainOsAccount result:" + JSON.stringify(result)); + }).catch((err)=>{ console.info("isMainOsAccount errInfo:" + JSON.stringify(err)); }); - console.info("isMainOsAccount result:" + JSON.stringify(result)); ``` ### queryOsAccountConstraintSourceTypes9+ @@ -1873,7 +1879,8 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - osAccountManager.queryOsAccountConstraintSourceTypes(100, "constraint.wifi",(err,sourceTypeInfos)=>{ + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryOsAccountConstraintSourceTypes(100, "constraint.wifi",(err,sourceTypeInfos)=>{ console.info("queryOsAccountConstraintSourceType errInfo:" + JSON.stringify(err)); console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); }); @@ -1907,27 +1914,33 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - var sourceTypeInfos = await osAccountManager.queryOsAccountConstraintSourceTypes(100, "constraint.wifi").catch((err)=>{ - console.info("queryOsAccountConstraintSourceType errInfo:" + JSON.stringify(err));}) - console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); + const accountManager = account_osAccount.getAccountManager(); + accountManager.queryOsAccountConstraintSourceTypes(100, "constraint.wifi").then((result) => { + console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(result)); + }).catch((err)=>{ + console.info("queryOsAccountConstraintSourceType errInfo:" + JSON.stringify(err)); + }); ``` ## UserAuth8+ Provides APIs for user authentication. +This is a system API and cannot be called by third-party applications. + ### constructor8+ constructor() A constructor used to create an instance for user authentication. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount **Example** ```js - let userAuth = new osAccount.UserAuth(); - console.info('====>test for examples constructor success'); + let userAuth = new account_osAccount.UserAuth(); ``` @@ -1949,17 +1962,16 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - let userAuth = new osAccount.UserAuth(); - console.info('====>test for examples constructor success'); - var version = userAuth.getVersion(); - console.info('====>test for examples version is : ' + JSON.stringify(version)); + let userAuth = new account_osAccount.UserAuth(); + let version = userAuth.getVersion(); + console.log("getVersion version = " + version); ``` ### getAvailableStatus8+ getAvailableStatus(authType: AuthType, authTrustLevel: AuthTrustLevel): number; -Checks whether the identity authentication function is available. +Checks whether the identity authentication feature is available. This is a system API and cannot be called by third-party applications. @@ -1971,23 +1983,22 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | --------------- | -----------------------------------------------| ---- | ------------------------- | -| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | -| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result.| +| authType | [AuthType](#authtype8) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result.| **Return value** | Type | Description | | :----- | :---------------------------------------- | -| number | Result code(#ResultCode8+).| +| number | [Result code](#resultcode8).| **Example** ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let authTrustLevel = osAccount.AuthTrustLevel.ATL1; - console.info('====>test for examples constructor success'); - let availableStatus = userAuth.getAvailableStatus(authType, authTrustLevel); - console.info('====>test for examples AvailabeStatus is : ' + JSON.stringify(availableStatus)); + let userAuth = new account_osAccount.UserAuth(); + let authType = account_osAccount.AuthType.PIN; + let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; + let status = userAuth.getAvailableStatus(authType, authTrustLevel); + console.log("getAvailableStatus status = " + status); ``` ### getProperty8+ @@ -2006,26 +2017,30 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------------------- | ---- | ---------------------------------- | -| request | [GetPropertyRequest](#GetPropertyRequest8+) | Yes | Request information, including the authentication credential type and property list.| -| callback | AsyncCallback<[ExecutorProperty](#ExecutorProperty8+)> | Yes | Callback invoked to return the executor property obtained. | +| request | [GetPropertyRequest](#getpropertyrequest8) | Yes | Request information, including the authentication credential type and property list.| +| callback | AsyncCallback<[ExecutorProperty](#executorproperty8)> | Yes | Callback invoked to return the executor property obtained. | **Example** ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let keys = new Array(); - keys[0] = osAccount.GetPropertyType.AUTH_SUB_TYPE; - keys[1] = osAccount.GetPropertyType.REMAIN_TIMES; - keys[2] = osAccount.GetPropertyType.FREEZING_TIME; - let getPropertyRequest = {authType, keys}; - userAuth.getProperty(getPropertyRequest,function (propReq) { - console.log("====>test for examples getallAuthInfo AsyncCallback = " + JSON.stringify(propReq)); - }) + let userAuth = new account_osAccount.UserAuth(); + let keys = [ + account_osAccount.GetPropertyType.AUTH_SUB_TYPE, + account_osAccount.GetPropertyType.REMAIN_TIMES, + account_osAccount.GetPropertyType.FREEZING_TIME + ]; + let request = { + authType: account_osAccount.AuthType.PIN, + keys: keys + }; + userAuth.getProperty(request, (err, result) => { + console.log("getProperty err = " + JSON.stringify(err)); + console.log("getProperty result = " + JSON.stringify(result)); + }); ``` ### getProperty8+ -getProperty(request: GetPropertyRequest): Promise; +getProperty(request: GetPropertyRequest): Promise<ExecutorProperty>; Obtains the executor property based on the request. This API uses a promise to return the result. @@ -2039,31 +2054,36 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------ | ---- | ---------------------------------- | -| request | [GetPropertyRequest](#GetPropertyRequest8+) | Yes | Request information, including the authentication credential type and property list.| +| request | [GetPropertyRequest](#getpropertyrequest8) | Yes | Request information, including the authentication credential type and property list.| **Return value** | Type | Description | | :---------------------------------------------------------------- | :-------------------------------------------------- | -| Promise<[ExecutorProperty](#ExecutorProperty8+)> | Promise used to return the executor property obtained.| - -**Example** - ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let keys = new Array(); - keys[0] = osAccount.GetPropertyType.AUTH_SUB_TYPE; - keys[1] = osAccount.GetPropertyType.REMAIN_TIMES; - keys[2] = osAccount.GetPropertyType.FREEZING_TIME; - let getPropertyRequest = {authType, keys}; - userAuth.getProperty(getPropertyRequest).then((propReq) => { - console.log("====>test for examples getallAuthInfo AsyncCallback = " + JSON.stringify(propReq)); +| Promise<[ExecutorProperty](#executorproperty8)> | Promise used to return the executor property obtained.| + +**Example** + ```js + let userAuth = new account_osAccount.UserAuth(); + let keys = [ + account_osAccount.GetPropertyType.AUTH_SUB_TYPE, + account_osAccount.GetPropertyType.REMAIN_TIMES, + account_osAccount.GetPropertyType.FREEZING_TIME + ]; + let request = { + authType: account_osAccount.AuthType.PIN, + keys: keys + }; + userAuth.getProperty(request).then((result) => { + console.log("getProperty result = " + JSON.stringify(result)); + }).catch((err) => { + console.log("getProperty error = " + JSON.stringify(err)); }); ``` ### setProperty8+ -setProperty(request: SetPropertyRequest, callback: AsyncCallback): void; +setProperty(request: SetPropertyRequest, callback: AsyncCallback<number>): void; Sets the property for the initialization algorithm. This API uses an asynchronous callback to return the result. @@ -2077,24 +2097,26 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------------------------- | -| request | [SetPropertyRequest](#SetPropertyRequest8+)| Yes | Request information, including the authentication credential type and key value to set. | -| callback | AsyncCallback<number> | Yes | Callback invoked to return the [result code](#ResultCode8+).| +| request | [SetPropertyRequest](#setpropertyrequest8)| Yes | Request information, including the authentication credential type and key value to set. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the [result](#resultcode8).| **Example** ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let key = osAccount.SetPropertyType.INIT_ALGORITHM; - let setInfo = new Uint8Array(); - let setPropertyRequest = {authType, key, setInfo}; - userAuth.setProperty(setPropertyRequest,function (setProp) { - console.log("====>test for examples setProperty AsyncCallback = " + JSON.stringify(setProp)); + let userAuth = new account_osAccount.UserAuth(); + let request = { + authType: account_osAccount.AuthType.PIN, + key: account_osAccount.SetPropertyType.INIT_ALGORITHM, + setInfo: new Uint8Array([0]) + }; + userAuth.setProperty(request, (err, result) => { + console.log("setProperty error = " + JSON.stringify(err)); + console.log("setProperty result = " + JSON.stringify(result)); }); ``` ### setProperty8+ -setProperty(request: SetPropertyRequest): Promise; +setProperty(request: SetPropertyRequest): Promise<number>; Sets the property for the initialization algorithm. This API uses a promise to return the result. @@ -2108,23 +2130,26 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------ | ---- | ---------------------------------------- | -| request | [SetPropertyRequest](#SetPropertyRequest8+) | Yes | Request information, including the authentication credential type and the key value to set.| +| request | [SetPropertyRequest](#setpropertyrequest8) | Yes | Request information, including the authentication credential type and the key value to set.| **Return value** | Type | Description | | :-------------------- | :-------------------------------------------------------------------------------------------- | -| Promise<number> | Promise used to return the [result code](#ResultCode8+).| +| Promise<number> | Promise used to return the [result](#resultcode8).| **Example** ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let key = osAccount.SetPropertyType.INIT_ALGORITHM; - let setInfo = new Uint8Array(); - let setPropertyRequest = {authType, key, setInfo}; - userAuth.setProperty(setPropertyRequest).then((setProp) => { - console.log("====>test for examples setProperty AsyncCallback = " + JSON.stringify(setProp)); + let userAuth = new account_osAccount.UserAuth(); + let request = { + authType: account_osAccount.AuthType.PIN, + key: account_osAccount.SetPropertyType.INIT_ALGORITHM, + setInfo: new Uint8Array([0]) + }; + userAuth.setProperty(request).then((result) => { + console.log("setProperty result = " + JSON.stringify(result)); + }).catch((err) => { + console.log("setProperty error = " + JSON.stringify(err)); }); ``` @@ -2145,9 +2170,9 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | --------------- | ---------------------------------------------------- | --- | ------------------------------------ | | challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security.| -| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | -| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result. | -| callback | [IUserAuthCallback](#IUserAuthCallback8+) | Yes | Callback invoked to return the authentication result and obtained information. | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result and obtained information. | **Return value** @@ -2158,22 +2183,15 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let challenge = 1; - let authTrustLevel = osAccount.AuthTrustLevel.ATL1; - let onresult = { - authresult: null, - authextr: null, - } - userAuth.auth(challenge, authType,authTrustLevel,{ - onResult: function(result,extraInfo){ - console.log("====>test for examples auth result = " + result); - onresult.authresult = result; - console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); - onresult.authextr = extraInfo; - console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); - } + let userAuth = new account_osAccount.UserAuth(); + let challenge = new Uint8Array([0]); + let authType = account_osAccount.AuthType.PIN; + let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; + userAuth.auth(challenge, authType, authTrustLevel, { + onResult: function(result,extraInfo){ + console.log("auth result = " + result); + console.log("auth extraInfo = " + JSON.stringify(extraInfo)); + } }); ``` @@ -2195,9 +2213,9 @@ This is a system API and cannot be called by third-party applications. | --------------- | ---------------------------------------------------- | --- | ------------------------------------ | | userId | number | Yes | User ID. | | challenge | Uint8Array | Yes | Challenge value, which is a random number used to improve security. | -| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | -| authTrustLevel | [AuthTrustLevel](#AuthTrustLevel8+) | Yes | Trust level of the authentication result. | -| callback | [IUserAuthCallback](#IUserAuthCallback8+) | Yes | Callback invoked to return the authentication result and obtained information. | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| callback | [IUserAuthCallback](#iuserauthcallback8) | Yes | Callback invoked to return the authentication result and obtained information. | **Return value** @@ -2208,23 +2226,16 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let challenge = 1; - let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let userAuth = new account_osAccount.UserAuth(); let userID = 100; - let onresult = { - authresult: null, - authextr: null, - } + let challenge = new Uint8Array([0]); + let authType = account_osAccount.AuthType.PIN; + let authTrustLevel = account_osAccount.AuthTrustLevel.ATL1; userAuth.authUser(userID, challenge, authType, authTrustLevel, { - onResult: function(result,extraInfo){ - console.log("====>test for examples authUser result = " + result); - onresult.authresult = result; - console.log("====>test for examples authUser extraInfo = " + JSON.stringify(extraInfo)); - onresult.authextr = extraInfo; - console.info('====>test for examples authUser onResult = ' + JSON.stringify(onresult)); - } + onResult: function(result,extraInfo){ + console.log("authUser result = " + result); + console.log("authUser extraInfo = " + JSON.stringify(extraInfo)); + } }); ``` @@ -2250,20 +2261,28 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | :----- | :-------------------------------------------------------- | -| number | [Result code](#ResultCode8+).| +| number | [Result code](#resultcode8).| **Example** ```js - let userAuth = new osAccount.UserAuth(); - let contextID = null; - let cancelAuthresult = null; - cancelAuthresult = userAuth.cancelAuth(contextID); - console.log("====>test for examples cancelAuthresult result = " + JSON.stringify(cancelAuthresult)); + let userAuth = new account_osAccount.UserAuth(); + let pinAuth = new account_osAccount.PINAuth(); + let challenge = new Uint8Array([0]); + let contextID = userAuth.auth(challenge, account_osAccount.AuthType.PIN, account_osAccount.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + console.log("auth result = " + result); + console.log("auth extraInfo = " + JSON.stringify(extraInfo)); + } + }); + let result = userAuth.cancelAuth(contextID); + console.log("cancelAuth result = " + result); ``` ## PINAuth8+ -Provides methods for PIN authentication. +Provides APIs for PIN authentication. + +This is a system API and cannot be called by third-party applications. ### constructor8+ @@ -2271,12 +2290,13 @@ constructor() A constructor used to create an instance for PIN authentication. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount **Example** ```js - var pinAuth = new osAccount.PINAuth(); - console.info('====>test for examples constructor success'); + let pinAuth = new account_osAccount.PINAuth(); ``` ### registerInputer @@ -2295,7 +2315,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ----------| ----------------------------------- | --- | ------------------ | -| inputer | [IInputer](#IInputer8+) | Yes | Callback invoked to obtain the PIN.| +| inputer | [IInputer](#iinputer8) | Yes | Callback invoked to obtain the PIN.| **Return value** @@ -2305,20 +2325,14 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - var pinAuth = new osAccount.PINAuth(); - var GetAuthSubType = 0; - var AuthSubType = osAccount.AuthSubType.PIN_SIX; - var Inputerdata = [0,1,3]; - var registerresult = pinAuth.registerInputer({ - onGetData: (GetAuthSubType, IInputData) => { - if (GetAuthSubType == 0) { - IInputData.onSetData(AuthSubType, Inputerdata) - } else { - IInputData.onSetData(GetAuthSubType, Inputerdata); - } + let pinAuth = new account_osAccount.PINAuth(); + let password = new Uint8Array([0, 0, 0, 0, 0]); + let result = pinAuth.registerInputer({ + onGetData: (pinSubType, callback) => { + callback.onSetData(pinSubType, password); } - }) - console.log("====>test for examples RegisterInputer result is: " + registerresult); + }); + console.log("registerInputer result = " + result); ``` ### unregisterInputer @@ -2335,13 +2349,15 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - var pinAuth = new osAccount.PinAuth(); + let pinAuth = new account_osAccount.PINAuth(); pinAuth.unregisterInputer(); ``` ## UserIdentityManager8+ -Provides methods for user identity management. +Provides APIs for user identity management. + +This is a system API and cannot be called by third-party applications. ### constructor8+ @@ -2349,12 +2365,13 @@ constructor() A constructor used to create an instance for user authentication. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - console.info('====>test for examples constructor success'); + let userIDM = new account_osAccount.UserIdentityManager(); ``` ### openSession8+ @@ -2373,23 +2390,14 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | -------------------------------- | ---- | -------------------------------- | -| callback | AsyncCallback<Uint8Array> | Yes | Callback invoked to return the result. If **0** is returned, the operation failed. If the operation is successful, the challenge value (a non-zero value) will be returned.| +| callback | AsyncCallback<Uint8Array> | Yes | Callback invoked to return the challenge value. If **0** is returned, the operation failed.| **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - var challenge; - userIDM.openSession(function(err, data){ - try{ - console.log("====>test for examples before get challenge"); - console.log("====>test for examples + " + data); - challenge = data; - console.log("====>test for examples end "); - console.log("====>test for examples after get challenge"); - } - catch(e) { - console.info('====>test for examples openSession error = ' + JSON.stringify(e)); - } + let userIDM = new account_osAccount.UserIdentityManager(); + userIDM.openSession((err, challenge) => { + console.log("openSession error = " + JSON.stringify(err)); + console.log("openSession challenge = " + JSON.stringify(challenge)); }); ``` @@ -2409,27 +2417,16 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | :------------------------ | :------------------------------------------------------- | -| Promise<Uint8Array> | Promise used to return the result. If **0** is returned, the operation failed. If the operation is successful, the challenge value (a non-zero value) will be returned.| +| Promise<Uint8Array> | Promise used to return the challenge value. If **0** is returned, the operation failed.| **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - var challenge; - userIDM.openSession().then((data) => { - try{ - console.log("====>test for examples before get challenge"); - console.log("====>test for examples + " + data); - challenge = data; - console.log("====>test for examples end "); - console.log("====>test for examples after get challenge"); - } - catch(err) { - console.info('====>test for examples faceDemo openSession error1 = ' + JSON.stringify(err)); - } - }) - .catch((err) => { - console.info('====>test for examples faceDemo openSession error2 = ' + JSON.stringify(err)); - }) + let userIDM = new account_osAccount.UserIdentityManager(); + userIDM.openSession().then((challenge) => { + console.info("openSession challenge = " + JSON.stringify(challenge)); + }).catch((err) => { + console.info("openSession error = " + JSON.stringify(err)); + }); ``` ### addCredential8+ @@ -2448,31 +2445,32 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------ | --- | -------------------------------- | -| credentialInfo | [CredentialInfo](#CredentialInfo8+) | Yes | Credential information to add. | -| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result and obtained information. | +| credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | Credential information to add. | +| callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result and obtained information. | **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - let CredentialInfo = null; - let onresult = { - addCredresult: null, - credentialId: null, - } - userIDM.addCredential(CredentialInfo, { - onResult: function(result,extraInfo){ - console.info('====>test for examples aaaaaaaaaaaaa'); - console.info("====>test for examples addCredential result = " + result); - console.info("====>test for examples addCredential extraInfo = " + JSON.stringify(extraInfo)); - console.log(result) - onresult.addCredresult= result; - if(extraInfo != undefined) { - onresult.credentialId = extraInfo.credentialId - } else { - onresult.credentialId = null; - } + 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); + } + }); + let credentialInfo = { + credType: account_osAccount.AuthType.PIN, + credSubType: account_osAccount.AuthSubType.PIN_SIX, + token: null + }; + let userIDM = new account_osAccount.UserIdentityManager(); + userIDM.openSession((err, challenge) => { + userIDM.addCredential(credentialInfo, { + onResult: (result, extraInfo) => { + console.log("updateCredential result = " + result); + console.log("updateCredential extraInfo = " + extraInfo); } - }) + }); + }); ``` ### updateCredential8+ @@ -2491,30 +2489,41 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------- | --- | -------------------------------- | -| credentialInfo | [CredentialInfo](#CredentialInfo8+) | Yes | New credential information. | -| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result and obtained information. | - -**Example** - ```js - var userIDM = new osAccount.UserIdentityManager(); - let CredentialInfo = null; - let onresult = { - addCredresult: null, - credentialId: null, - } - userIDM.updateCredential(CredentialInfo, { - onResult: function(result,extraInfo){ - console.log("====>test for examples faceDemo updateCredential result = " + result) - onresult.updateCredresult = result - console.log("====>test for examples faceDemo updateCredential credentialId = " + extraInfo.credentialId) - if(extraInfo != undefined) { - onresult.CredentialId = extraInfo.credentialId - } else { - onresult.CredentialId = null; +| credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | New credential information. | +| callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result and obtained information. | + +**Example** + ```js + let userIDM = new account_osAccount.UserIdentityManager(); + let userAuth = new account_osAccount.UserAuth(); + let pinAuth = new account_osAccount.PINAuth(); + let password = new Uint8Array([0, 0, 0, 0, 0, 0]); + let credentialInfo = { + credType: account_osAccount.AuthType.PIN, + credSubType: account_osAccount.AuthSubType.PIN_SIX, + token: null + }; + pinAuth.registerInputer({ + onGetData: (pinSubType, callback) => { + callback.onSetData(pinSubType, password); + } + }); + userIDM.openSession((err, challenge) => { + userAuth.auth(challenge, credentialInfo.credType, account_osAccount.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + if (result != account_osAccount.ResultCode.SUCCESS) { + return; + } + credentialInfo.token = extraInfo.token; + userIDM.updateCredential(credentialInfo, { + onResult: (result, extraInfo) => { + console.log("updateCredential result = " + result); + console.log("updateCredential extraInfo = " + extraInfo); } - console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); + }); } - }) + }); + }); ``` ### closeSession8+ @@ -2531,7 +2540,7 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); + let userIDM = new account_osAccount.UserIdentityManager(); userIDM.closeSession(); ``` @@ -2557,13 +2566,14 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | :----- | :-------------------------------------------------------- | -| number | [Result code](#ResultCode8+).| +| number | [Result code](#resultcode8) indicating whether the operation is successful.| **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - let challenge = 1; - let cancelresult = userIDM.cancel(challenge); + let userIDM = new account_osAccount.UserIdentityManager(); + let challenge = new Uint8Array([0]); + let result = userIDM.cancel(challenge); + console.log("cancel result: " + result); ``` ### delUser8+ @@ -2583,28 +2593,18 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------ | --- | ------------------------- | | token | Uint8Array | Yes | Authentication token. | -| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result.| +| callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result.| **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - let onresult = { - delUserresult: null, - CredentialId: null, - } - let token = null; + let userIDM = new account_osAccount.UserIdentityManager(); + let token = new Uint8Array([0]); userIDM.delUser(token, { - onResult: function(result,extraInfo){ - console.log("====>test for examples delUser result = " + result) - onresult.delUserresult = result - if(extraInfo != undefined) { - onresult.CredentialId = extraInfo.credentialId - } else { - onresult.CredentialId = null; - } - console.info('====>test for examples publicdelUser delUser = ' + JSON.stringify(onresult)); - } - }) + onResult: (result, extraInfo) => { + console.log("delUser result = " + result); + console.log("delUser extraInfo = " + JSON.stringify(extraInfo)); + } + }); ``` ### delCred8+ @@ -2625,35 +2625,24 @@ This is a system API and cannot be called by third-party applications. | --------------- | ----------------------------------------------- | --- | ---------------------------| | credentialId | Uint8Array | Yes | Credential ID. | | token | Uint8Array | Yes | Authentication token. | -| callback | [IIdmCallback](#IIdmCallback8+) | Yes | Callback invoked to return the result.| +| callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the result.| **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - let onresult = { - delUserresult: null, - CredentialId: null, - } - let credentialId = 1; - let token = null; - userIDM.delCred(credentialId, token,{ - onResult: function(result,extraInfo){ - console.log("====>test for examples delCred result = " + result) - onresult.delCredresult = result - console.log("====>test for examples delCred extraInfo = " + extraInfo) - if(extraInfo != undefined) { - onresult.CredentialId = extraInfo.credentialId - } else { - onresult.CredentialId = null; - } - console.log("====>test for examples delCred onresult = " + JSON.stringify(onresult)); - } - }) + let userIDM = new account_osAccount.UserIdentityManager(); + let credentialId = new Uint8Array([0]); + let token = new Uint8Array([0]); + userIDM.delCred(credentialId, token, { + onResult: (result, extraInfo) => { + console.log("delCred result = " + result); + console.log("delCred extraInfo = " + JSON.stringify(extraInfo)); + } + }); ``` ### getAuthInfo8+ -getAuthInfo(callback: AsyncCallback<Array<EnrolledCredInfo>>, authType?: AuthType): void; +getAuthInfo(callback: AsyncCallback<Array<EnrolledCredInfo>>): void; Obtains authentication information. This API uses asynchronous callback to return the result. @@ -2661,22 +2650,50 @@ This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_USER_IDM +**Required permissions**: ohos.permission.USE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | -------------------------------------------------- | +| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return information about all enrolled credentials of the specified type.| + + +**Example** + ```js + let userIDM = new account_osAccount.UserIdentityManager(); + userIDM.getAuthInfo((err, result) => { + console.log("getAuthInfo err = " + JSON.stringify(err)); + console.log("getAuthInfo result = " + JSON.stringify(result)); + }); + ``` + +### getAuthInfo8+ + +getAuthInfo(authType: AuthType, callback: AsyncCallback<Array<EnrolledCredInfo>>): void; + +Obtains authentication information of the specified type. This API uses an asynchronous callback to return the result. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.USE_USER_IDM **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | -------------------------------------------------- | -| callback | AsyncCallback<Array<[EnrolledCredInfo](#EnrolledCredInfo8+)>> | Yes | Callback invoked to return information about all enrolled credentials of the specified type of the user.| -| authType | [AuthType](#AuthType8+) | No | Authentication credential type. | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type. | +| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return information about all the user's enrolled credentials of the specified type.| **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - var authType = osAccount.AuthType.PIN; - userIDM.getAuthInfo(authType, function (authInfo) { - console.log("====>test for examples getAuthInfo AsyncCallback = " + JSON.stringify(authInfo)) - }) + let userIDM = new account_osAccount.UserIdentityManager(); + userIDM.getAuthInfo(account_osAccount.AuthType.PIN, (err, result) => { + console.log("getAuthInfo err = " + JSON.stringify(err)); + console.log("getAuthInfo result = " + JSON.stringify(result)); + }); ``` ### getAuthInfo8+ @@ -2689,37 +2706,42 @@ This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_USER_IDM +**Required permissions**: ohos.permission.USE_USER_IDM **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | -------- | -| authType | [AuthType](#AuthType8+) | No | Authentication credential type.| +| authType | [AuthType](#authtype8) | No | Authentication credential type.| **Return value** | Type | Description | | :------------------------------------------- | :------------------------------------------------------------------------ | -| Promise<Array<[EnrolledCredInfo](#EnrolledCredInfo8+)>> | Promise used to return information about all enrolled credentials of the specified type of the user.| +| Promise<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Promise used to return information about all the user's enrolled credentials of the specified type.| **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - var authType = osAccount.AuthType.PIN; - userIDM.getAuthInfo(authType).then((authInfo) => { - console.log("====>test for examples getAuthInfo AsyncCallback = " + JSON.stringify(authInfo)) - }) + let userIDM = new account_osAccount.UserIdentityManager(); + userIDM.getAuthInfo(account_osAccount.AuthType.PIN).then((result) => { + console.log("getAuthInfo result = " + JSON.stringify(result)) + }).catch((err) => { + console.log("getAuthInfo error = " + JSON.stringify(err)); + }); ``` ## IInputData8+ Provides callbacks for PIN operations. +This is a system API and cannot be called by third-party applications. + ### onSetData8+ onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; +This is a system API and cannot be called by third-party applications. + Called to set data. **System capability**: SystemCapability.Account.OsAccount @@ -2728,85 +2750,78 @@ Called to set data. | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | -| pinSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype. | +| pinSubType | [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** ```js - console.log("====>test for examples onCreate start "); - var pinAuth = new osAccount.PINAuth(); - var GetAuthSubType = 0; - var AuthSubType = osAccount.AuthSubType.PIN_SIX; - console.log("====>test for examples GetAuthSubType " + GetAuthSubType); - console.log("====>test for examples AuthSubType " + AuthSubType); - var Inputerdata = [0,1,3]; - var registerresult = pinAuth.registerInputer({ - onGetData: (GetAuthSubType, IInputData) => { - console.log("====>test for examples by GetAuthSubType " +GetAuthSubType ); - if (GetAuthSubType == 0) { - console.log("====>test for examples GetAuthSubType == 0 "); - IInputData.onSetData(AuthSubType, Inputerdata) - } else { - console.log("====>test for examples GetAuthSubType == 1 "); - IInputData.onSetData(GetAuthSubType, Inputerdata); - } - } - }) - console.log("====>test for examples RegisterInputer result is: " + registerresult); + 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); + } else { + callback.onSetData(pinSubType, password); + } + } + }; ``` ## IInputer8+ Provides callbacks for the PIN input box. +This is a system API and cannot be called by third-party applications. + ### onGetData8+ -onGetData: (callback: IInputData) => void; +onGetData: (pinSubType: AuthSubType, callback: IInputData) => void; Called to obtain data. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount **Parameters** | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | --------------- | -| callback | [IInputData](#IInputData8+) | Yes | Called to input the PIN.| - -**Example** - ```js - console.log("====>test for examples onCreate start "); - var pinAuth = new osAccount.PINAuth(); - var GetAuthSubType = 0; - var AuthSubType = osAccount.AuthSubType.PIN_SIX; - console.log("====>test for examples GetAuthSubType " + GetAuthSubType); - console.log("====>test for examples AuthSubType " + AuthSubType); - var Inputerdata = [0,1,3]; - var registerresult = pinAuth.registerInputer({ - onGetData: (GetAuthSubType, IInputData) => { - console.log("====>test for examples by GetAuthSubType " +GetAuthSubType ); - if (GetAuthSubType == 0) { - console.log("====>test for examples GetAuthSubType == 0 "); - IInputData.onSetData(AuthSubType, Inputerdata) - } else { - console.log("====>test for examples GetAuthSubType == 1 "); - IInputData.onSetData(GetAuthSubType, Inputerdata); - } - } - }) - console.log("====>test for examples RegisterInputer result is: " + registerresult); +| callback | [IInputData](#iinputdata8) | Yes | Called to input the PIN.| + +**Example** + ```js + 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); + } else { + callback.onSetData(pinSubType, password); + } + } + }; + let pinAuth = new account_osAccount.PINAuth(); + let result = pinAuth.registerInputer(inputer); + console.log("registerInputer result: " + result); ``` ## IUserAuthCallback8+ Provides callbacks for user authentication. +This is a system API and cannot be called by third-party applications. + ### onResult8+ onResult: (result: number, extraInfo: AuthResult) => void; Called to return the authentication result code. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount **Parameters** @@ -2814,27 +2829,16 @@ Called to return the authentication result code. | Name | Type | Mandatory| Description | | --------- | --------------------------------------- | ---- | ------------------- | | result | number | Yes | Authentication result code.| -| extraInfo | [AuthResult](#AuthResult8+) | Yes | Specific authentication result information. If the authentication is successful, the authentication token is returned in **extrainfo**. If the authentication fails, the remaining authentication time is returned. If the authentication executor is locked, the freezing time is returned.| +| extraInfo | [AuthResult](#authresult8) | Yes | Specific authentication result information. If the authentication is successful, the authentication token is returned in **extrainfo**. If the authentication fails, the remaining authentication time is returned. If the authentication executor is locked, the freezing time is returned.| **Example** ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let challenge = 1; - let authTrustLevel = osAccount.AuthTrustLevel.ATL1; - let onresult = { - authresult: null, - authextr: null, - } - userAuth.auth(challenge, authType,authTrustLevel,{ - onResult: function(result,extraInfo){ - console.log("====>test for examples auth result = " + result); - onresult.authresult = result; - console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); - onresult.authextr = extraInfo; - console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); - } - }); + let authCallback = { + onResult: (result, extraInfo) => { + console.log("auth result = " + result); + console.log("auth extraInfo = " + JSON.stringify(extraInfo)); + } + }; ``` ### onAcquireInfo?8+ @@ -2857,45 +2861,28 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - let userAuth = new osAccount.UserAuth(); - let authType = osAccount.AuthType.PIN; - let challenge = 1; - let authTrustLevel = osAccount.AuthTrustLevel.ATL1; - let onresult = { - authresult: null, - authextr: null, - } - let onacquireinfo = { - authmodule : null, - authacquire : null, - authextr : null - } - userAuth.auth(challenge, authType,authTrustLevel,{ - onResult: function(result,extraInfo){ - console.log("====>test for examples auth result = " + result) - onresult.authresult = result - console.log("====>test for examples auth extraInfo = " + JSON.stringify(extraInfo)); - onresult.authextr = extraInfo; - console.info('====>test for examples auth onResult = ' + JSON.stringify(onresult)); - }, - onAcquireInfo:function (modulea,acquire,extr){ - console.info('====>test for examples publicauth auth onAcquireInfo in'); - onacquireinfo.authmodule = modulea; - onacquireinfo.authacquire = acquire; - onacquireinfo.authextr = extr; - console.log("====>test for examples auth module = " + JSON.stringify(modulea)); - console.info('====>test for examples publicauth auth onAcquireInfo = ' + JSON.stringify(onacquireinfo)); - } - }); + let authCallback = { + onResult: (result, extraInfo) => { + console.log("auth result = " + result) + console.log("auth extraInfo = " + JSON.stringify(extraInfo)); + }, + onAcquireInfo: (module, acquire, extraInfo) => { + console.log("auth module = " + module); + console.log("auth acquire = " + acquire); + console.info('auth extraInfo = ' + JSON.stringify(extraInfo)); + } + }; ``` ## IIdmCallback8+ Provides callbacks for IDM. +This is a system API and cannot be called by third-party applications. + ### onResult8+ -onResult: (result: number, extraInfo: AuthResult) => void; +onResult: (result: number, extraInfo: RequestResult) => void; Called to return the authentication result code. @@ -2908,29 +2895,16 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | --------- | --------------------------------------- | ---- | ----------------------- | | result | number | Yes | Authentication result code. | -| extraInfo | [AuthResult](#AuthResult8+) | Yes | Specific information to be transferred.| +| extraInfo | [AuthResult](#authresult8) | Yes | Specific information to be transferred.| **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - let CredentialInfo = null; - let onresult = { - addCredresult: null, - credentialId: null, - } - userIDM.updateCredential(CredentialInfo, { - onResult: function(result,extraInfo){ - console.log("====>test for examples updateCredential result = " + result) - onresult.updateCredresult = result - console.log("====>test for examples updateCredential credentialId = " + extraInfo.credentialId) - if(extraInfo != undefined) { - onresult.CredentialId = extraInfo.credentialId - } else { - onresult.CredentialId = null; - } - console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); - } - }) + var idmCallback = { + onResult: (result, extraInfo) => { + console.log("callback result = " + result) + console.info('callback extraInfo = ' + JSON.stringify(extraInfo)); + } + }; ``` ### onAcquireInfo?8+ @@ -2953,73 +2927,58 @@ This is a system API and cannot be called by third-party applications. **Example** ```js - var userIDM = new osAccount.UserIdentityManager(); - let CredentialInfo = null; - let onresult = { - addCredresult: null, - credentialId: null, - } - let onacquireinfo = { - updateCredmodule : null, - updateCredacquire : null, - updateCredextr : null - } - userIDM.updateCredential(CredentialInfo, { - onResult: function(result,extraInfo){ - console.log("====>test for examples updateCredential result = " + result) - onresult.updateCredresult = result - console.log("====>test for examples updateCredential credentialId = " + extraInfo.credentialId) - if(extraInfo != undefined) { - onresult.CredentialId = extraInfo.credentialId - } else { - onresult.CredentialId = null; - } - console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); - }, - onAcquireInfo:function (modulea,acquire,extr){ - console.info('====>test for examples publicupdateCred updateCredential onAcquireInfo in '); - onacquireinfo.updateCredmodule = modulea - onacquireinfo.updateCredacquire = acquire - onacquireinfo.updateCredextr = extr - console.info('====>test for examples updateCredential onacquireinfo = ' + JSON.stringify(onacquireinfo)); - console.log("====>test for examples updateCredential module = " + modulea) - } - }) + let idmCallback = { + onResult: (result, extraInfo) => { + console.log("callback result = " + result) + console.log("callback onResult = " + JSON.stringify(extraInfo)); + }, + onAcquireInfo: (module, acquire, extraInfo) => { + console.log("callback module = " + module); + console.log("callback acquire = " + acquire); + console.log('callback onacquireinfo = ' + JSON.stringify(extraInfo)); + } + }; ``` ## GetPropertyRequest8+ Defines the request for obtaining property information. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory | Description | | -------- | ------------------------------------------------------------- | ----- | ----------------------- | -| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | -| keys | Array<[GetPropertyType](#GetPropertyType8+)> | Yes | An array of the types of the properties to obtain.| +| authType | [AuthType](#authtype8) | Yes | Authentication credential type. | +| keys | Array<[GetPropertyType](#getpropertytype8)> | Yes | An array of the types of the properties to obtain.| ## SetPropertyRequest8+ Defines the request for setting property information. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory | Description | | -------- | ------------------------------------------------ | ----- | -------------------- | -| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | -| keys | [SetPropertyType](#SetPropertyType8+) | Yes | Type of the property to be set.| +| authType | [AuthType](#authtype8) | Yes | Authentication credential type. | +| key | [SetPropertyType](#setpropertytype8) | Yes | Type of the property to set.| | setInfo | Uint8Array | Yes | Information to set. | ## ExecutorProperty8+ Defines the executor property. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ----- | ----------------- | | result | number | Yes | Result. | -| authSubType | [AuthSubType](#AuthSubType8+) | Yes | Authentication credential subtype.| +| authSubType | [AuthSubType](#authsubtype8) | Yes | Authentication credential subtype.| | remainTimes | number | No | Remaining time. | | freezingTime | number | No | Freezing time. | @@ -3027,6 +2986,8 @@ Defines the executor property. Defines the authentication result information. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory | Description | @@ -3039,18 +3000,22 @@ Defines the authentication result information. Defines the credential information. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ----- | ----------------- | -| credType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | -| credSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype. | +| credType | [AuthType](#authtype8) | Yes | Authentication credential type. | +| credSubType | [AuthSubType](#authsubtype8) | Yes | Authentication credential subtype. | | token | Uint8Array | Yes | Authentication token. | ## RequestResult8+ Defines the request result information. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory | Description | @@ -3061,24 +3026,28 @@ Defines the request result information. Defines enrolled credential information. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ----- | ------------------- | | credentialId | Uint8Array | Yes | Credential ID. | -| authType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | -| authSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype.| -| templateId | Uint8Array | Yes | Credential template ID. | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type. | +| authSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype.| +| templateId | Uint8Array | Yes | Authentication credential template ID. | ## GetPropertyType8+ Enumerates the types of the properties to obtain. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | | ------------- | ------ | --------- | -| AUTH_SUB_TYPE | 1 | Authentication subtype.| +| AUTH_SUB_TYPE | 1 | Authentication credential subtype.| | REMAIN_TIMES | 2 | Remaining time. | | FREEZING_TIME | 3 | Freezing time. | @@ -3086,6 +3055,8 @@ Enumerates the types of the properties to obtain. Enumerates the types of the properties to set. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | @@ -3094,7 +3065,9 @@ Enumerates the types of the properties to set. ## AuthType8+ -Enumerates the credential types. +Enumerates the authentication credential types. + +This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount @@ -3105,7 +3078,9 @@ Enumerates the credential types. ## AuthSubType8+ -Enumerates the credential subtypes. +Enumerates the authentication credential subtypes. + +This is a system API and cannot be called by third-party applications. **System capability**: SystemCapability.Account.OsAccount @@ -3121,6 +3096,8 @@ Enumerates the credential subtypes. Enumerates the trust levels of the authentication result. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | @@ -3134,28 +3111,32 @@ Enumerates the trust levels of the authentication result. Enumerates the modules from which information is obtained. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | | --------- | ------ | ------------------------ | -| FACE_AUTH | 1 | Information obtained from the face authentication module.| +| FACE_AUTH | 1 | Face authentication module.| ## ResultCode8+ Enumerates the authentication result codes. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | | ----------------------- | ----- | ---------------------------------------- | -| SUCCESS | 0 | The authentication is successful or the authentication function is supported. | +| SUCCESS | 0 | The authentication is successful or the authentication feature is supported. | | FAIL | 1 | The authentication executor failed to identify the user. | | GENERAL_ERROR | 2 | Other errors. | | CANCELED | 3 | The authentication is canceled. | | TIMEOUT | 4 | The authentication timed out. | | TYPE_NOT_SUPPORT | 5 | The authentication credential type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | -| BUSY | 7 | The authentication task is not available. Try again after a few seconds.| +| BUSY | 7 | The authentication executor is busy. Try again after a few seconds.| | INVALID_PARAMETERS | 8 | Incorrect parameters are detected. | | LOCKED | 9 | The authentication executor is locked. | | NOT_ENROLLED | 10 | The authentication executor is not enrolled. | @@ -3164,6 +3145,8 @@ Enumerates the authentication result codes. Enumerates the tip codes for facial authentication. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | @@ -3180,10 +3163,12 @@ Enumerates the tip codes for facial authentication. | FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the device. | | FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. | -## ingerprintTips8+ +## FingerprintTips8+ Enumerates the tip codes for fingerprint authentication. +This is a system API and cannot be called by third-party applications. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index 8420e6055aadb9d2e7d45567d25b5fee9c21b795..a05b509b3c5072c28129c1d58a6d2974a4d2a01b 100755 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -64,8 +64,8 @@ This is a system API and cannot be called by third-party applications. **Example** ```js -var child = process.runCmd('ls'); -var result = child.wait(); +let child = process.runCmd('ls'); +let result = child.wait(); result.then(val=>{ console.log("result = " + val); }) @@ -91,8 +91,8 @@ This is a system API and cannot be called by third-party applications. **Example** ```js -var child = process.runCmd('ls'); -var result = child.wait(); +let child = process.runCmd('ls'); +let result = child.wait(); child.getOutput().then(val=>{ console.log("child.getOutput = " + val); }) @@ -118,8 +118,8 @@ This is a system API and cannot be called by third-party applications. **Example** ```js -var child = process.runCmd('madir test.text'); -var result = child.wait(); +let child = process.runCmd('madir test.text'); +let result = child.wait(); child.getErrorOutput().then(val=>{ console.log("child.getErrorOutput= " + val); }) @@ -139,7 +139,7 @@ This is a system API and cannot be called by third-party applications. **Example** ```js -var child = process.runCmd('sleep 5; ls'); +let child = process.runCmd('sleep 5; ls'); child.close(); ``` @@ -163,7 +163,7 @@ This is a system API and cannot be called by third-party applications. **Example** ```js -var child = process.runCmd('sleep 5; ls'); +let child = process.runCmd('sleep 5; ls'); child.kill(9); ``` @@ -185,7 +185,7 @@ Checks whether this process is isolated. **Example** ```js -var result = process.isIsolatedProcess(); +let result = process.isIsolatedProcess(); ``` @@ -212,7 +212,7 @@ Checks whether a UID belongs to this app. **Example** ```js -var result = process.isAppUid(688); +let result = process.isAppUid(688); ``` @@ -233,7 +233,7 @@ Checks whether this process is running in a 64-bit environment. **Example** ```js -var result = process.is64Bit(); +let result = process.is64Bit(); ``` @@ -260,7 +260,7 @@ Obtains the process UID based on the process name. **Example** ```js -var pres = process.getUidForName("tool") +let pres = process.getUidForName("tool") ``` @@ -287,8 +287,8 @@ Obtains the thread priority based on the specified TID. **Example** ```js -var tid = process.tid; -var pres = process.getThreadPriority(tid); +let tid = process.tid; +let pres = process.getThreadPriority(tid); ``` @@ -309,7 +309,7 @@ Obtains the duration, in milliseconds, from the time the system starts to the ti **Example** ```js -var realtime = process.getStartRealtime(); +let realtime = process.getStartRealtime(); ``` ## process.getPastCpuTime8+ @@ -329,7 +329,7 @@ Obtains the CPU time (in milliseconds) from the time the process starts to the c **Example** ```js -var result = process.getPastCpuTime() ; +let result = process.getPastCpuTime() ; ``` @@ -356,8 +356,8 @@ Obtains the system configuration. **Example** ```js -var _SC_ARG_MAX = 0 -var pres = process.getSystemConfig(_SC_ARG_MAX) +let _SC_ARG_MAX = 0 +let pres = process.getSystemConfig(_SC_ARG_MAX) ``` @@ -384,7 +384,7 @@ Obtains the value of an environment variable. **Example** ```js -var pres = process.getEnvironmentVar("PATH") +let pres = process.getEnvironmentVar("PATH") ``` @@ -422,8 +422,8 @@ This is a system API and cannot be called by third-party applications. **Example** ```js -var child = process.runCmd('ls', { maxBuffer : 2 }); -var result = child.wait(); +let child = process.runCmd('ls', { maxBuffer : 2 }); +let result = child.wait(); child.getOutput.then(val=>{ console.log("child.getOutput = " + val); }) @@ -505,7 +505,7 @@ This is a system API and cannot be called by third-party applications. process.on("data", (e)=>{ console.log("data callback"); }) -var result = process.off("data"); +let result = process.off("data"); ``` @@ -545,7 +545,7 @@ This is a system API and cannot be called by third-party applications. **Example** ```js -var path = process.cwd(); +let path = process.cwd(); ``` @@ -589,7 +589,7 @@ Obtains the running time of this process. **Example** ```js -var time = process.uptime(); +let time = process.uptime(); ``` @@ -617,6 +617,6 @@ Sends a signal to the specified process to terminate it. **Example** ```js -var pres = process.pid -var result = process.kill(28, pres) +let pres = process.pid +let result = process.kill(28, pres) ``` diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 971b3408c9a9fdd616fe1133ca3cab3844ee7fd1..e88c899e36745869e6009616b1c8581c3fa37b49 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -21,28 +21,31 @@ Shows a toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------------- | ---- | ------- | | options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| **Example** - ```js + +```js prompt.showToast({ message: 'Message Info', duration: 2000, }); - ``` +``` + ## ShowToastOptions Describes the options for showing the toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ------ | ---------------------------------------- | -| message | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Text to display. | -| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The recommended value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used.| -| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| message | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | ## prompt.showDialog @@ -53,6 +56,7 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | --------------------------------------- | ---- | ------ | | options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| @@ -65,7 +69,7 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **Example** - ```js +```js prompt.showDialog({ title: 'Title Info', message: 'Message Info', @@ -86,7 +90,7 @@ prompt.showDialog({ .catch(err => { console.info('showDialog error: ' + err); }) - ``` +``` ## prompt.showDialog @@ -96,15 +100,16 @@ Shows a dialog box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full - **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------ | | options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| | callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | **Example** - ```js + +```js prompt.showDialog({ title: 'showDialog Title Info', message: 'Message Info', @@ -125,7 +130,7 @@ prompt.showDialog({ } console.info('showDialog success callback, click button: ' + data.index); }); - ``` +``` ## ShowDialogOptions @@ -135,8 +140,8 @@ Describes the options for showing the dialog box. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Title of the dialog box. | -| message | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Text body. | +| title | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Title of the dialog box. | +| message | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Text body. | | buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -159,6 +164,7 @@ Shows an action menu. This API uses a callback to return the result asynchronous **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------- | | options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | @@ -166,7 +172,8 @@ Shows an action menu. This API uses a callback to return the result asynchronous **Example** - ```js + +```js prompt.showActionMenu({ title: 'Title Info', buttons: [ @@ -186,7 +193,7 @@ prompt.showActionMenu({ } console.info('showActionMenu success callback, click button: ' + data.index); }) - ``` +``` ## prompt.showActionMenu @@ -197,17 +204,20 @@ Shows an action menu. This API uses a promise to return the result synchronously **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | --------------------------------------- | ---- | ------- | | options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options.| **Return value** + | Type | Description | | ---------------------------------------- | ------- | | Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| **Example** - ```js + +```js prompt.showActionMenu({ title: 'showActionMenu Title Info', buttons: [ @@ -227,7 +237,7 @@ prompt.showActionMenu({ .catch(err => { console.info('showActionMenu error: ' + err); }) - ``` +``` ## ActionMenuOptions Describes the options for showing the action menu. @@ -236,7 +246,7 @@ Describes the options for showing the action menu. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](.../ui/ts-types.md#resource-type)9+| No | Title of the text to display. | +| title | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Title of the text to display. | | buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse @@ -257,5 +267,5 @@ Describes the menu item button in the action menu. | Name | Type | Mandatory | Description | | ----- | ---------------------------------------- | ---- | ------- | -| text | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Button text.| -| color | string\| [Resource](.../ui/ts-types.md#resource-type)9+| Yes | Text color of the button.| +| text | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Button text.| +| color | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index ee61f71f78a97411006f72225f5ac4a65e09e300..d094a5c7e3abd27ebc042ab377543a3d2898b1e1 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -70,7 +70,7 @@ let promise = radio.getRadioTech(slotId); promise.then(data => { console.log(`getRadioTech success, data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getRadioTech fail, err->${JSON.stringify(err)}`); + console.log(`getRadioTech failed, err->${JSON.stringify(err)}`); }); ``` @@ -157,7 +157,7 @@ let promise = radio.getNetworkState(slotId); promise.then(data => { console.log(`getNetworkState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getNetworkState fail, promise: err->${JSON.stringify(err)}`); + console.log(`getNetworkState failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -215,7 +215,7 @@ let promise = radio.getNetworkSelectionMode(slotId); promise.then(data => { console.log(`getNetworkSelectionMode success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getNetworkSelectionMode fail, promise: err->${JSON.stringify(err)}`); + console.log(`getNetworkSelectionMode failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -273,7 +273,7 @@ let promise = radio.getISOCountryCodeForNetwork(slotId); promise.then(data => { console.log(`getISOCountryCodeForNetwork success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getISOCountryCodeForNetwork fail, promise: err->${JSON.stringify(err)}`); + console.log(`getISOCountryCodeForNetwork failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -322,7 +322,7 @@ let promise = radio.getPrimarySlotId(); promise.then(data => { console.log(`getPrimarySlotId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getPrimarySlotId fail, promise: err->${JSON.stringify(err)}`); + console.error(`getPrimarySlotId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -380,7 +380,7 @@ let promise = radio.getSignalInformation(slotId); promise.then(data => { console.log(`getSignalInformation success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getSignalInformation fail, promise: err->${JSON.stringify(err)}`); + console.error(`getSignalInformation failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -496,7 +496,7 @@ let promise = radio.isRadioOn(slotId); promise.then(data => { console.log(`isRadioOn success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`isRadioOn fail, promise: err->${JSON.stringify(err)}`); + console.error(`isRadioOn failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -554,7 +554,7 @@ let promise = radio.getOperatorName(slotId); promise.then(data => { console.log(`getOperatorName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getOperatorName fail, promise: err->${JSON.stringify(err)}`); + console.log(`getOperatorName failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -564,7 +564,7 @@ setPrimarySlotId(slotId: number, callback: AsyncCallback): void Sets the ID of the slot in which the primary card is located. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -593,7 +593,7 @@ setPrimarySlotId\(slotId: number\): Promise\ Sets the ID of the slot in which the primary card is located. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -619,7 +619,7 @@ let promise = radio.setPrimarySlotId(slotId); promise.then(data => { console.log(`setPrimarySlotId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setPrimarySlotId fail, promise: err->${JSON.stringify(err)}`); + console.log(`setPrimarySlotId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -629,7 +629,7 @@ getIMEI(callback: AsyncCallback): void Obtains the IMEI of the SIM card in a card slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -656,7 +656,7 @@ getIMEI(slotId: number, callback: AsyncCallback): void Obtains the IMEI of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -685,7 +685,7 @@ getIMEI(slotId?: number): Promise Obtains the IMEI of the SIM card in a card slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -711,7 +711,7 @@ let promise = radio.getIMEI(slotId); promise.then(data => { console.log(`getIMEI success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getIMEI fail, promise: err->${JSON.stringify(err)}`); + console.error(`getIMEI failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -721,7 +721,7 @@ getMEID(callback: AsyncCallback): void Obtains the MEID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -748,7 +748,7 @@ getMEID(slotId: number, callback: AsyncCallback): void Obtains the MEID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -777,7 +777,7 @@ getMEID(slotId?: number): Promise Obtains the MEID of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -803,7 +803,7 @@ let promise = radio.getMEID(slotId); promise.then(data => { console.log(`getMEID success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getMEID fail, promise: err->${JSON.stringify(err)}`); + console.error(`getMEID failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -813,7 +813,7 @@ getUniqueDeviceId(callback: AsyncCallback): void Obtains the unique device ID of the SIM card in a card slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -840,7 +840,7 @@ getUniqueDeviceId(slotId: number, callback: AsyncCallback): void Obtains the unique device ID of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -869,7 +869,7 @@ getUniqueDeviceId(slotId?: number): Promise Obtains the unique device ID of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -895,7 +895,7 @@ let promise = radio.getUniqueDeviceId(slotId); promise.then(data => { console.log(`getUniqueDeviceId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getUniqueDeviceId fail, promise: err->${JSON.stringify(err)}`); + console.error(`getUniqueDeviceId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -905,7 +905,7 @@ sendUpdateCellLocationRequest\(callback: AsyncCallback\): void Sends a cell location update request. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -929,7 +929,7 @@ sendUpdateCellLocationRequest\(slotId: number, callback: AsyncCallback\): Sends a cell location update request for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -955,7 +955,7 @@ sendUpdateCellLocationRequest\(slotId?: number): Promise Sends a cell location update request for the SIM card in the specified slot.This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -979,7 +979,7 @@ let promise = radio.sendUpdateCellLocationRequest(slotId); promise.then(data => { console.log(`sendUpdateCellLocationRequest success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`sendUpdateCellLocationRequest fail, promise: err->${JSON.stringify(err)}`); + console.log(`sendUpdateCellLocationRequest failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -989,7 +989,7 @@ getCellInformation(callback: AsyncCallback>): void Obtains cell information. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.LOCATION @@ -1016,7 +1016,7 @@ getCellInformation(slotId: number, callback: AsyncCallback\> Obtains cell information for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.LOCATION @@ -1071,7 +1071,7 @@ let promise = radio.getCellInformation(slotId); promise.then(data => { console.log(`getCellInformation success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getCellInformation fail, promise: err->${JSON.stringify(err)}`); + console.error(`getCellInformation failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1081,7 +1081,7 @@ setNetworkSelectionMode\(options: NetworkSelectionModeOptions, callback: AsyncCa Sets the network selection mode. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1120,7 +1120,7 @@ setNetworkSelectionMode\(options: NetworkSelectionModeOptions\): Promise Sets the network selection mode. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1157,7 +1157,7 @@ let promise = radio.setNetworkSelectionMode(networkSelectionModeOptions); promise.then(data => { console.log(`setNetworkSelectionMode success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setNetworkSelectionMode fail, promise: err->${JSON.stringify(err)}`); + console.log(`setNetworkSelectionMode failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1167,7 +1167,7 @@ getNetworkSearchInformation\(slotId: number, callback: AsyncCallback Obtains network search information for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1219,7 +1219,7 @@ let promise = radio.getNetworkSearchInformation(0); promise.then(data => { console.log(`getNetworkSearchInformation success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getNetworkSearchInformation fail, promise: err->${JSON.stringify(err)}`); + console.log(`getNetworkSearchInformation failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1229,7 +1229,7 @@ getNrOptionMode(callback: AsyncCallback): void Obtains the NR option mode. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1254,7 +1254,7 @@ getNrOptionMode(slotId: number, callback: AsyncCallback): void Obtains the NR option mode for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1281,7 +1281,7 @@ getNrOptionMode(slotId?: number): Promise Obtains the NR option mode for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1305,7 +1305,7 @@ let promise = radio.getNrOptionMode(slotId); promise.then(data => { console.log(`getNrOptionMode success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getNrOptionMode fail, promise: err->${JSON.stringify(err)}`); + console.error(`getNrOptionMode failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1315,7 +1315,7 @@ turnOnRadio(callback: AsyncCallback): void Turns on the radio function. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1342,7 +1342,7 @@ turnOnRadio(slotId: number, callback: AsyncCallback): void Turns on the radio function for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1371,7 +1371,7 @@ turnOnRadio(slotId?: number): Promise Turns on the radio function for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1397,7 +1397,7 @@ let promise = radio.turnOnRadio(slotId); promise.then(data => { console.log(`turnOnRadio success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`turnOnRadio fail, promise: err->${JSON.stringify(err)}`); + console.error(`turnOnRadio failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1407,7 +1407,7 @@ turnOffRadio(callback: AsyncCallback): void Turns off the radio function. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1434,7 +1434,7 @@ turnOffRadio(slotId: number, callback: AsyncCallback): void Turns off the radio function for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1463,7 +1463,7 @@ turnOffRadio(slotId?: number): Promise Turns off the radio function for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1489,7 +1489,7 @@ let promise = radio.turnOffRadio(slotId); promise.then(data => { console.log(`turnOffRadio success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`turnOffRadio fail, promise: err->${JSON.stringify(err)}`); + console.error(`turnOffRadio failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1499,7 +1499,7 @@ setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback Sets the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1527,7 +1527,7 @@ setPreferredNetwork(slotId: number, networkMode: PreferredNetworkMode): Promise< Sets the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1553,7 +1553,7 @@ let promise = radio.setPreferredNetwork(0, 1); promise.then(data => { console.log(`setPreferredNetwork success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setPreferredNetwork fail, promise: err->${JSON.stringify(err)}`); + console.log(`setPreferredNetwork failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1563,7 +1563,7 @@ getPreferredNetwork\(slotId: number, callback: AsyncCallback Obtains the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1615,7 +1615,7 @@ let promise = radio.getPreferredNetwork(0); promise.then(data => { console.log(`getPreferredNetwork success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getPreferredNetwork fail, promise: err->${JSON.stringify(err)}`); + console.log(`getPreferredNetwork failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1625,7 +1625,7 @@ getImsRegInfo(slotId: number, imsType: ImsServiceType, callback: AsyncCallback Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1679,7 +1679,7 @@ let promise = radio.getImsRegInfo(0, 1); promise.then(data => { console.log(`getImsRegInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getImsRegInfo fail, promise: err->${JSON.stringify(err)}`); + console.log(`getImsRegInfo failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1689,7 +1689,7 @@ on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Enables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1718,7 +1718,7 @@ off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback Disables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1857,7 +1857,7 @@ Enumerates network selection modes. Enumerates preferred network modes. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1902,7 +1902,7 @@ This is a system API. Defines the cell information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1918,7 +1918,7 @@ This is a system API. Defines the CDMA cell information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1934,7 +1934,7 @@ This is a system API. Defines the GSM cell information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1951,7 +1951,7 @@ This is a system API. Defines the LTE cell information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1970,7 +1970,7 @@ This is a system API. Defines the NR cell information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1987,7 +1987,7 @@ This is a system API. Defines the TD-SCDMA cell information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2004,7 +2004,7 @@ This is a system API. Defines the WCDMA cell information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2021,7 +2021,7 @@ This is a system API. Enumerates NR selection modes. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2036,7 +2036,7 @@ This is a system API. Defines the network search result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2049,7 +2049,7 @@ This is a system API. Defines the network information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2064,7 +2064,7 @@ This is a system API. Enumerates network information states. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2079,7 +2079,7 @@ This is a system API. Defines the network selection mode. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2094,7 +2094,7 @@ This is a system API. Enumerates IMS registration states. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2107,7 +2107,7 @@ This is a system API. Enumerates IMS registration technologies. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2122,7 +2122,7 @@ This is a system API. Defines the IMS registration information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2135,7 +2135,7 @@ This is a system API. Enumerates IMS service types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index bc42373a4589e4ab2fa4b268d1472a1c7bb60ad2..d2dcd1fdd0b4dd88d4a6917d260f052aa9198eca 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -24,9 +24,10 @@ Checks whether the screen is locked. This API uses an asynchronous callback to r **System capability**: SystemCapability.MiscServices.ScreenLock **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Returns **true** if the screen is locked; returns **false** otherwise.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if the screen is locked; returns **false** otherwise.| **Example** @@ -50,6 +51,7 @@ Checks whether the screen is locked. This API uses a promise to return the resul **System capability**: SystemCapability.MiscServices.ScreenLock **Return value** + | Type| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the result.| @@ -77,9 +79,10 @@ Checks whether a device is in secure mode. This API uses an asynchronous callbac **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Returns **true** if the device is in secure mode; returns **false** otherwise.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if the device is in secure mode; returns **false** otherwise.| **Example** @@ -103,6 +106,7 @@ Checks whether a device is in secure mode. This API uses a promise to return the **System capability**: SystemCapability.MiscServices.ScreenLock **Return value** + | Type| Description| | -------- | -------- | | Promise<boolean> | Promise used to return the result.| @@ -130,9 +134,10 @@ Unlocks the screen. This API uses an asynchronous callback to return the result. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation failed, an error message is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, an error message is returned.| **Example** @@ -156,6 +161,7 @@ Unlocks the screen. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock **Return value** + | Type| Description| | -------- | -------- | | Promise<void> | Promise used to return the result.| @@ -173,7 +179,7 @@ Unlocks the screen. This API uses a promise to return the result. ## screenlock.lockScreen9+ -lockScreen(callback: AsyncCallback<void>): void +lockScreen(callback: AsyncCallback<boolean>): void Locks the screen. This API uses an asynchronous callback to return the result. @@ -184,9 +190,10 @@ Locks the screen. 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. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation failed, an error message is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, an error message is returned.| **Example** @@ -202,7 +209,7 @@ Locks the screen. This API uses an asynchronous callback to return the result. ## screenlock.lockScreen9+ -lockScreen(): Promise<void> +lockScreen(): Promise<boolean> Locks the screen. This API uses a promise to return the result. @@ -238,6 +245,7 @@ Subscribes to screen lock status changes. **System API**: This is a system API and cannot be called by third-party applications. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.| @@ -262,6 +270,7 @@ Subscribes to screen lock status changes. **System API**: This is a system API and cannot be called by third-party applications. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.| @@ -285,6 +294,7 @@ Subscribes to screen lock status changes. **System API**: This is a system API and cannot be called by third-party applications. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type.
- **"screenlockEnabled"**: Screen lock is enabled.| @@ -310,6 +320,7 @@ Unsubscribes from screen lock status changes. **System API**: This is a system API and cannot be called by third-party applications. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.
- **"screenlockEnabled"**: Screen lock is enabled.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.| @@ -334,6 +345,7 @@ Sends an event to the screen lock service. This API uses an asynchronous callbac **System API**: This is a system API and cannot be called by third-party applications. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | String | Yes| Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.| @@ -359,12 +371,14 @@ Sends an event to the screen lock service. This API uses a promise to return the **System API**: This is a system API and cannot be called by third-party applications. **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | String | Yes| Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.| | parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.| **Return value** + | Type| Description| | -------- | -------- | | Promise\ | Promise used to return the result.| diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 94f5f3cb5e532f3e28f221addb164358589b1754..73ea5d3c915d2ba91c129ed8d7c8ed80efe8170d 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -99,7 +99,7 @@ Unsubscribes from events related to the screen state. **Example** ```js var callback = (data) => { - console.info('Unegister the callback for screen changes. Data: ' + JSON.stringify(data)) + console.info('Unregister the callback for screen changes. Data: ' + JSON.stringify(data)) }; screen.off("connect", callback); ``` diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 52ffdfc66d3fd0880602eccf574ec3b1b310904d..5b9107af6a142f762171272278e3ea543bb93b81 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -89,7 +89,6 @@ on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,callback:Callback<Lin Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. - **Required permissions**: ohos.permission.ACCELEROMETER (a system permission) **System capability**: SystemCapability.Sensors.Sensor @@ -1811,7 +1810,7 @@ sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions, callback: AsyncCallback<Array<number>>): void -Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses a callback to return the result. +Rotates a rotation vector so that it can represent the coordinate system in different ways. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor @@ -1876,16 +1875,16 @@ const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x getGeomagneticField(locationOptions: LocationOptions, timeMillis: number, callback: AsyncCallback<GeomagneticResponse>): void -Obtains the geomagnetic field of a geographic location. This API uses a callback to return the result. +Obtains the geomagnetic field of a geographic location. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor **Parameters** -| Name | Type | Mandatory | Description | -| --------------- | ---------------------------------------- | ---- | ----------------- | -| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | -| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| -| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- | ---------------------------------- | +| locationOptions | [LocationOptions](#locationoptions) | Yes | Geographic location. | +| timeMillis | number | Yes | Time for obtaining the magnetic declination, in milliseconds.| +| callback | AsyncCallback<[GeomagneticResponse](#geomagneticresponse)> | Yes | Callback used to return the geomagnetic field. | **Example** ```js @@ -1934,7 +1933,7 @@ Obtains the geomagnetic field of a geographic location. This API uses a promise getAltitude(seaPressure: number, currentPressure: number, callback: AsyncCallback<number>): void -Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses a callback to return the result. +Obtains the altitude at which the device is located based on the sea-level atmospheric pressure and the current atmospheric pressure. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor @@ -1996,7 +1995,7 @@ Obtains the altitude at which the device is located based on the sea-level atmos getGeomagneticDip(inclinationMatrix: Array<number>, callback: AsyncCallback<number>): void -Obtains the magnetic dip based on the inclination matrix. This API uses a callback to return the result. +Obtains the magnetic dip based on the inclination matrix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor @@ -2055,7 +2054,7 @@ Obtains the magnetic dip based on the inclination matrix. This API uses a promis getAngleModify(currentRotationMatrix: Array<number>, preRotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void -Obtains the angle change between two rotation matrices. This API uses a callback to return the result. +Obtains the angle change between two rotation matrices. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor @@ -2123,7 +2122,7 @@ Obtains the angle change between two rotation matrices. This API uses a promise createRotationMatrix(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void -Converts a rotation vector into a rotation matrix. This API uses a callback to return the result. +Converts a rotation vector into a rotation matrix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor @@ -2189,7 +2188,7 @@ Converts a rotation vector into a rotation matrix. This API uses a promise to re createQuaternion(rotationVector: Array<number>, callback: AsyncCallback<Array<number>>): void -Converts a rotation vector into a quaternion. This API uses a callback to return the result. +Converts a rotation vector into a quaternion. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor @@ -2255,7 +2254,7 @@ Converts a rotation vector into a quaternion. This API uses a promise to return getDirection(rotationMatrix: Array<number>, callback: AsyncCallback<Array<number>>): void -Obtains the device direction based on the rotation matrix. This API uses a callback to return the result. +Obtains the device direction based on the rotation matrix. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor @@ -2322,7 +2321,7 @@ Obtains the device direction based on the rotation matrix. This API uses a promi createRotationMatrix(gravity: Array<number>, geomagnetic: Array<number>, callback: AsyncCallback<RotationMatrixResponse>): void -Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses a callback to return the result. +Creates a rotation matrix based on the gravity vector and geomagnetic vector. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Sensors.Sensor @@ -2385,6 +2384,118 @@ Creates a rotation matrix based on the gravity vector and geomagnetic vector. Th }) ``` +## sensor.getSensorLists9+ + + getSensorLists(callback: AsyncCallback): void + +Obtains information about all sensors on the device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ---------------- | +| callback | AsyncCallback | Yes | Callback used to return the sensor list.| + +**Example** + +```js +sensor.getSensorList((error, data) => { + if (error) { + console.error('getSensorList failed'); + } else { + console.info("getSensorList callback in" + data.length); + for (var i = 0; i < data.length; i++) { + console.info("getSensorList " + JSON.stringify(data[i])); + } + } +}); +``` + +## sensor.getSensorLists9+ + + getSensorLists(): Promise< Array<Sensor>> + +Obtains information about all sensors on the device. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Return value** + +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------- | ---- | ---------------- | +| promise | Promise | Yes | Promise used to return the sensor list.| + +**Example** + +```js +sensor.getSensorList().then((data) => { + console.info("getSensorList promise in" + data.length); + for (var i = 0; i < data.length; i++) { + console.info("getSensorList " + JSON.stringify(data[i])); + } +}, (error)=>{ + console.error('getSensorList failed'); +}); +``` + +## sensor.getSingleSensor9+ + +getSingleSensor(type: SensorType, callback: AsyncCallback<sensor>): void + +Obtains information about the sensor of a specific type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ---------------- | +| type | SensorType | Yes | Sensor type. | +| callback | AsyncCallback<[Sensor](#sensor)> | Yes | Callback used to return the sensor information.| + +**Example** + +```js + sensor.getSingleSensor(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, (error, data) => { + if (error) { + console.error('getSingleSensor failed'); + } else { + console.info("getSingleSensor " + JSON.stringify(data)); + } +}); +``` + +## sensor.getSingleSensor9+ + + getSingleSensor(type: SensorType,): Promise<Sensor> + +Obtains information about the sensor of a specific type. This API uses a promise to return the result. + +**System capability**: SystemCapability.Sensors.Sensor + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ------------ | +| type | SensorType | Yes | Sensor type.| + +**Return value** + +| Name | Type | Mandatory| Description | +| ------- | -------------------------------- | ---- | ---------------- | +| promise | Promise<[Sensor](#sensor)> | Yes | Promise used to return the sensor information.| + +**Example** + +```js +sensor.getSingleSensor(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER).then((data) => { + console.info("getSingleSensor " + JSON.stringify(data)); +}, (error)=>{ + console.error('getSingleSensor failed'); +}); +``` ## SensorType @@ -2426,10 +2537,26 @@ Describes the timestamp of the sensor data. **System capability**: SystemCapability.Sensors.Sensor -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ------------ | -| timestamp | number | Yes | Yes | Timestamp when the sensor reports data.| +| Name | Type| Readable| Writable| Description | +| --------- | -------- | ---- | ---- | ------------------------ | +| timestamp | number | Yes | Yes | Timestamp when the sensor reports data.| + +## Sensor + +Describes the sensor information. + +**System capability**: SystemCapability.Sensors.Sensor +| Name | Type| Description | +| --------------- | -------- | ---------------------- | +| sensorName | string | Sensor name. | +| venderName | string | Vendor of the sensor. | +| firmwareVersion | string | Firmware version of the sensor. | +| hardwareVersion | string | Hardware version of the sensor. | +| sensorTypeId | number | Sensor type ID. | +| maxRange | number | Maximum measurement range of the sensor.| +| precision | number | Precision of the sensor. | +| power | number | Power supply of the sensor. | ## AccelerometerResponse diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md index 5a521ffca5fcefb393551effd6b02bc69a9d64aa..7ed184b2a61aaaf781a37b9137e8f510a2ffbc2f 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -724,15 +724,17 @@ Disconnects this ability from the Service ability. This API uses a promise to re startAbilityByCall(want: Want): Promise<Caller>; -Starts an ability in the background and obtains the caller interface for communication. +Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, including the ability name, module name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| **Return value** @@ -744,16 +746,38 @@ Starts an ability in the background and obtains the caller interface for communi ```js let caller = undefined; - this.context.startAbilityByCall({ + + // Start an ability in the background by not passing parameters. + var wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", abilityName: "MainAbility", deviceId: "" - }).then((obj) => { - caller = obj; - console.log('Caller GetCaller Get ' + caller); - }).catch((e) => { - console.log('Caller GetCaller error ' + e); - }); + }; + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + caller = obj; + console.log('GetCaller Success'); + }).catch((error) => { + console.log(`GetCaller failed with ${error}`); + }); + + // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. + var wantForeground = { + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "", + parameters: { + "ohos.aafwk.param.callAbilityToForeground": true + } + }; + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + caller = obj; + console.log('GetCaller success'); + }).catch((error) => { + console.log(`GetCaller failed with ${error}`); + }); ``` diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index f9475d2e7d76b6ccf20f6b0f32d01969fdccfbbb..a2d761225c3169bd6d9f5a7603232d4050c0342b 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -511,7 +511,7 @@ getSimAccountInfo(slotId: number, callback: AsyncCallback): voi Obtains account information of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -539,7 +539,7 @@ getSimAccountInfo(slotId: number): Promise Obtains account information of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -574,7 +574,7 @@ getActiveSimAccountInfoList(callback: AsyncCallback>): vo Obtains the account information list of the active SIM card. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -601,7 +601,7 @@ getActiveSimAccountInfoList(): Promise>; Obtains the account information list of the active SIM card. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -630,7 +630,7 @@ setDefaultVoiceSlotId(slotId: number, callback: AsyncCallback): void Sets the default slot ID of the SIM card that provides voice services. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -658,7 +658,7 @@ setDefaultVoiceSlotId(slotId: number): Promise\ Sets the default slot ID of the SIM card that provides voice services. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -693,7 +693,7 @@ setShowName\(slotId: number, name: string,callback: AsyncCallback\): void Sets a display name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -722,7 +722,7 @@ setShowName\(slotId: number, name: string\): Promise\ Sets a display name for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -759,7 +759,7 @@ getShowName(slotId: number, callback: AsyncCallback): void Obtains the name of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -787,7 +787,7 @@ getShowName(slotId: number): Promise Obtains the name of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -822,7 +822,7 @@ setShowNumber\(slotId: number, number: string,callback: AsyncCallback\): Sets a display number for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -852,7 +852,7 @@ setShowNumber\(slotId: number,number: string\): Promise\ Sets a display number for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -889,7 +889,7 @@ getShowNumber(slotId: number,callback: AsyncCallback): void Obtains the display number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -917,7 +917,7 @@ getShowNumber(slotId: number): Promise Obtains the display number of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -952,7 +952,7 @@ activateSim(slotId: number, callback: AsyncCallback): void Activates the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -980,7 +980,7 @@ activateSim(slotId: number): Promise\ Activates the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1015,7 +1015,7 @@ deactivateSim(slotId: number, callback: AsyncCallback): void Deactivates the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1043,7 +1043,7 @@ deactivateSim(slotId: number): Promise\ Deactivates the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1078,7 +1078,7 @@ setLockState(slotId: number, options: LockInfo, callback: AsyncCallback Sets the lock status of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1153,7 +1153,7 @@ getLockState(slotId: number, lockType: LockType, callback: AsyncCallback Obtains the lock status of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -1214,7 +1214,7 @@ alterPin(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback Changes the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1244,7 +1244,7 @@ alterPin(slotId: number, newPin: string, oldPin: string): Promise Unlocks the PIN of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1415,7 +1415,7 @@ unlockPuk(slotId: number,newPin: string,puk: string ,callback: AsyncCallback Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1553,7 +1553,7 @@ unlockPuk2(slotId: number, newPin2: string, puk2: string, callback: AsyncCallbac Unlocks PUK 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1585,7 +1585,7 @@ unlockPuk2(slotId: number, newPin2: string, puk2: string): Promise<LockStatus Unlocks PUK 2 of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1644,7 +1644,7 @@ getSimIccId(slotId: number, callback: AsyncCallback): void Obtains the IC card identity (ICCID) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1672,7 +1672,7 @@ getSimIccId(slotId: number): Promise Obtains the ICCID of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1707,7 +1707,7 @@ getVoiceMailIdentifier(slotId: number, callback: AsyncCallback): void Obtains the voice mailbox alpha identifier of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1735,7 +1735,7 @@ getVoiceMailIdentifier(slotId: number): Promise Obtains the voice mailbox alpha identifier of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1770,7 +1770,7 @@ getVoiceMailNumber(slotId: number, callback: AsyncCallback): void Obtains the voice mailbox number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1798,7 +1798,7 @@ getVoiceMailNumber(slotId: number): Promise Obtains the voice mailbox number of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1833,7 +1833,7 @@ setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string, callback: Sets voice mailbox information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1863,7 +1863,7 @@ setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string): Promise< Sets voice mailbox information for the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -1900,7 +1900,7 @@ getSimTelephoneNumber(slotId: number, callback: AsyncCallback): void Obtains the mobile subscriber ISDN number (MSISDN) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1928,7 +1928,7 @@ getSimTelephoneNumber(slotId: number): Promise Obtains the MSISDN of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1963,7 +1963,7 @@ getSimGid1(slotId: number, callback: AsyncCallback): void Obtains the group identifier level 1 (GID1) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -1991,7 +1991,7 @@ getSimGid1(slotId: number): Promise Obtains the GID1 of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -2026,7 +2026,7 @@ getIMSI(slotId: number, callback: AsyncCallback): void Obtains the international mobile subscriber identity (IMSI) of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -2054,7 +2054,7 @@ getIMSI(slotId: number): Promise Obtains the IMSI of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -2089,7 +2089,7 @@ getOperatorConfigs(slotId: number, callback: AsyncCallback> Obtains the carrier configuration of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE @@ -2152,7 +2152,7 @@ queryIccDiallingNumbers(slotId: number, type: ContactType, callback: AsyncCallba Queries contact numbers of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.READ_CONTACTS @@ -2181,7 +2181,7 @@ queryIccDiallingNumbers(slotId: number, type: ContactType): Promise): vo Sends an envelope command to the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2483,7 +2483,7 @@ sendEnvelopeCmd(slotId: number, cmd: string): Promise Sends an envelope command to the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2519,7 +2519,7 @@ sendTerminalResponseCmd(slotId: number, cmd: string, callback: AsyncCallback Sends a terminal response command to the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -2584,7 +2584,7 @@ unlockSimLock(slotId: number, lockInfo: PersoLockInfo, callback: AsyncCallback): void Obtains the opkey of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2683,7 +2683,7 @@ getOpKey(slotId: number): Promise Obtains the opkey of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2716,7 +2716,7 @@ getOpName(slotId: number, callback: AsyncCallback): void Obtains the OpName of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2742,7 +2742,7 @@ getOpName(slotId: number): Promise Obtains the OpName of the SIM card in the specified slot. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2807,7 +2807,7 @@ Enumerates SIM card types. Enumerates lock types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2820,7 +2820,7 @@ This is a system API. Enumerates lock states. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2833,7 +2833,7 @@ This is a system API. Enumerates personalized lock types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2854,7 +2854,7 @@ This is a system API. Defines the lock status response. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2867,7 +2867,7 @@ This is a system API. Defines the lock information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2881,7 +2881,7 @@ This is a system API. Defines the personalized lock information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2894,7 +2894,7 @@ This is a system API. Defines the ICC account information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2912,7 +2912,7 @@ This is a system API. Defines the carrier configuration. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2925,7 +2925,7 @@ This is a system API. Defines the contact number information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService @@ -2940,7 +2940,7 @@ This is a system API. Enumerates contact types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.CoreService diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 9039fb774527e9ed6bbd43c95b0996afdc94780d..5443e18d1bd7e01ca1bbe74f62fdd9cce061e343 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -71,7 +71,7 @@ let promise = sms.createMessage(pdu, specification); promise.then(data => { console.log(`createMessage success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`createMessage fail, promise: err->${JSON.stringify(err)}`); + console.error(`createMessage failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -154,7 +154,7 @@ let promise = sms.getDefaultSmsSlotId(); promise.then(data => { console.log(`getDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getDefaultSmsSlotId fail, promise: err->${JSON.stringify(err)}`); + console.error(`getDefaultSmsSlotId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -164,7 +164,7 @@ setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback<void>\): void Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -192,7 +192,7 @@ setDefaultSmsSlotId\(slotId: number\): Promise<void> Sets the default slot of the SIM card used to send SMS messages. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE @@ -217,7 +217,7 @@ let promise = sms.setDefaultSmsSlotId(0); promise.then(data => { console.log(`setDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`setDefaultSmsSlotId fail, promise: err->${JSON.stringify(err)}`); + console.error(`setDefaultSmsSlotId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -227,7 +227,7 @@ setSmscAddr\(slotId: number, smscAddr: string, callback: AsyncCallback\): Sets the short message service center (SMSC) address. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission) @@ -258,7 +258,7 @@ setSmscAddr\(slotId: number, smscAddr: string\): Promise\ Sets the SMSC address. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SET_TELEPHONY_STATE (a system permission) @@ -286,7 +286,7 @@ let promise = sms.setSmscAddr(slotId, smscAddr); promise.then(data => { console.log(`setSmscAddr success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`setSmscAddr fail, promise: err->${JSON.stringify(err)}`); + console.error(`setSmscAddr failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -297,7 +297,7 @@ getSmscAddr\(slotId: number, callback: AsyncCallback\): void Obtains the SMSC address. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission) @@ -326,7 +326,7 @@ getSmscAddr\(slotId: number\): Promise Obtains the SMSC address. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.GET_TELEPHONY_STATE (a system permission) @@ -352,7 +352,7 @@ let promise = sms.getSmscAddr(slotId); promise.then(data => { console.log(`getSmscAddr success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getSmscAddr fail, promise: err->${JSON.stringify(err)}`); + console.error(`getSmscAddr failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -381,7 +381,7 @@ splitMessage(content: string, callback: AsyncCallback>): void Splits an SMS message into multiple segments. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SEND_MESSAGES @@ -410,7 +410,7 @@ splitMessage(content: string): Promise> Splits an SMS message into multiple segments. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.SEND_MESSAGES @@ -436,7 +436,7 @@ let promise = sms.splitMessage(content); promise.then(data => { console.log(`splitMessage success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`splitMessage fail, promise: err->${JSON.stringify(err)}`); + console.error(`splitMessage failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -446,7 +446,7 @@ addSimMessage(options: SimMessageOptions, callback: AsyncCallback): void Adds a SIM message. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -480,7 +480,7 @@ addSimMessage(options: SimMessageOptions): Promise Adds a SIM message. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -511,7 +511,7 @@ let promise = sms.addSimMessage(simMessageOptions); promise.then(data => { console.log(`addSimMessage success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`addSimMessage fail, promise: err->${JSON.stringify(err)}`); + console.error(`addSimMessage failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -521,7 +521,7 @@ delSimMessage(slotId: number, msgIndex: number, callback: AsyncCallback): Deletes a SIM message. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -552,7 +552,7 @@ delSimMessage(slotId: number, msgIndex: number): Promise Deletes a SIM message. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -580,7 +580,7 @@ let promise = sms.delSimMessage(slotId, msgIndex); promise.then(data => { console.log(`delSimMessage success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`delSimMessage fail, promise: err->${JSON.stringify(err)}`); + console.error(`delSimMessage failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -590,7 +590,7 @@ updateSimMessage(options: UpdateSimMessageOptions, callback: AsyncCallback Updates a SIM message. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES @@ -657,7 +657,7 @@ let promise = sms.updateSimMessage(updateSimMessageOptions); promise.then(data => { console.log(`updateSimMessage success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`updateSimMessage fail, promise: err->${JSON.stringify(err)}`); + console.error(`updateSimMessage failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -667,7 +667,7 @@ getAllSimMessages(slotId: number, callback: AsyncCallback> Obtains all SIM card messages. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.RECEIVE_SMS @@ -722,7 +722,7 @@ let promise = sms.getAllSimMessages(slotId); promise.then(data => { console.log(`getAllSimMessages success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getAllSimMessages fail, promise: err->${JSON.stringify(err)}`); + console.error(`getAllSimMessages failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -732,7 +732,7 @@ setCBConfig(options: CBConfigOptions, callback: AsyncCallback): void Sets the cell broadcast configuration. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.RECEIVE_SMS @@ -766,7 +766,7 @@ setCBConfig(options: CBConfigOptions): Promise Sets the cell broadcast configuration. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **Required permission**: ohos.permission.RECEIVE_SMS @@ -797,7 +797,7 @@ let promise = sms.setCBConfig(cbConfigOptions); promise.then(data => console.log(`setCBConfig success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`setCBConfig fail, promise: err->${JSON.stringify(err)}`); + console.error(`setCBConfig failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -807,7 +807,7 @@ getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean, callback Obtains SMS message segment information. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -836,7 +836,7 @@ getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean): Promise Obtains SMS message segment information. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -862,7 +862,7 @@ let promise = sms.getSmsSegmentsInfo(slotId, "message", false); promise.then(data => console.log(`getSmsSegmentsInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getSmsSegmentsInfo fail, promise: err->${JSON.stringify(err)}`); + console.error(`getSmsSegmentsInfo failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -872,7 +872,7 @@ isImsSmsSupported(callback: AsyncCallback): void Checks whether SMS is supported on IMS. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -897,7 +897,7 @@ isImsSmsSupported(): Promise Checks whether SMS is supported on IMS. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -914,7 +914,7 @@ let promise = sms.isImsSmsSupported(); promise.then(data => { console.log(`isImsSmsSupported success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`isImsSmsSupported fail, promise: err->${JSON.stringify(err)}`); + console.error(`isImsSmsSupported failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -924,7 +924,7 @@ getImsShortMessageFormat(callback: AsyncCallback): void Obtains the SMS format supported by the IMS. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -949,7 +949,7 @@ getImsShortMessageFormat(): Promise Obtains the SMS format supported by the IMS. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -966,7 +966,7 @@ let promise = sms.getImsShortMessageFormat(); promise.then(data => { console.log(`getImsShortMessageFormat success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`getImsShortMessageFormat fail, promise: err->${JSON.stringify(err)}`); + console.error(`getImsShortMessageFormat failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -976,7 +976,7 @@ decodeMms(mmsFilePathName: string | Array, callback: AsyncCallback): Promise Decodes MMS messages. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1027,7 +1027,7 @@ let promise = sms.getSmscAddr(mmsFilePathName); promise.then(data => { console.log(`decodeMms success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`decodeMms fail, promise: err->${JSON.stringify(err)}`); + console.error(`decodeMms failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1037,7 +1037,7 @@ encodeMms(mms: MmsInformation, callback: AsyncCallback>): void Encodes MMS messages. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1072,7 +1072,7 @@ encodeMms(mms: MmsInformation): Promise> Encodes MMS messages. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1104,7 +1104,7 @@ let promise = sms.encodeMms(mmsInformation); promise.then(data => { console.log(`encodeMms success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.error(`encodeMms fail, promise: err->${JSON.stringify(err)}`); + console.error(`encodeMms failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1203,7 +1203,7 @@ Enumerates SMS message sending results. Defines the MMS message information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1217,7 +1217,7 @@ This is a system API. Defines an MMS message sending request. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1243,7 +1243,7 @@ This is a system API. Defines the MMS message sending configuration. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1258,7 +1258,7 @@ This is a system API. Defines an MMS notification index. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1279,7 +1279,7 @@ This is a system API. Defines an MMS confirmation index. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1293,7 +1293,7 @@ This is a system API. Defines the MMS message retrieval configuration. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1318,7 +1318,7 @@ This is a system API. Defines the original MMS message reading index. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1336,7 +1336,7 @@ This is a system API. Defines the MMS message reading index. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1354,7 +1354,7 @@ This is a system API. Defines the attachment of an MMS message. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1375,7 +1375,7 @@ This is a system API. Defines an MMSC address. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1388,7 +1388,7 @@ This is a system API. Enumerates message types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1408,7 +1408,7 @@ This is a system API. Enumerates MMS message priorities. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1422,7 +1422,7 @@ This is a system API. Enumerates MMS versions. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1437,7 +1437,7 @@ This is a system API. Enumerates MMS character sets. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1462,7 +1462,7 @@ This is a system API. Enumerates disposition types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1476,7 +1476,7 @@ This is a system API. Enumerates report types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1489,7 +1489,7 @@ This is a system API. Defines the cell broadcast configuration options. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1505,7 +1505,7 @@ This is a system API. Defines the SIM message status. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1521,7 +1521,7 @@ This is a system API. Enumerates RAN types. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1534,7 +1534,7 @@ This is a system API. Enumerates SMS encoding schemes. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1549,7 +1549,7 @@ This is a system API. Defines the SIM message options. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1564,7 +1564,7 @@ This is a system API. Defines the updating SIM message options. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1580,7 +1580,7 @@ This is a system API. Defines a SIM message. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1594,7 +1594,7 @@ This is a system API. Defines an MMS message delivery index. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1610,7 +1610,7 @@ This is a system API. Defines an MMS response index. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms @@ -1625,7 +1625,7 @@ This is a system API. Defines the SMS message segment information. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Telephony.SmsMms diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index b590efb7ca3455c95c3d217b86e741848c5ac547..77dd0bc0560d11837a5cfbb68f38fd3f39075310 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1041,7 +1041,7 @@ promise1.then(() => { console.log('connect success'); let promise2 = tcp.getRemoteAddress(); promise2.then(() => { - console.log('getRemoteAddress success:' + JSON.stringify(data)); + console.log('getRemoteAddress success'); }).catch(err => { console.log('getRemoteAddressfail'); }); @@ -1120,7 +1120,7 @@ promise.then(() => { console.log('connect success'); let promise1 = tcp.getState(); promise1.then(() => { - console.log('getState success:' + JSON.stringify(data)); + console.log('getState success'); }).catch(err => { console.log('getState fail'); }); diff --git a/en/application-dev/reference/apis/js-apis-system-sensor.md b/en/application-dev/reference/apis/js-apis-system-sensor.md index a551dea9a8f79c5d153649ce69dc912f93ddd4b6..7df5f6675bb53168935ada36ca1d0675e49da978 100644 --- a/en/application-dev/reference/apis/js-apis-system-sensor.md +++ b/en/application-dev/reference/apis/js-apis-system-sensor.md @@ -21,9 +21,9 @@ import sensor from '@system.sensor'; ## Error Codes -| Error Code | Description | -| ---- | -------------- | -| 900 | The current device does not support the corresponding sensor.| +| Error Code | Description | +| ---------- | ---------------------------------------- | +| 900 | The current device does not support the corresponding sensor. | ## sensor.subscribeAccelerometer @@ -37,19 +37,19 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the acceleration sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ---------------------------------------- | +| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | +| success | Function | Yes | Called when the acceleration sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | ------- | -| x | number | Acceleration on the x-axis.| -| y | number | Acceleration on the y-axis.| -| z | number | Acceleration on the z-axis.| +| Name | Type | Description | +| ---- | ------ | --------------------------- | +| x | number | Acceleration on the x-axis. | +| y | number | Acceleration on the y-axis. | +| z | number | Acceleration on the z-axis. | **Example** @@ -97,16 +97,16 @@ Subscribes to data changes of the compass sensor. If this API is called multiple **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | --------------- | -| success | Function | Yes | Called when the compass sensor data changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the compass sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ---------- | -| direction | number | Direction of the device, in degrees.| +| Name | Type | Description | +| --------- | ------ | ------------------------------------ | +| direction | number | Direction of the device, in degrees. | **Example** @@ -149,16 +149,16 @@ Subscribes to data changes of the proximity sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ----------------- | -| success | Function | Yes | Called when the proximity sensor data changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the proximity sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | --------------------- | -| distance | number | Distance between a visible object and the device screen.| +| Name | Type | Description | +| -------- | ------ | ---------------------------------------- | +| distance | number | Distance between a visible object and the device screen. | **Example** @@ -201,16 +201,16 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | --------------- | -| success | Function | Yes | Called when the ambient light sensor data changes| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the ambient light sensor data changes | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ------------ | -| intensity | number | Light intensity, in lux.| +| Name | Type | Description | +| --------- | ------ | ------------------------ | +| intensity | number | Light intensity, in lux. | **Example** @@ -255,16 +255,16 @@ Subscribes to data changes of the step counter sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ---------------- | -| success | Function | Yes | Called when the step counter sensor data changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the step counter sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------ | --------------------- | -| steps | number | Number of counted steps after the sensor is restarted.
| +| Name | Type | Description | +| ----- | ------ | ---------------------------------------- | +| steps | number | Number of counted steps after the sensor is restarted.
| **Example** @@ -302,7 +302,7 @@ sensor.unsubscribeStepCounter(); ## sensor.subscribeBarometer -subcribeBarometer(Object): void +subscribeBarometer(Object): void Subscribes to data changes of the barometer sensor. If this API is called multiple times for the same application, the last call takes effect. @@ -310,16 +310,16 @@ Subscribes to data changes of the barometer sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ---------------- | -| success | Function | Yes | Called when the barometer sensor data changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the barometer sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | ----------- | -| pressure | number | Pressure, in pascal.| +| Name | Type | Description | +| -------- | ------ | -------------------- | +| pressure | number | Pressure, in pascal. | **Example** @@ -366,16 +366,16 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ------------------------- | -| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | ---------------------------------------- | +| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ---- | -| heartRate | number | Heart rate.| +| Name | Type | Description | +| --------- | ------ | ----------- | +| heartRate | number | Heart rate. | **Example** @@ -421,16 +421,16 @@ Subscribes to changes of the wearing state of a wearable device. If this API is **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | ---- | ------------- | -| success | Function | Yes | Called when the wearing state changes.| -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | --------- | -------------------------------------- | +| success | Function | Yes | Called when the wearing state changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------ | -| value | boolean | Whether the wearable device is worn.| +| Name | Type | Description | +| ----- | ------- | ------------------------------------ | +| value | boolean | Whether the wearable device is worn. | **Example** @@ -473,17 +473,17 @@ Obtains the wearing state of a wearable device. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ------------ | -| success | Function | No | Callback upon success.| -| fail | Function | No | Callback upon failure.| -| complete | Function | No | Called when the execution is complete.| +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | -------------------------------------- | +| success | Function | No | Callback upon success. | +| fail | Function | No | Callback upon failure. | +| complete | Function | No | Called when the execution is complete. | Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------ | -| value | boolean | Whether the wearable device is worn.| +| Name | Type | Description | +| ----- | ------- | ------------------------------------ | +| value | boolean | Whether the wearable device is worn. | **Example** @@ -510,18 +510,18 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the device orientation sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | +| success | Function | Yes | Called when the device orientation sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | +| Name | Type | Description | | ----- | ------ | ---------------------------------------- | -| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth.| -| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth.| -| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth.| +| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth. | +| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth. | +| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth. | **Example** @@ -571,19 +571,19 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | ---- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| -| success | Function | Yes | Called when the gyroscope sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | +| success | Function | Yes | Called when the gyroscope sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | --------- | -| x | number | Rotation angular velocity of the X axis.| -| y | number | Rotation angular velocity of the Y axis.| -| z | number | Rotation angular velocity of the Z axis.| +| Name | Type | Description | +| ---- | ------ | ---------------------------------------- | +| x | number | Rotation angular velocity of the X axis. | +| y | number | Rotation angular velocity of the Y axis. | +| z | number | Rotation angular velocity of the Z axis. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md index 5ed3760a0cf3664cc6991a73489dd7f53ab9d83b..e6073f2dca4b101454fbdf14dd9bdd406a8eaade 100644 --- a/en/application-dev/reference/apis/js-apis-tagSession.md +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -1,9 +1,8 @@ -# Standard NFC Tag Session +# NFC Tag Session 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** @@ -18,7 +17,7 @@ Provides common APIs for establishing connections and transferring data. **tagSe A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. -The specific method varies with the NFC tag technology in use. For details, see [nfcTag](js-apis-nfcTag.md). +The specific API varies with the NFC tag technology in use. For details, see [NFC Tags](js-apis-nfcTag.md). ### tagSession.connectTag @@ -26,7 +25,7 @@ connectTag(): boolean; Connects to this tag. -Call this method to set up a connection before reading data from or writing data to a 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 @@ -95,7 +94,7 @@ Checks whether the tag is connected. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an Object given by nfc service when tag is dispatched. +// tagInfo is an object given by the NFC service when a tag is dispatched. let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); console.log("isTagConnected:" +isTagConnected); ``` diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index 60fd45f98209c718374e4a2633b074a531aa719c..faeb4f766d6c1417728f540fcab71551ee688abf 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -47,7 +47,7 @@ A constructor used to create a URI instance. **Example** ```js -var mm = 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; +let mm = 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; new uri.URI(mm); // Output 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; ``` ```js diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 55694ec1cb024a25affa93feca40b2a73ef38234..c060118f7e466da51f2ee5b7fdd6ad20f7e256ca 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -26,16 +26,16 @@ Creates a **URLSearchParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| 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| +| 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** ```js -var objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); -var objectParams1 = new Url.URLSearchParams({"fod" : '1' , "bard" : '2'}); -var objectParams2 = new Url.URLSearchParams('?fod=1&bard=2'); -var urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); -var params = new Url.URLSearchParams(urlObject.search); +let objectParams = new Url.URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); +let objectParams1 = new Url.URLSearchParams({"fod" : '1' , "bard" : '2'}); +let objectParams2 = new Url.URLSearchParams('?fod=1&bard=2'); +let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); +let params = new Url.URLSearchParams(urlObject.search); ``` @@ -133,7 +133,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th **Example** ```js -var searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2"); +let searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2"); for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs console.log(pair[0]+ ', '+ pair[1]); } @@ -197,9 +197,9 @@ Obtains the value of the first key-value pair based on the specified key. **Example** ```js -var paramsOject = new Url.URLSearchParams('name=Jonathan&age=18'); -var name = paramsOject.get("name"); // is the string "Jonathan" -var age = parseInt(paramsOject.get("age"), 10); // is the number 18 +let paramsObject = new Url.URLSearchParams('name=Jonathan&age=18'); +let name = paramsObject.get("name"); // is the string "Jonathan" +let age = parseInt(paramsObject.get("age"), 10); // is the number 18 ``` @@ -267,7 +267,7 @@ Sorts all key-value pairs contained in this object based on the Unicode code poi **Example** ```js -var searchParamsObject = new Url.URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object +let searchParamsObject = new Url.URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object searchParamsObject.sort(); // Sort the key/value pairs console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4 ``` @@ -290,7 +290,7 @@ Obtains an ES6 iterator that contains the keys of all the key-value pairs. **Example** ```js -var searchParamsObject = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing +let searchParamsObject = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing for (var key of searchParamsObject .keys()) { // Output key-value pairs console.log(key); } @@ -314,8 +314,8 @@ Obtains an ES6 iterator that contains the values of all the key-value pairs. **Example** ```js -var searchParams = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing -for (var value of searchParams.values()) { +let searchParams = new Url.URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing +for (var value of searchParams.values()) { console.log(value); } ``` @@ -339,7 +339,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ```js const paramsObject = new Url.URLSearchParams('fod=bay&edg=bap'); -for (const [name, value] of paramsObject) { +for (const [name, value] of paramsObject) { console.log(name, value); } ``` @@ -409,11 +409,11 @@ Creates a URL. **Example** ```js -var mm = 'http://username:password@host:8080'; -var a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/'; -var b = new Url.URL(mm); // Output 'http://username:password@host:8080/'; +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'; -var c = 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 diff --git a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md new file mode 100644 index 0000000000000000000000000000000000000000..60690327946699362eb5b86deaaae3b438897e3e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -0,0 +1,81 @@ +# Facial Authentication + +The **userIAM.faceAuth** module provides APIs for face enrollment. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. + +## Modules to Import + +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; +``` + +## FaceAuthManager + +Provides APIs for facial authentication management. + +### constructor + +constructor() + +A constructor used to create a **FaceAuthManager** object. + +**System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth + +**Return value** + +| Type | Description | +| ---------------------- | -------------------- | +| [FaceAuthManager](#faceauthmanager) | **FaceAuthManager** object.| + +**Example** + + ```js + import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; + + let faceAuthManager = new userIAM_faceAuth.FaceAuthManager() + ``` + +### setSurfaceId + +setSurfaceId(surfaceId: string): ResultCode; + +Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. + +**System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ---------------------------------- | ---- | -------------------------- | +| surfaceId | string | Yes | ID of the surface held by the [XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| + +**Return value** + +| Type | Description | +| ---------- | ------------------------------------------------------------ | +| [ResultCode](#resultcode) | Operation result code.| + +**Example** + + ```js + import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; + + let faceAuthManager = new userIAM_faceAuth.FaceAuthManager() + faceAuthManager.setSurfaceId("0"); + ``` + +## ResultCode + + Enumerates the operation result codes. + + **System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth + +| Name | Default Value| Description | +| ----------------------- | ------ | -------------------- | +| SUCCESS | 0 | The operation is successful. | +| FAIL | 1 | The operation fails. | diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index d98f43faaf7bc2a575cfa80907a776d9436bfbff..a43b77bcf631b9ad1c2882a841af545fbe9669fd 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -119,8 +119,6 @@ constructor() A constructor used to create an **authenticator** object. -**Required permissions**: ohos.permission.ACCESS_BIOMETRIC - **System capability**: SystemCapability.UserIAM.UserAuth.Core **Return value** @@ -279,7 +277,8 @@ Cancels an authentication. // contextId can be obtained using auth(). In this example, it is defined here. let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); - let cancelCode = auth.cancel(contextId); + let auth = new userIAM_userAuth.UserAuth(); + let cancelCode = auth.cancelAuth(contextId); if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { console.info("cancel auth success"); } else { @@ -492,11 +491,10 @@ getAuthenticator(): Authenticator Obtains an **Authenticator** object for user authentication. -**Required permissions**: ohos.permission.ACCESS_BIOMETRIC - **System capability**: SystemCapability.UserIAM.UserAuth.Core **Return value** + | Type | Description | | ----------------------------------------- | ------------ | | [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| @@ -516,7 +514,7 @@ Provides methods to manage an **Authenticator** object. ### execute(deprecated) -execute(type: string, level: string, callback: AsyncCallback<number>): void +execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void > **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). @@ -531,8 +529,8 @@ Performs user authentication. This API uses asynchronous callback to return the | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| -| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| | callback | AsyncCallback<number> | No | Callback used to return the result. | Parameters returned in callback @@ -543,19 +541,20 @@ Performs user authentication. This API uses asynchronous callback to return the **Example** ```js - authenticator.execute("FACE_ONLY", "S2", (code)=>{ - if (code == userIAM_userAuth.AuthenticationResult.SUCCESS) { + let authenticator = userIAM_userAuth.getAuthenticator(); + authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ + if (code === userIAM_userAuth.ResultCode.SUCCESS) { console.info("auth success"); return; } console.error("auth fail, code = " + code); - }) + }); ``` ### execute(deprecated) -execute(type:string, level:string): Promise<number> +execute(type:AuthType, level:SecureLevel): Promise<number> > **NOTE**
> This API is not longer maintained since API version 8. You are advised to use [auth](#auth8). @@ -567,26 +566,28 @@ Performs user authentication. This API uses a promise to return the result. **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| -| level | string | Yes | Security level of the authentication. It can be S1 (lowest), S2, S3, or S4 (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| +| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| **Return value** + | Type | Description | | --------------------- | ------------------------------------------------------------ | | Promise<number> | Promise used to return the authentication result, which is a number. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** -```js -let authenticator = userIAM_userAuth.getAuthenticator(); -authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); -}).catch((code)=>{ - console.error("auth fail, code = " + code); -}); -``` + ```js + let authenticator = userIAM_userAuth.getAuthenticator(); + authenticator.execute("FACE_ONLY", "S2").then((code)=>{ + console.info("auth success"); + }).catch((error)=>{ + console.error("auth fail, code = " + error); + }); + ``` ## AuthenticationResult(deprecated) diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index d1ffe6f45c4a792bdfda7ad81743a3fe1b8aac51..eb52d85a2c418842f2cb2d581fb0583917b68622 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -24,19 +24,21 @@ Prints the input content in a formatted string. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | format | string | Yes| Format of the string to print.| | ...args | Object[] | No| Data to format.| **Return value** + | Type| Description| | -------- | -------- | | string | String in the specified format.| **Example** ```js - var res = util.printf("%s", "hello world!"); + let res = util.printf("%s", "hello world!"); console.log(res); ``` @@ -50,19 +52,21 @@ Obtains detailed information about a system error code. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | errno | number | Yes| Error code generated.| **Return value** + | Type| Description| | -------- | -------- | | string | Detailed information about the error code.| **Example** ```js - var errnum = 10; // 10 is a system error code. - var result = util.getErrorString(errnum); + let errnum = 10; // 10 is a system error code. + let result = util.getErrorString(errnum); console.log("result = " + result); ``` @@ -82,6 +86,7 @@ Calls back an asynchronous function. In the callback, the first parameter indica | original | Function | Yes| Asynchronous function.| **Return value** + | Type| Description| | -------- | -------- | | Function | Callback, in which the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved) and the second parameter indicates the resolved value.| @@ -91,8 +96,8 @@ Calls back an asynchronous function. In the callback, the first parameter indica async function promiseFn() { return Promise.reject('value'); } - var err = "type err"; - var cb = util.callbackWrapper(promiseFn); + let err = "type err"; + let cb = util.callbackWrapper(promiseFn); cb((err, ret) => { console.log(err); console.log(ret); @@ -105,7 +110,6 @@ Calls back an asynchronous function. In the callback, the first parameter indica promiseWrapper(original: (err: Object, value: Object) => void): Object > **NOTE** -> > This API is deprecated since API version 9. You are advised to use **[util.promisify9+](#utilpromisify9)** instead. Processes an asynchronous function and returns a promise version. @@ -119,9 +123,10 @@ Processes an asynchronous function and returns a promise version. | original | Function | Yes| Asynchronous function.| **Return value** + | Type| Description| | -------- | -------- | -| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise version.| +| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| ## util.promisify9+ @@ -132,11 +137,13 @@ Processes an asynchronous function and returns a promise. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | original | Function | Yes| Asynchronous function.| **Return value** + | Type| Description| | -------- | -------- | | Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| @@ -156,6 +163,90 @@ Processes an asynchronous function and returns a promise. }) ``` +## util.randomUUID9+ + +randomUUID(entropyCache?: boolean): string + +Uses a secure random number generator to generate a random universally unique identifier (UUID) of RFC 4122 version 4. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| entropyCache | boolean | No| Whether a cached UUID can be used. The default value is **true**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | A string representing the UUID generated.| + +**Example** + ```js + let uuid = util.randomUUID(true); + console.log("RFC 4122 Version 4 UUID:" + uuid); + // Output: + // RFC 4122 Version 4 UUID:88368f2a-d5db-47d8-a05f-534fab0a0045 + ``` + +## util.randomBinaryUUID9+ + +randomBinaryUUID(entropyCache?: boolean): Uint8Array + +Uses a secure random number generator to generate a random binary UUID of RFC 4122 version 4. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| entropyCache | boolean | No| Whether a cached UUID can be used. The default value is **true**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Uint8Array | A Uint8Array value representing the UUID generated.| + +**Example** + ```js + let uuid = util.randomBinaryUUID(true); + console.log(JSON.stringify(uuid)); + // Output: + // 138,188,43,243,62,254,70,119,130,20,235,222,199,164,140,150 + ``` + +## util.parseUUID9+ + +parseUUID(uuid: string): Uint8Array + +Parses a UUID from a string, as described in RFC 4122 version 4. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uuid | string | Yes| A string representing the UUID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Uint8Array | A Uint8Array value representing the UUID parsed. If the parsing fails, **SyntaxError** is thrown.| + +**Example** + ```js + let uuid = util.parseUUID("84bdf796-66cc-4655-9b89-d6218d100f9c"); + console.log(JSON.stringify(uuid)); + // Output: + // 132,189,247,150,102,204,70,85,155,137,214,33,141,16,15,156 + ``` + ## TextDecoder ### Attributes @@ -178,6 +269,7 @@ A constructor used to create a **TextDecoder** object. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | encoding | string | No| Encoding format.| @@ -192,7 +284,7 @@ A constructor used to create a **TextDecoder** object. **Example** ```js - var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); + let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); ``` @@ -205,6 +297,7 @@ Decodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | input | Uint8Array | Yes| Uint8Array to decode.| @@ -217,14 +310,15 @@ Decodes the input content. | stream | boolean | No| Whether to allow data blocks in subsequent **decode()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| **Return value** + | Type| Description| | -------- | -------- | | string | Data decoded.| **Example** ```js - var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); - var result = new Uint8Array(6); + let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); + let result = new Uint8Array(6); result[0] = 0xEF; result[1] = 0xBB; result[2] = 0xBF; @@ -232,7 +326,50 @@ Decodes the input content. result[4] = 0x62; result[5] = 0x63; console.log("input num:"); - var retStr = textDecoder.decode( result , {stream: false}); + let retStr = textDecoder.decode( result , {stream: false}); + console.log("retStr = " + retStr); + ``` + + +### decodeWithStream9+ + +decodeWithStream(input: Uint8Array, options?: { stream?: boolean }): string + +Decodes the input content. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| input | Uint8Array | Yes| Uint8Array to decode.| +| options | Object | No| Options related to decoding.| + + **Table 2** options + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| stream | boolean | No| Whether to allow data blocks in subsequent **decodeWithStream()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Data decoded.| + +**Example** + ```js + let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); + let result = new Uint8Array(6); + result[0] = 0xEF; + result[1] = 0xBB; + result[2] = 0xBF; + result[3] = 0x61; + result[4] = 0x62; + result[5] = 0x63; + console.log("input num:"); + let retStr = textDecoder.decodeWithStream( result , {stream: false}); console.log("retStr = " + retStr); ``` @@ -258,7 +395,7 @@ A constructor used to create a **TextEncoder** object. **Example** ```js - var textEncoder = new util.TextEncoder(); + let textEncoder = new util.TextEncoder(); ``` @@ -271,20 +408,22 @@ Encodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | input | string | Yes| String to encode.| **Return value** + | Type| Description| | -------- | -------- | | Uint8Array | Encoded text.| **Example** ```js - var textEncoder = new util.TextEncoder(); - var buffer = new ArrayBuffer(20); - var result = new Uint8Array(buffer); + let textEncoder = new util.TextEncoder(); + let buffer = new ArrayBuffer(20); + let result = new Uint8Array(buffer); result = textEncoder.encode("\uD800¥¥"); ``` @@ -298,22 +437,24 @@ Stores the UTF-8 encoded text. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | input | string | Yes| String to encode.| | dest | Uint8Array | Yes| **Uint8Array** instance used to store the UTF-8 encoded text.| **Return value** + | Type| Description| | -------- | -------- | | Uint8Array | Encoded text.| **Example** ```js - var that = new util.TextEncoder() - var buffer = new ArrayBuffer(4) - var dest = new Uint8Array(buffer) - var result = new Object() + let that = new util.TextEncoder() + let buffer = new ArrayBuffer(4) + let dest = new Uint8Array(buffer) + let result = new Object() result = that.encodeInto('abcd', dest) ``` @@ -329,6 +470,7 @@ A constructor used to create a **RationalNumber** object. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | numerator | number | Yes| Numerator, which is an integer.| @@ -336,7 +478,7 @@ A constructor used to create a **RationalNumber** object. **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); + let rationalNumber = new util.RationalNumber(1,2); ``` @@ -349,19 +491,21 @@ Creates a **RationalNumber** object based on the given string. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | rationalString | string | Yes| String used to create the **RationalNumber** object.| **Return value** + | Type| Description| | -------- | -------- | | object | **RationalNumber** object created.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var rational = util.RationalNumber.createRationalFromString("3/4"); + let rationalNumber = new util.RationalNumber(1,2); + let rational = util.RationalNumber.createRationalFromString("3/4"); ``` @@ -374,20 +518,22 @@ Compares this **RationalNumber** object with a given object. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.| **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var rational = util.RationalNumber.createRationalFromString("3/4"); - var result = rationalNumber.compareTo(rational); + let rationalNumber = new util.RationalNumber(1,2); + let rational = util.RationalNumber.createRationalFromString("3/4"); + let result = rationalNumber.compareTo(rational); ``` @@ -400,14 +546,15 @@ Obtains the value of this **RationalNumber** object as an integer or a floating- **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | number | An integer or a floating-point number.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var result = rationalNumber.valueOf(); + let rationalNumber = new util.RationalNumber(1,2); + let result = rationalNumber.valueOf(); ``` @@ -420,20 +567,22 @@ Checks whether this **RationalNumber** object equals the given object. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | object | Object | Yes| Object used to compare with this **RationalNumber** object.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the two objects are equal; returns **false** otherwise.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var rational = util.RationalNumber.createRationalFromString("3/4"); - var result = rationalNumber.equals(rational); + let rationalNumber = new util.RationalNumber(1,2); + let rational = util.RationalNumber.createRationalFromString("3/4"); + let result = rationalNumber.equals(rational); ``` @@ -446,20 +595,22 @@ Obtains the greatest common divisor of two specified integers. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | number1 | number | Yes| The first integer used to get the greatest common divisor.| | number2 | number | Yes| The second integer used to get the greatest common divisor.| **Return value** + | Type| Description| | -------- | -------- | | number | Greatest common divisor obtained.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var result = util.RationalNumber.getCommonDivisor(4,6); + let rationalNumber = new util.RationalNumber(1,2); + let result = util.RationalNumber.getCommonDivisor(4,6); ``` @@ -479,8 +630,8 @@ Obtains the numerator of this **RationalNumber** object. **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var result = rationalNumber.getNumerator(); + let rationalNumber = new util.RationalNumber(1,2); + let result = rationalNumber.getNumerator(); ``` @@ -493,14 +644,15 @@ Obtains the denominator of this **RationalNumber** object. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | number | Denominator of this **RationalNumber** object.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var result = rationalNumber.getDenominator(); + let rationalNumber = new util.RationalNumber(1,2); + let result = rationalNumber.getDenominator(); ``` @@ -513,14 +665,15 @@ Checks whether this **RationalNumber** object is **0**. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the value of this **RationalNumber** object is **0**; returns **false** otherwise.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var result = rationalNumber.isZero(); + let rationalNumber = new util.RationalNumber(1,2); + let result = rationalNumber.isZero(); ``` @@ -533,14 +686,15 @@ Checks whether this **RationalNumber** object is a Not a Number (NaN). **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if this **RationalNumber** object is a NaN (the denominator and numerator are both **0**); returns **false** otherwise.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var result = rationalNumber.isNaN(); + let rationalNumber = new util.RationalNumber(1,2); + let result = rationalNumber.isNaN(); ``` @@ -553,14 +707,15 @@ Checks whether this **RationalNumber** object represents a finite value. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if this **RationalNumber** object represents a finite value (the denominator is not **0**); returns **false** otherwise.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var result = rationalNumber.isFinite(); + let rationalNumber = new util.RationalNumber(1,2); + let result = rationalNumber.isFinite(); ``` @@ -573,14 +728,15 @@ Obtains the string representation of this **RationalNumber** object. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | string | Returns **NaN** if the numerator and denominator of this object are both **0**; returns a string in Numerator/Denominator format otherwise, for example, **3/5**.| **Example** ```js - var rationalNumber = new util.RationalNumber(1,2); - var result = rationalNumber.toString(); + let rationalNumber = new util.RationalNumber(1,2); + let result = rationalNumber.toString(); ``` ## LruBuffer8+ @@ -595,10 +751,10 @@ Obtains the string representation of this **RationalNumber** object. **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); pro.put(1,8); - var result = pro.length; + let result = pro.length; ``` @@ -611,13 +767,14 @@ A constructor used to create an **LruBuffer** instance. The default capacity of **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | capacity | number | No| Capacity of the **LruBuffer** to create.| **Example** ```js - var lrubuffer= new util.LruBuffer(); + let lrubuffer= new util.LruBuffer(); ``` @@ -630,14 +787,15 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | newCapacity | number | Yes| New capacity of the **LruBuffer**.| **Example** ```js - var pro = new util.LruBuffer(); - var result = pro.updateCapacity(100); + let pro = new util.LruBuffer(); + let result = pro.updateCapacity(100); ``` @@ -650,17 +808,18 @@ Obtains the string representation of this **LruBuffer** object. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | string | String representation of this **LruBuffer** object.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); pro.get(2); pro.remove(20); - var result = pro.toString(); + let result = pro.toString(); ``` @@ -673,14 +832,15 @@ Obtains the capacity of this buffer. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | number | Capacity of this buffer.| **Example** ```js - var pro = new util.LruBuffer(); - var result = pro.getCapacity(); + let pro = new util.LruBuffer(); + let result = pro.getCapacity(); ``` @@ -694,9 +854,9 @@ Clears key-value pairs from this buffer. The **afterRemoval()** method will be c **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.length; + let result = pro.length; pro.clear(); ``` @@ -710,15 +870,16 @@ Obtains the number of return values for **createDefault()**. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | number | Number of return values for **createDefault()**.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(1,8); - var result = pro.getCreateCount(); + let result = pro.getCreateCount(); ``` @@ -731,16 +892,17 @@ Obtains the number of times that the queried values are mismatched. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | number | Number of times that the queried values are mismatched.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); pro.get(2); - var result = pro.getMissCount(); + let result = pro.getMissCount(); ``` @@ -753,17 +915,18 @@ Obtains the number of removals from this buffer. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | number | Number of removals from the buffer.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); pro.updateCapacity(2); pro.put(50,22); - var result = pro.getRemovalCount(); + let result = pro.getRemovalCount(); ``` @@ -776,16 +939,17 @@ Obtains the number of times that the queried values are matched. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | number | Number of times that the queried values are matched.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); pro.get(2); - var result = pro.getMatchCount(); + let result = pro.getMatchCount(); ``` @@ -798,15 +962,16 @@ Obtains the number of additions to this buffer. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | number | Number of additions to the buffer.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.getPutCount(); + let result = pro.getPutCount(); ``` @@ -819,15 +984,16 @@ Checks whether this buffer is empty. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the buffer does not contain any value.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.isEmpty(); + let result = pro.isEmpty(); ``` @@ -840,20 +1006,22 @@ Obtains the value of the specified key. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key based on which the value is queried.| **Return value** + | Type| Description| | -------- | -------- | -| V \| undefind | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| +| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.get(2); + let result = pro.get(2); ``` @@ -866,23 +1034,24 @@ Adds a key-value pair to this buffer. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key of the key-value pair to add.| | value | V | Yes| Value of the key-value pair to add.| **Return value** + | Type| Description| | -------- | -------- | | V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | **Example** ```js - var pro = new util.LruBuffer(); - var result = pro.put(2,10); + let pro = new util.LruBuffer(); + let result = pro.put(2,10); ``` - ### values8+ values(): V[] @@ -892,17 +1061,18 @@ Obtains all values in this buffer, listed from the most to the least recently ac **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | V [] | All values in the buffer, listed from the most to the least recently accessed.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); pro.put(2,"anhu"); pro.put("afaf","grfb"); - var result = pro.values(); + let result = pro.values(); ``` @@ -915,15 +1085,16 @@ Obtains all keys in this buffer, listed from the most to the least recently acce **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | K [] | All keys in the buffer, listed from the most to the least recently accessed.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.keys(); + let result = pro.keys(); ``` @@ -936,20 +1107,22 @@ Removes the specified key and its value from this buffer. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key to remove.| **Return value** + | Type| Description| | -------- | -------- | -| V \| undefind | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| +| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.remove(20); + let result = pro.remove(20); ``` @@ -962,6 +1135,7 @@ Performs subsequent operations after a value is removed. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | isEvict | boolean | No| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| @@ -971,8 +1145,8 @@ Performs subsequent operations after a value is removed. **Example** ```js - var arr = []; - class ChildLruBuffer extends util.LruBuffer + let arr = []; + class ChildLruBuffer extends util.LruBuffer { constructor() { @@ -986,7 +1160,7 @@ Performs subsequent operations after a value is removed. } } } - var lru = new ChildLruBuffer(); + let lru = new ChildLruBuffer(); lru.afterRemoval(false,10,30,null); ``` @@ -1000,20 +1174,22 @@ Checks whether this buffer contains the specified key. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.contains(20); + let result = pro.contains(20); ``` @@ -1026,19 +1202,21 @@ Creates a value if the value of the specified key is not available. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | key | K | Yes| Key of which the value is missing.| **Return value** + | Type| Description| | -------- | -------- | | V | Value of the key.| **Example** ```js - var pro = new util.LruBuffer(); - var result = pro.createDefault(50); + let pro = new util.LruBuffer(); + let result = pro.createDefault(50); ``` @@ -1051,15 +1229,16 @@ Obtains a new iterator object that contains all key-value pairs in this object. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | [K, V] | Iterable array.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro.entries(); + let result = pro.entries(); ``` @@ -1072,15 +1251,16 @@ Obtains a two-dimensional array in key-value pairs. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | [K, V] | Two-dimensional array in key-value pairs.| **Example** ```js - var pro = new util.LruBuffer(); + let pro = new util.LruBuffer(); pro.put(2,10); - var result = pro[Symbol.iterator](); + let result = pro[Symbol.iterator](); ``` @@ -1111,7 +1291,7 @@ class Temperature{ // private readonly _temp: Temperature; this._temp = value; } - comapreTo(value){ + compareTo(value){ return this._temp >= value.getTemp(); } getTemp(){ @@ -1133,6 +1313,7 @@ A constructor used to create a **Scope** object with the specified upper and low **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit of the **Scope** object.| @@ -1140,9 +1321,9 @@ A constructor used to create a **Scope** object with the specified upper and low **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var range = new util.Scope(tempLower, tempUpper); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); ``` @@ -1155,16 +1336,17 @@ Obtains a string representation that contains this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | string | String representation containing the **Scope**.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var range = new util.Scope(tempLower, tempUpper); - var result = range.toString(); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.toString(); ``` @@ -1177,23 +1359,25 @@ Obtains the intersection of this **Scope** and the given **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | range | [Scope](#scope8) | Yes| **Scope** specified.| **Return value** + | Type| Description| | -------- | -------- | | [Scope](#scope8) | Intersection of this **Scope** and the given **Scope**.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var range = new util.Scope(tempLower, tempUpper); - var tempMiDF = new Temperature(35); - var tempMidS = new Temperature(39); - var rangeFir = new util.Scope(tempMiDF, tempMidS); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let rangeFir = new util.Scope(tempMiDF, tempMidS); range.intersect(rangeFir ); ``` @@ -1207,24 +1391,26 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| | upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| **Return value** + | Type| Description| | -------- | -------- | | [Scope](#scope8) | Intersection of this **Scope** and the given lower and upper limits.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var tempMiDF = new Temperature(35); - var tempMidS = new Temperature(39); - var range = new util.Scope(tempLower, tempUpper); - var result = range.intersect(tempMiDF, tempMidS); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let result = range.intersect(tempMiDF, tempMidS); ``` @@ -1244,10 +1430,10 @@ Obtains the upper limit of this **Scope**. **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var range = new util.Scope(tempLower, tempUpper); - var result = range.getUpper(); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.getUpper(); ``` @@ -1260,16 +1446,17 @@ Obtains the lower limit of this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** + | Type| Description| | -------- | -------- | | [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var range = new util.Scope(tempLower, tempUpper); - var result = range.getLower(); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.getLower(); ``` @@ -1282,12 +1469,14 @@ Obtains the union set of this **Scope** and the given lower and upper limits. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| | upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| **Return value** + | Type| Description| | -------- | -------- | | [Scope](#scope8) | Union set of this **Scope** and the given lower and upper limits.| @@ -1295,12 +1484,12 @@ Obtains the union set of this **Scope** and the given lower and upper limits. **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var tempMiDF = new Temperature(35); - var tempMidS = new Temperature(39); - var range = new util.Scope(tempLower, tempUpper); - var result = range.expand(tempMiDF, tempMidS); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let result = range.expand(tempMiDF, tempMidS); ``` @@ -1313,24 +1502,26 @@ Obtains the union set of this **Scope** and the given **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | range | [Scope](#scope8) | Yes| **Scope** specified.| **Return value** + | Type| Description| | -------- | -------- | | [Scope](#scope8) | Union set of this **Scope** and the given **Scope**.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var tempMiDF = new Temperature(35); - var tempMidS = new Temperature(39); - var range = new util.Scope(tempLower, tempUpper); - var rangeFir = new util.Scope(tempMiDF, tempMidS); - var result = range.expand(rangeFir); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let rangeFir = new util.Scope(tempMiDF, tempMidS); + let result = range.expand(rangeFir); ``` @@ -1343,22 +1534,24 @@ Obtains the union set of this **Scope** and the given value. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** + | Type| Description| | -------- | -------- | | [Scope](#scope8) | Union set of this **Scope** and the given value.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var tempMiDF = new Temperature(35); - var range = new util.Scope(tempLower, tempUpper); - var result = range.expand(tempMiDF); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + let result = range.expand(tempMiDF); ``` @@ -1371,21 +1564,23 @@ Checks whether a value is within this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var tempMiDF = new Temperature(35); - var range = new util.Scope(tempLower, tempUpper); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); range.contains(tempMiDF); ``` @@ -1399,24 +1594,26 @@ Checks whether a range is within this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | range | [Scope](#scope8) | Yes| **Scope** specified.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var range = new util.Scope(tempLower, tempUpper); - var tempLess = new Temperature(20); - var tempMore = new Temperature(45); - var rangeSec = new util.Scope(tempLess, tempMore); - var result = range.contains(rangeSec); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let tempLess = new Temperature(20); + let tempMore = new Temperature(45); + let rangeSec = new util.Scope(tempLess, tempMore); + let result = range.contains(rangeSec); ``` @@ -1429,22 +1626,24 @@ Limits a value to this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** + | Type| Description| | -------- | -------- | | [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** ```js - var tempLower = new Temperature(30); - var tempUpper = new Temperature(40); - var tempMiDF = new Temperature(35); - var range = new util.Scope(tempLower, tempUpper); - var result = range.clamp(tempMiDF); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + let result = range.clamp(tempMiDF); ``` @@ -1461,7 +1660,7 @@ A constructor used to create a **Base64** object. **Example** ```js - var base64 = new util.Base64(); + let base64 = new util.Base64(); ``` @@ -1474,20 +1673,22 @@ Encodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array | Yes| Uint8Array to encode.| **Return value** + | Type| Description| | -------- | -------- | | Uint8Array | Uint8Array encoded.| **Example** ```js - var that = new util.Base64(); - var array = new Uint8Array([115,49,51]); - var result = that.encodeSync(array); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let result = that.encodeSync(array); ``` @@ -1500,20 +1701,22 @@ Encodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array | Yes| Uint8Array to encode.| **Return value** + | Type| Description| | -------- | -------- | | string | String encoded from the Uint8Array.| **Example** ```js - var that = new util.Base64(); - var array = new Uint8Array([115,49,51]); - var result = that.encodeToStringSync(array); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let result = that.encodeToStringSync(array); ``` @@ -1526,20 +1729,22 @@ Decodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array \| string | Yes| Uint8Array or string to decode.| **Return value** + | Type| Description| | -------- | -------- | | Uint8Array | Uint8Array decoded.| **Example** ```js - var that = new util.Base64(); - var buff = 'czEz'; - var result = that.decodeSync(buff); + let that = new util.Base64(); + let buff = 'czEz'; + let result = that.decodeSync(buff); ``` @@ -1552,20 +1757,22 @@ Encodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array | Yes| Uint8Array to encode asynchronously.| **Return value** + | Type| Description| | -------- | -------- | | Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** ```js - var that = new util.Base64(); - var array = new Uint8Array([115,49,51]); - var rarray = new Uint8Array([99,122,69,122]); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let rarray = new Uint8Array([99,122,69,122]); that.encode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { console.log(val[i].toString()) @@ -1583,19 +1790,21 @@ Encodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array | Yes| Uint8Array to encode asynchronously.| **Return value** + | Type| Description| | -------- | -------- | | Promise<string> | String obtained after asynchronous encoding.| **Example** ```js - var that = new util.Base64(); - var array = new Uint8Array([115,49,51]); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); that.encodeToString(array).then(val=>{ console.log(val) }) @@ -1611,20 +1820,22 @@ Decodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.| **Return value** + | Type| Description| | -------- | -------- | | Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** ```js - var that = new util.Base64(); - var array = new Uint8Array([99,122,69,122]); - var rarray = new Uint8Array([115,49,51]); + let that = new util.Base64(); + let array = new Uint8Array([99,122,69,122]); + let rarray = new Uint8Array([115,49,51]); that.decode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { console.log(val[i].toString()) @@ -1646,7 +1857,7 @@ A constructor used to create a **Types** object. **Example** ```js - var type = new util.types(); + let type = new util.types(); ``` @@ -1659,19 +1870,21 @@ Checks whether the input value is of the **ArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isAnyArrayBuffer(new ArrayBuffer(0)); + let that = new util.types(); + let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); ``` @@ -1686,19 +1899,21 @@ Checks whether the input value is of the **ArrayBufferView** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isArrayBufferView(new Int8Array([])); + let that = new util.types(); + let result = that.isArrayBufferView(new Int8Array([])); ``` @@ -1711,22 +1926,24 @@ Checks whether the input value is of the **arguments** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); + let that = new util.types(); function foo() { var result = that.isArgumentsObject(arguments); } - var f = foo(); + let f = foo(); ``` @@ -1739,19 +1956,21 @@ Checks whether the input value is of the **ArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isArrayBuffer(new ArrayBuffer(0)); + let that = new util.types(); + let result = that.isArrayBuffer(new ArrayBuffer(0)); ``` @@ -1764,19 +1983,21 @@ Checks whether the input value is an asynchronous function. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isAsyncFunction(async function foo() {}); + let that = new util.types(); + let result = that.isAsyncFunction(async function foo() {}); ``` @@ -1789,19 +2010,21 @@ Checks whether the input value is of the **Boolean** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isBooleanObject(new Boolean(true)); + let that = new util.types(); + let result = that.isBooleanObject(new Boolean(true)); ``` @@ -1814,19 +2037,21 @@ Checks whether the input value is of the **Boolean**, **Number**, **String**, or **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isBoxedPrimitive(new Boolean(false)); + let that = new util.types(); + let result = that.isBoxedPrimitive(new Boolean(false)); ``` @@ -1839,20 +2064,22 @@ Checks whether the input value is of the **DataView** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); + let that = new util.types(); const ab = new ArrayBuffer(20); - var result = that.isDataView(new DataView(ab)); + let result = that.isDataView(new DataView(ab)); ``` @@ -1865,19 +2092,21 @@ Checks whether the input value is of the **Date** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isDate(new Date()); + let that = new util.types(); + let result = that.isDate(new Date()); ``` @@ -1890,19 +2119,21 @@ Checks whether the input value is of the **native external** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isExternal(true); + let that = new util.types(); + let result = that.isExternal(true); ``` @@ -1915,19 +2146,21 @@ Checks whether the input value is of the **Float32Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isFloat32Array(new Float32Array()); + let that = new util.types(); + let result = that.isFloat32Array(new Float32Array()); ``` @@ -1940,19 +2173,21 @@ Checks whether the input value is of the **Float64Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isFloat64Array(new Float64Array()); + let that = new util.types(); + let result = that.isFloat64Array(new Float64Array()); ``` @@ -1965,19 +2200,21 @@ Checks whether the input value is a generator function. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isGeneratorFunction(function* foo() {}); + let that = new util.types(); + let result = that.isGeneratorFunction(function* foo() {}); ``` @@ -1990,21 +2227,23 @@ Checks whether the input value is a generator object. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| **Example** ```js - var that = new util.types(); + let that = new util.types(); function* foo() {} const generator = foo(); - var result = that.isGeneratorObject(generator); + let result = that.isGeneratorObject(generator); ``` @@ -2017,19 +2256,21 @@ Checks whether the input value is of the **Int8Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isInt8Array(new Int8Array([])); + let that = new util.types(); + let result = that.isInt8Array(new Int8Array([])); ``` @@ -2042,19 +2283,21 @@ Checks whether the input value is of the **Int16Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isInt16Array(new Int16Array([])); + let that = new util.types(); + let result = that.isInt16Array(new Int16Array([])); ``` @@ -2067,19 +2310,21 @@ Checks whether the input value is of the **Int32Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isInt32Array(new Int32Array([])); + let that = new util.types(); + let result = that.isInt32Array(new Int32Array([])); ``` @@ -2092,19 +2337,21 @@ Checks whether the input value is of the **Map** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isMap(new Map()); + let that = new util.types(); + let result = that.isMap(new Map()); ``` @@ -2117,20 +2364,22 @@ Checks whether the input value is of the **MapIterator** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); + let that = new util.types(); const map = new Map(); - var result = that.isMapIterator(map.keys()); + let result = that.isMapIterator(map.keys()); ``` @@ -2143,19 +2392,21 @@ Checks whether the input value is of the **Error** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isNativeError(new TypeError()); + let that = new util.types(); + let result = that.isNativeError(new TypeError()); ``` @@ -2168,19 +2419,21 @@ Checks whether the input value is a number object. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isNumberObject(new Number(0)); + let that = new util.types(); + let result = that.isNumberObject(new Number(0)); ``` @@ -2193,19 +2446,21 @@ Checks whether the input value is a promise. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isPromise(Promise.resolve(1)); + let that = new util.types(); + let result = that.isPromise(Promise.resolve(1)); ``` @@ -2218,21 +2473,23 @@ Checks whether the input value is a proxy. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| **Example** ```js - var that = new util.types(); + let that = new util.types(); const target = {}; const proxy = new Proxy(target, {}); - var result = that.isProxy(proxy); + let result = that.isProxy(proxy); ``` @@ -2245,19 +2502,21 @@ Checks whether the input value is of the **RegExp** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isRegExp(new RegExp('abc')); + let that = new util.types(); + let result = that.isRegExp(new RegExp('abc')); ``` @@ -2270,19 +2529,21 @@ Checks whether the input value is of the **Set** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isSet(new Set()); + let that = new util.types(); + let result = that.isSet(new Set()); ``` @@ -2295,20 +2556,22 @@ Checks whether the input value is of the **SetIterator** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); + let that = new util.types(); const set = new Set(); - var result = that.isSetIterator(set.keys()); + let result = that.isSetIterator(set.keys()); ``` @@ -2321,19 +2584,21 @@ Checks whether the input value is a string object. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isStringObject(new String('foo')); + let that = new util.types(); + let result = that.isStringObject(new String('foo')); ``` @@ -2346,20 +2611,22 @@ Checks whether the input value is a symbol object. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| **Example** ```js - var that = new util.types(); + let that = new util.types(); const symbols = Symbol('foo'); - var result = that.isSymbolObject(Object(symbols)); + let result = that.isSymbolObject(Object(symbols)); ``` @@ -2374,19 +2641,21 @@ Checks whether the input value is of the **TypedArray** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isTypedArray(new Float64Array([])); + let that = new util.types(); + let result = that.isTypedArray(new Float64Array([])); ``` @@ -2399,19 +2668,21 @@ Checks whether the input value is of the **Uint8Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isUint8Array(new Uint8Array([])); + let that = new util.types(); + let result = that.isUint8Array(new Uint8Array([])); ``` @@ -2424,19 +2695,21 @@ Checks whether the input value is of the **Uint8ClampedArray** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isUint8ClampedArray(new Uint8ClampedArray([])); + let that = new util.types(); + let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); ``` @@ -2449,19 +2722,21 @@ Checks whether the input value is of the **Uint16Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isUint16Array(new Uint16Array([])); + let that = new util.types(); + let result = that.isUint16Array(new Uint16Array([])); ``` @@ -2474,19 +2749,21 @@ Checks whether the input value is of the **Uint32Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isUint32Array(new Uint32Array([])); + let that = new util.types(); + let result = that.isUint32Array(new Uint32Array([])); ``` @@ -2499,19 +2776,21 @@ Checks whether the input value is of the **WeakMap** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isWeakMap(new WeakMap()); + let that = new util.types(); + let result = that.isWeakMap(new WeakMap()); ``` @@ -2524,17 +2803,128 @@ Checks whether the input value is of the **WeakSet** type. **System capability**: SystemCapability.Utils.Lang **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | Object | Yes| Object to check.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| **Example** ```js - var that = new util.types(); - var result = that.isWeakSet(new WeakSet()); + let that = new util.types(); + let result = that.isWeakSet(new WeakSet()); + ``` + + +### isBigInt64Array8+ + +isBigInt64Array(value: Object): boolean + +Checks whether the input value is of the **BigInt64Array** type. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| + +**Example** + ```js + let that = new util.types(); + let result = that.isBigInt64Array(new BigInt64Array([])); + ``` + + +### isBigUint64Array8+ + +isBigUint64Array(value: Object): boolean + +Checks whether the input value is of the **BigUint64Array** type. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| + +**Example** + ```js + let that = new util.types(); + let result = that.isBigUint64Array(new BigUint64Array([])); + ``` + + +### isModuleNamespaceObject8+ + +isModuleNamespaceObject(value: Object): boolean + +Checks whether the input value is a module namespace object. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| + +**Example** + ```js + import url from '@ohos.url' + let that = new util.types(); + let result = that.isModuleNamespaceObject(url); + ``` + + +### isSharedArrayBuffer8+ + +isSharedArrayBuffer(value: Object): boolean + +Checks whether the input value is of the **SharedArrayBuffer** type. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| + +**Example** + ```js + let that = new util.types(); + let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); ``` diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index 2eae3ec8e5599a6e2b0123f4f6fa7368e51365e7..8c6ca80a6161e29fd1eb4ccd5e3a4f9f7841556b 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -21,10 +21,10 @@ Defines the wallpaper type. **System capability**: SystemCapability.MiscServices.Wallpaper -| Name | Description | +| Name| Description| | -------- | -------- | -| WALLPAPER_LOCKSCREEN | Lock screen wallpaper. | -| WALLPAPER_SYSTEM | Home screen wallpaper. | +| WALLPAPER_LOCKSCREEN | Lock screen wallpaper.| +| WALLPAPER_SYSTEM | Home screen wallpaper.| ## wallpaper.getColors @@ -36,10 +36,11 @@ Obtains the main color information of the wallpaper of the specified type. This **System capability**: SystemCapability.MiscServices.Wallpaper **Parameters** -| Name | Type | Mandatory | Description | + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | -| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes | Callback used to return the main color information of the wallpaper. | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes| Callback used to return the main color information of the wallpaper.| **Example** @@ -64,15 +65,15 @@ Obtains the main color information of the wallpaper of the specified type. This **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<Array<[RgbaColor](#rgbacolor)>> | Promise used to return the main color information of the wallpaper. | +| Promise<Array<[RgbaColor](#rgbacolor)>> | Promise used to return the main color information of the wallpaper.| **Example** @@ -95,10 +96,10 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1. | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<number> | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| **Example** @@ -124,15 +125,15 @@ Obtains the ID of the wallpaper of the specified type. This API uses a promise t **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1. | +| Promise<number> | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| **Example** @@ -155,9 +156,9 @@ Obtains the minimum height of this wallpaper. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead. | +| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| **Example** @@ -183,9 +184,9 @@ Obtains the minimum height of this wallpaper. This API uses a promise to return **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead. | +| Promise<number> | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| **Example** @@ -206,11 +207,12 @@ Obtains the minimum width of this wallpaper. This API uses an asynchronous callb **System capability**: SystemCapability.MiscServices.Wallpaper + **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead. | +| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| **Example** @@ -235,9 +237,9 @@ Obtains the minimum width of this wallpaper. This API uses a promise to return t **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<number> | Promised used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead. | +| Promise<number> | Promised used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| **Example** @@ -260,9 +262,9 @@ Checks whether to allow the application to change the wallpaper for the current **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Returns **true** if the application is allowed to change the wallpaper for the current user; returns **false** otherwise. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if the application is allowed to change the wallpaper for the current user; returns **false** otherwise.| **Example** @@ -287,9 +289,9 @@ Checks whether to allow the application to change the wallpaper for the current **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<boolean> | Returns **true** if the application is allowed to change the wallpaper for the current user; returns **false** otherwise. | +| Promise<boolean> | Promise used to return the result. Returns **true** if the application is allowed to change the wallpaper for the current user; returns **false** otherwise.| **Example** @@ -312,9 +314,9 @@ Checks whether the user is allowed to set wallpapers. This API uses an asynchron **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Returns **true** if the user is allowed to set wallpapers; returns **false** otherwise. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if the user is allowed to set wallpapers; returns **false** otherwise.| **Example** @@ -339,9 +341,9 @@ Checks whether the user is allowed to set wallpapers. This API uses a promise to **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<boolean> | Returns **true** if the user is allowed to set wallpapers; returns **false** otherwise. | +| Promise<boolean> | Promise used to return the result. Returns **true** if the user is allowed to set wallpapers; returns **false** otherwise.| **Example** @@ -366,10 +368,10 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned. | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.| **Example** @@ -396,15 +398,15 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned. | +| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| **Example** @@ -429,16 +431,16 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \| [PixelMap](js-apis-image.md#pixelmap7) | Yes | URI of a JPEG or PNG file, or bitmap of a PNG file. | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned. | +| source | string \|[PixelMap](js-apis-image.md#pixelmap7) | | URI of a JPEG or PNG file, or bitmap of a PNG file.| +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| **Example** -```js -// The source type is string. + ```js + //The source type is string. let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { if (error) { @@ -448,7 +450,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a console.log(`success to setWallpaper.`); }); -// The source type is image.PixelMap. + // The source type is image.PixelMap. import image from '@ohos.multimedia.image'; let imageSource = image.createImageSource("file://" + wallpaperPath); let opts = { @@ -468,7 +470,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a }).catch((error) => { console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); }); -``` + ``` ## wallpaper.setWallpaper @@ -483,21 +485,21 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \| [PixelMap](js-apis-image.md#pixelmap7) | Yes | URI path of the JPEG or PNG file, or bitmap of the PNG file. | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | +| source | string \|[PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned. | +| Promise<void> | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| **Example** -```js -// The source type is string. + ```js + // The source type is string. let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { console.log(`success to setWallpaper.`); @@ -505,7 +507,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); }); -// The source type is image.PixelMap. + // The source type is image.PixelMap. import image from '@ohos.multimedia.image'; let imageSource = image.createImageSource("file://" + wallpaperPath); let opts = { @@ -523,7 +525,7 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr }).catch((error) => { console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); }); -``` + ``` ## wallpaper.getFile8+ @@ -537,10 +539,10 @@ Obtains the wallpaper of the specified type. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned. | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| **Example** @@ -566,15 +568,15 @@ Obtains the wallpaper of the specified type. This API uses a promise to return t **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes | Wallpaper type. | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned. | +| Promise<number> | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| **Example** @@ -591,18 +593,20 @@ Obtains the wallpaper of the specified type. This API uses a promise to return t getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; -Obtains the pixel image for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| **Example** @@ -618,12 +622,14 @@ Obtains the pixel image for the wallpaper of the specified type. This API uses a getPixelMap(wallpaperType: WallpaperType): Promise<image.PixelMap> -Obtains the pixel image for the wallpaper of the specified type. This API uses a promise to return the result. +Obtains the pixel map for the wallpaper of the specified type. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -634,7 +640,7 @@ Obtains the pixel image for the wallpaper of the specified type. This API uses a | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| +| Promise<void> | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| **Example** @@ -659,10 +665,10 @@ Subscribes to the wallpaper color change event. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value **colorChange** indicates subscribing to the wallpaper color change event. | -| callback | function | Yes | Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | +| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.| +| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| **Example** @@ -684,10 +690,10 @@ Unsubscribes from the wallpaper color change event. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value **colorChange** indicates unsubscribing from the wallpaper color change event. | -| callback | function | No | Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type. | +| type | string | Yes| Type of the event to unsubscribe from. The value **colorChange** indicates unsubscribing from the wallpaper color change event.| +| callback | function | No| Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| **Example** @@ -696,10 +702,10 @@ Unsubscribes from the wallpaper color change event. console.log(`wallpaper color changed.`); }; wallpaper.on('colorChange', listener); -// Unsubscribe from the listener. -wallpaper.off('colorChange', listener); -// Unsubscribe from all subscriptions of the colorChange type. -wallpaper.off('colorChange'); + // Unsubscribe from the listener. + wallpaper.off('colorChange', listener); + // Unsubscribe from all subscriptions of the colorChange type. + wallpaper.off('colorChange'); ``` @@ -707,9 +713,9 @@ wallpaper.off('colorChange'); **System capability**: SystemCapability.MiscServices.Wallpaper -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| red | number | Yes | Yes | Red color. The value ranges from 0 to 255. | -| green | number | Yes | Yes | Green color. The value ranges from 0 to 255. | -| blue | number | Yes | Yes | Blue color. The value ranges from 0 to 255. | -| alpha | number | Yes | Yes | Alpha value. The value ranges from 0 to 255. | +| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.| +| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.| +| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.| +| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.| diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index eccade788a2d19a81b1512ae206dbdfba449b95d..ae5ab4c9b924e6b72457a9bbadec1cfd26ef5e6b 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -16,13 +16,15 @@ import wifi from '@ohos.wifi'; enableWifi(): boolean Enables WLAN. -This is a system API. + +**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.| @@ -33,13 +35,15 @@ This is a system API. disableWifi(): boolean Disables WLAN. -This is a system API. + +**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.| @@ -56,6 +60,7 @@ Checks whether WLAN is enabled. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** + | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| @@ -72,6 +77,7 @@ Starts a scan for WLAN. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** + | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -88,6 +94,7 @@ Obtains the scan result. This API uses a promise to return the result. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** + | **Type**| **Description**| | -------- | -------- | | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| @@ -104,6 +111,7 @@ Obtains the scan result. This API uses an asynchronous callback to return the re **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.| @@ -157,6 +165,7 @@ 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.| @@ -167,8 +176,8 @@ Represents WLAN hotspot information. | 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.| -| centerFrequency19+ | number | Read only| Center frequency.| +| 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.| @@ -179,6 +188,7 @@ Enumerates the WLAN security types. **System capability**: SystemCapability.Communication.WiFi.Core + | **Name**| **Default Value**| **Description**| | -------- | -------- | -------- | | WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| @@ -197,8 +207,11 @@ Enumerates the WLAN security types. 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.| @@ -211,6 +224,7 @@ Enumerates the WLAN channel widths. **System capability**: SystemCapability.Communication.WiFi.STA + | **Name**| **Default Value**| **Description**| | -------- | -------- | -------- | | WIDTH_20MHZ | 0 | 20 MHz.| @@ -232,6 +246,7 @@ Obtains the scan result. This API returns the result synchronously. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** + | **Type**| **Description**| | -------- | -------- | |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| @@ -242,18 +257,21 @@ Obtains the scan result. This API returns the result synchronously. addDeviceConfig(config: WifiDeviceConfig): Promise<number> Adds network configuration. This API uses a promise to return the result. -This is a system API. + +**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 WLAN configuration ID. If **-1** is returned, the operation has failed.| @@ -264,6 +282,7 @@ 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.| @@ -271,22 +290,25 @@ Represents the WLAN configuration. | 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| User ID, which is available only to system applications.| -| disableReason | number | Read only| Reason for disabling WLAN. This parameter is available only to system applications.| -| netId | number | Read only| Allocated network ID, which is available only to system applications.| -| randomMacType | number | Read only| Random MAC type, which is available only to system applications.| -| randomMacAddr | string | Read only| Random MAC address, which is available only for system applications.| -| ipType | [IpType](#iptype7) | Read only| IP address type, which is available only to system applications.| -| staticIp | [IpConfig](#ipconfig7) | Read only| Static IP address configuration, which is available only to system applications.| -| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Read only| EAP configuration, which is available only to system applications.| +| 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.| ## IpType7+ Enumerate the IP address types. +**System API**: This is a system API. + **System capability**: SystemCapability.Communication.WiFi.STA + | Name| Default Value| Description| | -------- | -------- | -------- | | STATIC | 0 | Static IP address.| @@ -298,6 +320,8 @@ Enumerate the IP address types. Represents IP configuration information. +**System API**: This is a system API. + **System capability**: SystemCapability.Communication.WiFi.STA | **Name**| **Type**| **Readable/Writable**| **Description**| @@ -312,6 +336,8 @@ Represents IP configuration information. Represents EAP configuration information. +**System API**: This is a system API. + **System capability**: SystemCapability.Communication.WiFi.STA | **Name**| **Type**| **Readable/Writable**| **Description**| @@ -335,6 +361,8 @@ Represents EAP configuration information. Enumerates the EAP authentication methods. +**System API**: This is a system API. + **System capability**: SystemCapability.Communication.WiFi.STA | Name| Default Value| Description| @@ -354,6 +382,8 @@ Enumerates the EAP authentication methods. Enumerates the Phase 2 authentication methods. +**System API**: This is a system API. + **System capability**: SystemCapability.Communication.WiFi.STA | Name| Default Value| Description| @@ -373,13 +403,15 @@ Enumerates the Phase 2 authentication methods. addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void Adds network configuration. This API uses an asynchronous callback to return the result. -This is a system API. + +**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.| @@ -397,11 +429,13 @@ Adds the configuration of an untrusted network. This API uses a promise to retur **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** + | **Type**| **Description**| | -------- | -------- | | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| @@ -418,6 +452,7 @@ Adds the configuration of an untrusted network. This API uses an asynchronous ca **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| @@ -435,11 +470,13 @@ Removes the configuration of an untrusted network. This API uses a promise to re **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| **Return value** + | **Type**| **Description**| | -------- | -------- | | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| @@ -456,6 +493,7 @@ Removes the configuration of an untrusted network. This API uses an asynchronous **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| @@ -473,11 +511,13 @@ Adds the configuration of a candidate network. This API uses a promise to return **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.| @@ -494,6 +534,7 @@ Adds the configuration of a candidate network. This API uses an asynchronous cal **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| @@ -511,11 +552,13 @@ Removes the configuration of a candidate network. This API uses a promise to ret **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.| @@ -532,6 +575,7 @@ Removes the configuration of a candidate network. This API uses an asynchronous **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | networkId | number | Yes| ID of the network configuration to remove.| @@ -549,6 +593,7 @@ Obtains candidate network configuration. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** + | **Type**| **Description**| | -------- | -------- | |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| @@ -556,7 +601,7 @@ Obtains candidate network configuration. ## wifi.connectToCandidateConfig9+ -connectToCandidateConfig(networkId: number): boolean +connectToCandidateConfig(networkId: number): void Connects to a candidate network. @@ -565,33 +610,32 @@ Connects to a candidate network. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | networkId | number | Yes| ID of the candidate network configuration.| -**Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - ## wifi.connectToNetwork connectToNetwork(networkId: number): boolean Connects to the specified network. -This is a system API. + +**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.| @@ -602,20 +646,22 @@ This is a system API. connectToDevice(config: WifiDeviceConfig): boolean Connects to the specified network. -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 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.| @@ -625,16 +671,17 @@ This is a system API. disconnect(): boolean -Disconnects from the specified network. -This is a system API. +Disconnects the network. -**Required permissions**: - ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) +**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.| @@ -651,12 +698,14 @@ Obtains the WLAN signal level. **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].| @@ -673,6 +722,7 @@ Obtains WLAN connection information. This API uses a promise to return the resul **System capability**: SystemCapability.Communication.WiFi.STA **Return value** + | Type| Description| | -------- | -------- | | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| @@ -689,6 +739,7 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r **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.| @@ -723,19 +774,19 @@ Represents the WLAN connection information. | -------- | -------- | -------- | -------- | | 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, which is available only to system applications.| +| 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. This parameter is only available to system applications.| -| snr | number | Read only| Signal-to-noise ratio (SNR), which is available only to system applications.| +| 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, which is available only to system applications.| +| suppState | [SuppState](#suppstate) | Read only| Supplicant state.
**System API**: This is a system API.| | connState | [ConnState](#connstate) | Read only| WLAN connection state.| @@ -761,6 +812,8 @@ Enumerates the WLAN connection states. Enumerates the supplicant states. +**System API**: This is a system API. + **System capability**: SystemCapability.Communication.WiFi.STA | Name| Default Value| Description| @@ -790,6 +843,7 @@ Checks whether the WLAN is connected. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** + | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| @@ -800,13 +854,15 @@ Checks whether the WLAN is connected. getSupportedFeatures(): number Obtains the features supported by this device. -This is a system API. + +**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. | @@ -839,11 +895,13 @@ Checks whether the device supports the specified WLAN feature. **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.| @@ -854,13 +912,15 @@ Checks whether the device supports the specified WLAN feature. getDeviceMacAddress(): string[] Obtains the device MAC address. -This is a system API. + +**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.| @@ -877,6 +937,7 @@ Obtains IP information. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** + | **Type**| **Description**| | -------- | -------- | | [IpInfo](#ipinfo7) | IP information obtained.| @@ -910,6 +971,7 @@ Obtains the country code. **System capability**: SystemCapability.Communication.WiFi.Core **Return value** + | **Type**| **Description**| | -------- | -------- | | string | Country code obtained.| @@ -920,13 +982,15 @@ Obtains the country code. reassociate(): boolean Re-associates with the network. -This is a system API. + +**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.| @@ -937,13 +1001,15 @@ This is a system API. reconnect(): boolean Reconnects to the network. -This is a system API. + +**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.| @@ -954,13 +1020,15 @@ This is a system API. getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> Obtains network configuration. -This is a system API. + +**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.| @@ -968,24 +1036,27 @@ This is a system API. ## wifi.updateNetwork7+ -updateNetwork(config: WifiDeviceConfig): boolean +updateNetwork(config: WifiDeviceConfig): number Updates network configuration. -This is a system API. + +**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**| | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| ## wifi.disableNetwork7+ @@ -993,18 +1064,21 @@ This is a system API. disableNetwork(netId: number): boolean Disables network configuration. -This is a system API. + +**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.| @@ -1015,13 +1089,15 @@ This is a system API. removeAllNetwork(): boolean Removes the configuration of all networks. -This is a system API. + +**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.| @@ -1032,18 +1108,21 @@ This is a system API. removeDevice(id: number): boolean Removes the specified network configuration. -This is a system API. + +**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.| @@ -1054,13 +1133,15 @@ This is a system API. enableHotspot(): boolean Enables this hotspot. -This is a system API. + +**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.| @@ -1071,13 +1152,15 @@ This is a system API. disableHotspot(): boolean Disables this hotspot. -This is a system API. + +**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.| @@ -1088,13 +1171,15 @@ This is a system API. isHotspotDualBandSupported(): boolean Checks whether the hotspot supports dual band. -This is a system API. + +**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.| @@ -1105,13 +1190,15 @@ This is a system API. isHotspotActive(): boolean Checks whether this hotspot is active. -This is a system API. + +**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.| @@ -1122,18 +1209,21 @@ This is a system API. setHotspotConfig(config: HotspotConfig): boolean Sets hotspot configuration. -This is a system API. + +**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](#hotspotconfig7) | Yes| Hotspot configuration to set.| **Return value** + | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -1143,6 +1233,8 @@ This is a system API. Represents the hotspot configuration. +**System API**: This is a system API. + **System capability**: SystemCapability.Communication.WiFi.AP.Core | **Name**| **Type**| **Readable/Writable**| **Description**| @@ -1159,13 +1251,15 @@ Represents the hotspot configuration. getHotspotConfig(): HotspotConfig obtains hotspot configuration. -This is a system API. + +**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](#hotspotconfig7) | Hotspot configuration obtained.| @@ -1176,13 +1270,15 @@ This is a system API. getStations():  Array<[StationInfo](#stationinfo7)> Obtains information about the connected stations. -This is a system API. + +**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](#stationinfo7)> | Connected stations obtained.| @@ -1192,6 +1288,8 @@ This is a system API. Represents the station information. +**System API**: This is a system API. + **System capability**: SystemCapability.Communication.WiFi.AP.Core | **Name**| **Type**| **Readable/Writable**| **Description**| @@ -1212,6 +1310,7 @@ Obtains P2P link information. This API uses a promise to return the result. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** + | Type| Description| | -------- | -------- | | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise used to return the P2P link information obtained.| @@ -1254,6 +1353,7 @@ Obtains P2P link information. This API uses an asynchronous callback to return t **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | 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.| @@ -1270,6 +1370,7 @@ Obtains the current P2P group information. This API uses a promise to return the **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** + | Type| Description| | -------- | -------- | | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| @@ -1286,6 +1387,7 @@ Obtains the current P2P group information. This API uses an asynchronous callbac **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<[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.| @@ -1302,6 +1404,7 @@ Obtains the peer device list in the P2P connection. This API uses a promise to r **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** + | Type| Description| | -------- | -------- | | Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise used to return the peer device list.| @@ -1318,6 +1421,7 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou **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 peer device list obtained. If **err** is not **0**, an error has occurred.| @@ -1364,6 +1468,7 @@ Obtains the local device information in the P2P connection. This API uses a prom **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** + | Type| Description| | -------- | -------- | | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| @@ -1380,6 +1485,7 @@ Obtains the local device information in the P2P connection. This API uses an asy **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.| @@ -1402,6 +1508,7 @@ Creates a P2P group. | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -1446,6 +1553,7 @@ Removes this P2P group. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -1463,11 +1571,13 @@ Sets up a P2P connection. **Parameters** + | **Name**| **Type**| Mandatory| **Description**| | -------- | -------- | -------- | -------- | | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -1551,6 +1661,7 @@ Cancels this P2P connection. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -1567,6 +1678,7 @@ Starts to discover devices. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -1583,6 +1695,7 @@ Stops discovering devices. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -1594,17 +1707,21 @@ deletePersistentGroup(netId: number): boolean Deletes a persistent group. -**Required permissions**: ohos.permission.GET_WIFI_INFO +**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.| @@ -1615,13 +1732,15 @@ Deletes a persistent group. getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> Obtains information about all P2P groups. This API uses a promise to return the result. -This is a system API. + +**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.| @@ -1652,11 +1771,14 @@ 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.| @@ -1667,19 +1789,21 @@ Obtains information about all P2P groups. This API uses an asynchronous callback setDeviceName(devName: string): boolean Sets the device name. -This is a system API. -**Required permissions**: - ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) +**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.| @@ -1696,6 +1820,7 @@ Registers the WLAN state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiStateChange**.| @@ -1722,6 +1847,7 @@ Unregisters the WLAN state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiStateChange**.| @@ -1755,6 +1881,7 @@ Registers the WLAN connection state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiConnectionChange**.| @@ -1779,6 +1906,7 @@ Unregisters the WLAN connection state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiConnectionChange**.| @@ -1796,6 +1924,7 @@ Registers the WLAN scan state change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiScanStateChange**.| @@ -1838,6 +1967,7 @@ Registers the RSSI change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiRssiChange**.| @@ -1855,6 +1985,7 @@ Unregisters the RSSI change events. **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **wifiRssiChange**.| @@ -1872,6 +2003,7 @@ Registers the hotspot state change events. **System capability**: SystemCapability.Communication.WiFi.AP.Core **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **hotspotStateChange**.| @@ -1898,6 +2030,7 @@ Unregisters the hotspot state change events. **System capability**: SystemCapability.Communication.WiFi.AP.Core **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **hotspotStateChange**.| @@ -1915,6 +2048,7 @@ Registers the P2P state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pStateChange**.| @@ -1941,6 +2075,7 @@ Unregisters the P2P state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pStateChange**.| @@ -1958,6 +2093,7 @@ Registers the P2P connection state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pConnectionChange**.| @@ -1975,6 +2111,7 @@ Unregisters the P2P connection state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pConnectionChange**.| @@ -1992,6 +2129,7 @@ Registers the P2P device state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDeviceChange**.| @@ -2009,6 +2147,7 @@ Unregisters the P2P device state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDeviceChange**.| @@ -2026,6 +2165,7 @@ Registers the P2P peer device state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| @@ -2043,6 +2183,7 @@ Unregisters the P2P peer device state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| @@ -2060,6 +2201,7 @@ Registers the P2P persistent group state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| @@ -2077,6 +2219,7 @@ Unregisters the P2P persistent group state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| @@ -2094,6 +2237,7 @@ Registers the P2P device discovery state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| @@ -2118,6 +2262,7 @@ Unregisters the P2P device discovery state change events. **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 4c716d142c2d773da09dec8e2c0d8b09d0d628aa..c30f11c4a06a5b80ae2f00f88a5baa8e071ffad3 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -3122,7 +3122,7 @@ let promise = windowClass.setForbidSplitMove(isForbidSplitMove); promise.then((data)=> { console.info('Succeeded in forbidding window moving in split screen mode. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to forbidd window moving in split screen mode. Cause: ' + JSON.stringify(err)); + console.error('Failed to forbid window moving in split screen mode. Cause: ' + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md index ee3fa7397ef213d615ce3e0f71d094cb3d4fc98e..fd9bb9e2d7e174e221c54fdefeedcff3473ff405 100644 --- a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md +++ b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md @@ -17,7 +17,9 @@ import windowAnimationManager from '@ohos.animation.windowAnimationManager' setController(controller: WindowAnimationController): void -Sets a window animation controller. +Sets a window animation controller. For details about the controller, see [WindowAnimationController](#windowanimationcontroller). + +Before using other APIs of **windowAnimationManager**, you must call this API to set a window animation controller. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -31,22 +33,38 @@ Sets a window animation controller. ```js var controller = { - onStartAppFromLauncher(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - console.log('onStartAppFromLauncher', startingWindowTarget); - }, - onStartAppFromRecent(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - console.log('onStartAppFromRecent', startingWindowTarget); + onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onStartAppFromRecent(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromRecent, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onStartAppFromOther(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromOther, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); }, - onStartAppFromOther(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - console.log('onStartAppFromOther', startingWindowTarget); + onAppTransition(fromWindowTarget: windowAnimationManager.WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onAppTransition, the fromWindowTarget is: ' + fromWindowTarget); + console.log('onAppTransition, the toWindowTarget is: ' + toWindowTarget); + finishCallback.onAnimationFinish(); }, - onAppTransition(fromWindowTarget: WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + onMinimizeWindow(minimizingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onMinimizeWindow, the minimizingWindowTarget is: ' + minimizingWindowTarget); + finishCallback.onAnimationFinish(); }, - onMinimizeWindow(minimizingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + onCloseWindow(closingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onCloseWindow, the closingWindowTarget is: ' + closingWindowTarget); + finishCallback.onAnimationFinish(); }, - onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + onScreenUnlock(finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onScreenUnlock called'); + finishCallback.onAnimationFinish(); }, - onScreenUnlock(finishCallback: WindowAnimationFinishedCallback): void { + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void{ + console.log('onWindowAnimationTargetsUpdate, the fullScreenWindowTarget is: ' + fullScreenWindowTarget); + console.log('onWindowAnimationTargetsUpdate, the floatingWindowTargets are: ' + floatingWindowTargets); } } @@ -73,9 +91,39 @@ Minimizes the window that displays the animation. This API uses an asynchronous ```js var target: WindowAnimationTarget = undefined; var controller = { - onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { - target = fullScreenWindowTarget; - }, + onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onStartAppFromRecent(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromRecent, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onStartAppFromOther(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromOther, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onAppTransition(fromWindowTarget: windowAnimationManager.WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onAppTransition, the fromWindowTarget is: ' + fromWindowTarget); + console.log('onAppTransition, the toWindowTarget is: ' + toWindowTarget); + finishCallback.onAnimationFinish(); + }, + onMinimizeWindow(minimizingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onMinimizeWindow, the minimizingWindowTarget is: ' + minimizingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onCloseWindow(closingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onCloseWindow, the closingWindowTarget is: ' + closingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onScreenUnlock(finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onScreenUnlock called'); + finishCallback.onAnimationFinish(); + }, + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void{ + console.log('onWindowAnimationTargetsUpdate, the fullScreenWindowTarget is: ' + fullScreenWindowTarget); + console.log('onWindowAnimationTargetsUpdate, the floatingWindowTargets are: ' + floatingWindowTargets); + } } windowAnimationManager.setController(controller) @@ -119,9 +167,39 @@ Minimizes the window that displays the animation. This API uses a promise to ret ```js var target: WindowAnimationTarget = undefined; var controller = { - onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { - target = fullScreenWindowTarget; - }, + onStartAppFromLauncher(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromLauncher, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onStartAppFromRecent(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromRecent, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onStartAppFromOther(startingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onStartAppFromOther, the startingWindowTarget is: ' + startingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onAppTransition(fromWindowTarget: windowAnimationManager.WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onAppTransition, the fromWindowTarget is: ' + fromWindowTarget); + console.log('onAppTransition, the toWindowTarget is: ' + toWindowTarget); + finishCallback.onAnimationFinish(); + }, + onMinimizeWindow(minimizingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onMinimizeWindow, the minimizingWindowTarget is: ' + minimizingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onCloseWindow(closingWindowTarget: windowAnimationManager.WindowAnimationTarget, finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onCloseWindow, the closingWindowTarget is: ' + closingWindowTarget); + finishCallback.onAnimationFinish(); + }, + onScreenUnlock(finishCallback: windowAnimationManager.WindowAnimationFinishedCallback): void { + console.log('onScreenUnlock called'); + finishCallback.onAnimationFinish(); + }, + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: windowAnimationManager.WindowAnimationTarget, floatingWindowTargets: Array): void{ + console.log('onWindowAnimationTargetsUpdate, the fullScreenWindowTarget is: ' + fullScreenWindowTarget); + console.log('onWindowAnimationTargetsUpdate, the floatingWindowTargets are: ' + floatingWindowTargets); + } } windowAnimationManager.setController(controller) @@ -137,7 +215,7 @@ promise.then((data) => { ## WindowAnimationController -Implements the window animation controller. +Implements the window animation controller. When creating a **WindowAnimationController** object, you must implement all callbacks in the object. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -156,13 +234,7 @@ Called when an application is started from the home screen. **Example** -```js -var controller = { - onStartAppFromLauncher(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - console.log('onStartAppFromLauncher', startingWindowTarget); - } -} -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ### onStartAppFromRecent @@ -179,13 +251,7 @@ Called when an application is started from the recent task list. **Example** -```js -var controller = { - onStartAppFromRecent(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - console.log('onStartAppFromRecent', startingWindowTarget); - } -} -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ### onStartAppFromOther @@ -202,13 +268,7 @@ Called when an application is started from a place other than the home screen an **Example** -```js -var controller = { - onStartAppFromOther(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - console.log('onStartAppFromOther', startingWindowTarget); - } -} -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ### onAppTransition @@ -226,14 +286,7 @@ Called during application transition. **Example** -```js -var controller = { - onAppTransition(fromWindowTarget: WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, - finishCallback: WindowAnimationFinishedCallback): void { - console.log('onAppTransition', fromWindowTarget); - } -} -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ### onMinimizeWindow @@ -250,13 +303,7 @@ Called when a window is minimized. **Example** -```js -var controller = { - onMinimizeWindow(minimizingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - console.log('onMinimizeWindow', minimizingWindowTarget); - } -} -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ### onCloseWindow @@ -273,13 +320,7 @@ Called when a window is closed. **Example** -```js -var controller = { - onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - console.log('onCloseWindow', closingWindowTarget); - } -} -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ### onScreenUnlock @@ -295,13 +336,7 @@ Called when the screen is unlocked. **Example** -```js -var controller = { - onScreenUnlock(finishCallback: WindowAnimationFinishedCallback): void { - console.log('onScreenUnlock'.); - } -} -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ### onWindowAnimationTargetsUpdate @@ -318,15 +353,7 @@ Called when the window that displays the animation is updated. **Example** -```js -var controller = { - onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { - console.log('onWindowAnimationTargetsUpdate'.); - } -} - -windowAnimationManager.setController(controller) -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ## WindowAnimationFinishedCallback Implements a callback that is invoked when the animation is finished. @@ -341,13 +368,7 @@ Called when the animation is finished. **Example** -```js -var controller = { - onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { - finishCallback.onAnimationFinish(); - } -} -``` +For details, see the sample code under [windowAnimationManager.setController](#windowanimationmanagersetcontroller). ## WindowAnimationTarget Defines a window to display animation. diff --git a/en/application-dev/reference/apis/js-apis-workScheduler.md b/en/application-dev/reference/apis/js-apis-workScheduler.md index 725b313ba88bedca924f0f5f1d2f6166308d2b8f..d897bc91717348ee8addd00751741f83cc77c345 100644 --- a/en/application-dev/reference/apis/js-apis-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-workScheduler.md @@ -8,12 +8,13 @@ The system executes Work Scheduler tasks at an appropriate time, subject to the > > - 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. +> - For details about the constraints on the Work Scheduler usage, see [Work Scheduler Overview](../../task-management/work-scheduler-overview.md). ## Modules to Import ```js -import workScheduler from '@ohos.workScheduler' +import workScheduler from '@ohos.workScheduler'; ``` ## workScheduler.startWork @@ -53,7 +54,7 @@ Instructs the **WorkSchedulerService** to add the specified task to the executio } } var res = workScheduler.startWork(workInfo); - console.info("workschedulerLog res:" + res); + console.info(`workschedulerLog res: ${res}`); ``` ## workScheduler.stopWork @@ -94,7 +95,7 @@ Instructs the **WorkSchedulerService** to stop the specified task. } } var res = workScheduler.stopWork(workInfo, false); - console.info("workschedulerLog res:" + res); + console.info(`workschedulerLog res: ${res}`); ``` ## workScheduler.getWorkStatus @@ -116,10 +117,10 @@ Obtains the latest task status. This API uses an asynchronous callback to return ```js workScheduler.getWorkStatus(50, (err, res) => { if (err) { - console.info('workschedulerLog getWorkStatus failed, because:' + err.code); + console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`); } else { for (let item in res) { - console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]); + console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); } } }); @@ -149,10 +150,10 @@ Obtains the latest task status. This API uses a promise to return the result. ```js workScheduler.getWorkStatus(50).then((res) => { for (let item in res) { - console.info('workschedulerLog getWorkStatus success,' + item + ' is:' + res[item]); + console.info(`workschedulerLog getWorkStatus success, ${item} is: ${res[item]}`); } }).catch((err) => { - console.info('workschedulerLog getWorkStatus failed, because:' + err.code); + console.info(`workschedulerLog getWorkStatus failed, because: ${err.code}`); }) ``` @@ -167,7 +168,7 @@ Obtains all tasks associated with this application. This API uses an asynchronou | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return all tasks associated with the current application.| +| callback | AsyncCallback\ | Yes | Callback used to return all tasks associated with the current application. | **Return value** @@ -180,9 +181,9 @@ Obtains all tasks associated with this application. This API uses an asynchronou ```js workScheduler.obtainAllWorks((err, res) =>{ if (err) { - console.info('workschedulerLog obtainAllWorks failed, because:' + err.code); + console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`); } else { - console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res)); + console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); } }); ``` @@ -198,15 +199,15 @@ Obtains all tasks associated with this application. This API uses a promise to r | Type | Description | | -------------------------------------- | ------------------------------ | -| Promise> | Promise used to return all tasks associated with the current application.| +| Promise> | Promise used to return all tasks associated with the current application. | **Example** ```js workScheduler.obtainAllWorks().then((res) => { - console.info('workschedulerLog obtainAllWorks success, data is:' + JSON.stringify(res)); + console.info(`workschedulerLog obtainAllWorks success, data is: ${JSON.stringify(res)}`); }).catch((err) => { - console.info('workschedulerLog obtainAllWorks failed, because:' + err.code); + console.info(`workschedulerLog obtainAllWorks failed, because: ${err.code}`); }) ``` @@ -221,7 +222,7 @@ Stops and cancels all tasks associated with the current application. ```js let res = workScheduler.stopAndClearWorks(); - console.info("workschedulerLog res:" + res); + console.info(`workschedulerLog res: ${res}`); ``` ## workScheduler.isLastWorkTimeOut @@ -249,9 +250,9 @@ Checks whether the last execution of the specified task timed out. This API uses ```js workScheduler.isLastWorkTimeOut(500, (err, res) =>{ if (err) { - console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code); + console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`); } else { - console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res); + console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); } }); ``` @@ -280,10 +281,10 @@ Checks whether the last execution of the specified task timed out. This API uses ```js workScheduler.isLastWorkTimeOut(500) .then(res => { - console.info('workschedulerLog isLastWorkTimeOut success, data is:' + res); + console.info(`workschedulerLog isLastWorkTimeOut success, data is: ${res}`); }) .catch(err => { - console.info('workschedulerLog isLastWorkTimeOut failed, because:' + err.code); + console.info(`workschedulerLog isLastWorkTimeOut failed, because: ${err.code}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index 067897c8c6f4d3292683d63b4288a7fc987c578c..5aa129293c705d4c8c9ce5eaf78ac2a6f7960662 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -8,7 +8,7 @@ The worker thread is an independent thread running in parallel with the main thr ## Modules to Import -``` +```js import worker from '@ohos.worker'; ``` @@ -28,10 +28,11 @@ Provides options that can be set for the **Worker** instance to create. **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description | -| ---- | --------- | ---- | ---- | ---------------------- | -| type | "classic" | Yes | Yes | Mode in which the worker thread executes the script.| -| name | string | Yes | Yes | Name of the worker thread. | +| Name | Type | Readable| Writable| Description | +| ------ | --------- | ---- | ---- | ---------------------- | +| type | "classic" | Yes | Yes | Mode in which the worker thread executes the script.| +| name | string | Yes | Yes | Name of the worker thread. | +| shared | boolean | Yes | Yes | Whether the worker can be shared.| ## Worker @@ -51,7 +52,7 @@ A constructor used to create a **Worker** instance. | Name | Type | Mandatory| Description | | --------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| scriptURL | string | Yes | URL of the script to be executed by the Worker thread. The script is stored in the **workers** directory, which is in the same directory as the **pages** directory of the new DevEco Studio project. If the **workers** directory does not exist, you need to create it.| +| scriptURL | string | Yes | URL of the script to be executed by the worker thread.
In the FA or stage model, DevEco Studio creates a **Worker** project in either of the following scenarios:
(a) The **workers** directory is at the same level as the **pages** directory.
(b) The **workers** directory is at a different level from the **pages** directory. | options | [WorkerOptions](#workeroptions) | No | Options that can be set for the **Worker** instance. | **Return value** @@ -62,11 +63,69 @@ A constructor used to create a **Worker** instance. **Example** +```js +import worker from '@ohos.worker'; +// Create a worker thread. + +// In the FA model, the workers and pages directories are at the same level. +const workerFAModel01 = new worker.Worker("workers/worker.js", {name:"first worker"}); +// In the FA model, the workers and pages directories are at different levels. +const workerFAModel02 = new worker.Worker("../workers/worker.js", {name:"first worker"}); + +// In the stage model, the workers and pages directories are at the same level. +const workerStageModel01 = new worker.Worker('entry/ets/workers/worker.ts'); +// In the stage model, the workers and pages directories are at different levels. +const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts'); + +// scriptURL—— Description of "entry/ets/workers/worker.ts". +// entry is the value of the name attribute under module in the module.json5 file. +// ets indicates the programming language in use. +``` +Depending on whether the works and pages directories are at the same level, you may need to configure the **buildOption** attribute in the **build-profile.json5** file. + +(1) If the workers and pages directories are at the same level, the configuration is optional. +In the FA model: + +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/MainAbility/workers/worker.ts" + ] + } + } +``` +In the stage model: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/worker.ts" + ] + } + } +``` +(2) If the workers and pages directories are at different levels, the configuration is mandatory. +In the FA model: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/workers/worker.ts" + ] + } + } +``` +In the stage model: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/pages/workers/worker.ts" + ] + } + } ``` -const workerInstance = new worker.Worker("workers/worker.js", {name:"first worker"}); -``` - - ### postMessage postMessage(message: Object, options?: PostMessageOptions): void @@ -84,13 +143,11 @@ Sends a message to the worker thread. The message data is transferred using the **Example** -``` +```js const workerInstance = new worker.Worker("workers/worker.js"); + workerInstance.postMessage("hello world"); -``` -``` -const workerInstance= new worker.Worker("workers/worker.js"); var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` @@ -113,8 +170,8 @@ Adds an event listener for the worker instance. **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.on("alert", (e)=>{ console.log("alert listener callback"); }) @@ -138,7 +195,7 @@ Adds an event listener for the worker thread and removes the event listener afte **Example** -``` +```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); @@ -163,7 +220,7 @@ Removes an event listener for the worker thread. **Example** -``` +```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.off("alert"); ``` @@ -179,9 +236,9 @@ Terminates the worker thread to stop it from receiving messages. **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.terminate() +```js +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.terminate(); ``` @@ -201,10 +258,10 @@ Defines the event handler to be called when the worker thread exits. The handler **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onexit = function(e) { - console.log("onexit") + console.log("onexit"); } ``` @@ -225,17 +282,17 @@ Defines the event handler to be called when an exception occurs during worker ex **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onerror = function(e) { - console.log("onerror") + console.log("onerror"); } ``` ### onmessage -onmessage?: (event: MessageEvent) => void +onmessage?: (event: MessageEvent\) => void Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread. @@ -249,17 +306,19 @@ Defines the event handler to be called when the host thread receives a message s **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onmessage = function(e) { - console.log("onerror") + // e: MessageEvent. The usage is as follows: + // let data = e.data; + console.log("onmessage"); } ``` ### onmessageerror -onmessageerror?: (event: MessageEvent) => void +onmessageerror?: (event: MessageEvent\) => void Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. @@ -273,10 +332,10 @@ Defines the event handler to be called when the worker thread receives a message **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onmessageerror= function(e) { - console.log("onmessageerror") + console.log("onmessageerror"); } ``` @@ -301,8 +360,8 @@ Adds an event listener for the worker thread. **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") +```js +const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) @@ -326,9 +385,9 @@ Removes an event listener for the worker thread. **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.removeEventListener("alert") +```js +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.removeEventListener("alert"); ``` @@ -354,9 +413,9 @@ Dispatches the event defined for the worker thread. **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.dispatchEvent({type:"alert"}) +```js +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.dispatchEvent({type:"alert"}); ``` @@ -370,9 +429,9 @@ Removes all event listeners for the worker thread. **Example** -``` -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.removeAllListener({type:"alert"}) +```js +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.removeAllListener(); ``` @@ -383,7 +442,7 @@ Implements communication between the worker thread and the host thread. The **po ### postMessage -postMessage(message: Object, options?: PostMessageOptions): void +postMessage(messageObject: Object, options?: PostMessageOptions): void Sends a message to the host thread from the worker thread. @@ -398,22 +457,23 @@ Sends a message to the host thread from the worker thread. **Example** -``` +```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.postMessage("hello world") +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.postMessage("hello world"); workerInstance.onmessage = function(e) { - console.log("receive data from worker.js") + // let data = e.data; + console.log("receive data from worker.js"); } ``` - -``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ - parentPort.postMessage("receive data from main.js") + // let data = e.data; + parentPort.postMessage("receive data from main.js"); } ``` @@ -428,13 +488,12 @@ Terminates the worker thread to stop it from receiving messages. **Example** -``` +```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") -``` - +const workerInstance = new worker.Worker("workers/worker.js"); ``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; @@ -446,7 +505,7 @@ parentPort.onmessage = function(e) { ### onmessage -onmessage?: (event: MessageEvent) => void +onmessage?: (event: MessageEvent\) => void Defines the event handler to be called when the worker thread receives a message sent by the host thread through **worker.postMessage**. The event handler is executed in the worker thread. @@ -460,26 +519,25 @@ Defines the event handler to be called when the worker thread receives a message **Example** -``` +```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") -workerInstance.postMessage("hello world") -``` - +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.postMessage("hello world"); ``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { - console.log("receive main.js message") + console.log("receive main.js message"); } ``` ### onmessageerror -onmessageerror?: (event: MessageEvent) => void +onmessageerror?: (event: MessageEvent\) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. @@ -493,13 +551,12 @@ Defines the event handler to be called when the worker thread receives a message **Example** -``` +```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Worker("workers/worker.js") -``` - +const workerInstance = new worker.Worker("workers/worker.js"); ``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; @@ -557,7 +614,7 @@ Specifies the callback to invoke. **Example** -``` +```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); @@ -621,13 +678,12 @@ Defines the event handler to be called when an exception occurs during worker ex **Example** -``` +```js // main.js import worker from '@ohos.worker'; const workerInstance = new worker.Worker("workers/worker.js") ``` - -``` +```js // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort @@ -635,3 +691,98 @@ parentPort.onerror = function(e){ console.log("worker.js onerror") } ``` + +## Sample Code +### FA Model +```js +// main.js (The following assumes that the workers and pages directories are at the same level.) +import worker from '@ohos.worker'; +const workerInstance = new worker.Worker("workers/worker.ts"); +// Create either a .json or .ts file. +// const workerInstance = new worker.Worker("workers/worker.js"); + +workerInstance.postMessage("123"); +workerInstance.onmessage = function(e) { + let data = e.data; + console.log("main.js onmessage"); + // Call terminate after the worker thread receives messages. + workerInstance.terminate(); +} +// Call onexit. +workerInstance.onexit = function() { + console.log("main.js terminate"); +} +``` +```js +// worker.js +import worker from '@ohos.worker'; +const parentPort = worker.parentPort + +parentPort.onmessage = function(e) { + let data = e.data; + console.log("worker.js onmessage"); + parentPort.postMessage("123") +} + +parentPort.onerror= function(e) { + console.log("worker.js onerror"); +} +``` +Configuration of the **build-profile.json5** file: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/MainAbility/workers/worker.ts" + ] + } + } +``` +### Stage Model +```js +// main.js (The following assumes that the workers and pages directories are at different levels.) +import worker from '@ohos.worker'; +const workerInstance = new worker.Worker("entry/ets/pages/workers/worker.ts"); +// Create either a .json or .ts file. +// const workerInstance = new worker.Worker("entry/ets/pages/workers/worker.js"); +workerInstance.postMessage("123"); +workerInstance.onmessage = function(e) { + let data = e.data; + console.log("main.js onmessage"); + // Call terminate after the worker thread receives messages. + workerInstance.terminate(); +} +// Call onexit. +workerInstance.onexit = function() { + console.log("main.js terminate"); +} +``` +```js +// worker.js +import worker from '@ohos.worker'; +const parentPort = worker.parentPort + +parentPort.onmessage = function(e) { + let data = e.data; + console.log("worker.js onmessage"); + parentPort.postMessage("123") +} + +parentPort.onerror= function(e) { + console.log("worker.js onerror"); +} +``` +Configuration of the **build-profile.json5** file: +```json + "buildOption": { + "sourceOption": { + "workers": [ + "./src/main/ets/pages/workers/worker.ts" + ] + } + } +``` + +## Precautions +Currently, a maximum of seven workers can co-exist. +If the number of workers exceeds the upper limit, the error message "Too many workers, the number of workers exceeds the maximum." is displayed. diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index c7d28fe1bf86073c4453ea9e2cf9cbcb3698062e..078c1dc0009329300ab7458a7672b63c76271f61 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -32,9 +32,9 @@ A constructor used to create an **XmlSerializer** instance. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var bufView = new DataView(arrayBuffer); -var thatSer = new xml.XmlSerializer(bufView); +let arrayBuffer = new ArrayBuffer(1024); +let bufView = new DataView(arrayBuffer); +let thatSer = new xml.XmlSerializer(bufView); ``` @@ -56,9 +56,9 @@ Sets an attribute. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var bufView = new DataView(arrayBuffer); -var thatSer = new xml.XmlSerializer(bufView); +let arrayBuffer = new ArrayBuffer(1024); +let bufView = new DataView(arrayBuffer); +let thatSer = new xml.XmlSerializer(bufView); thatSer.setAttributes("importance", "high"); ``` @@ -80,9 +80,9 @@ Adds an empty element. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var bufView = new DataView(arrayBuffer); -var thatSer = new xml.XmlSerializer(bufView); +let arrayBuffer = new ArrayBuffer(1024); +let bufView = new DataView(arrayBuffer); +let thatSer = new xml.XmlSerializer(bufView); thatSer.addEmptyElement("b"); // => ``` @@ -98,9 +98,9 @@ Sets a declaration. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var bufView = new DataView(arrayBuffer); -var thatSer = new xml.XmlSerializer(bufView); +let arrayBuffer = new ArrayBuffer(1024); +let bufView = new DataView(arrayBuffer); +let thatSer = new xml.XmlSerializer(bufView); thatSer.setDeclaration() // => ; ``` @@ -122,8 +122,8 @@ Writes the start tag based on the given element name. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var thatSer = new xml.XmlSerializer(arrayBuffer); +let arrayBuffer = new ArrayBuffer(1024); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("notel"); thatSer.endElement();// => ''; ``` @@ -140,9 +140,9 @@ Writes the end tag of the element. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var bufView = new DataView(arrayBuffer); -var thatSer = new xml.XmlSerializer(bufView); +let arrayBuffer = new ArrayBuffer(1024); +let bufView = new DataView(arrayBuffer); +let thatSer = new xml.XmlSerializer(bufView); thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); thatSer.startElement("table"); thatSer.setAttributes("importance", "high"); @@ -169,8 +169,8 @@ Sets the namespace for an element tag. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var thatSer = new xml.XmlSerializer(arrayBuffer); +let arrayBuffer = new ArrayBuffer(1024); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.setDeclaration(); thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); thatSer.startElement("note"); @@ -194,8 +194,8 @@ Sets the comment. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var thatSer = new xml.XmlSerializer(arrayBuffer); +let arrayBuffer = new ArrayBuffer(1024); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); thatSer.setComment("Hi!"); thatSer.endElement(); // => '\r\n \r\n'; @@ -219,8 +219,8 @@ Sets CDATA attributes. **Example** ```js -var arrayBuffer = new ArrayBuffer(1028); -var thatSer = new xml.XmlSerializer(arrayBuffer); +let arrayBuffer = new ArrayBuffer(1028); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.setCDATA('root SYSTEM') // => ''; ``` @@ -242,8 +242,8 @@ Sets **Text**. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var thatSer = new xml.XmlSerializer(arrayBuffer); +let arrayBuffer = new ArrayBuffer(1024); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); thatSer.setAttributes("importance", "high"); thatSer.setText("Happy1"); @@ -268,8 +268,8 @@ Sets **DocType**. **Example** ```js -var arrayBuffer = new ArrayBuffer(1024); -var thatSer = new xml.XmlSerializer(arrayBuffer); +let arrayBuffer = new ArrayBuffer(1024); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.setDocType('root SYSTEM'); // => ''; ``` @@ -295,20 +295,20 @@ Creates and returns an **XmlPullParser** object. The **XmlPullParser** object pa **Example** ```js -var strXml = +let strXml = '' + '' + ' Happy' + ' Work' + ' Play' + ''; -var arrayBuffer = new ArrayBuffer(strXml.length*2); -var bufView = new Uint8Array(arrayBuffer); -var strLen = strXml.length; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; for (var i = 0; i < strLen; ++i) { bufView[i] = strXml.charCodeAt(i);// Set the ArrayBuffer mode. } -var that = new xml.XmlPullParser(arrayBuffer); +let that = new xml.XmlPullParser(arrayBuffer); ``` @@ -329,37 +329,37 @@ Parses XML information. **Example** ```js -var strXml = +let strXml = '' + '' + ' Happy' + ' Work' + ' Play' + ''; -var arrayBuffer = new ArrayBuffer(strXml.length*2); -var bufView = new Uint8Array(arrayBuffer); -var strLen = strXml.length; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; for (var i = 0; i < strLen; ++i) { bufView[i] = strXml.charCodeAt(i); } -var that = new xml.XmlPullParser(arrayBuffer); -var arrTag = {}; -var str = ""; -var i = 0; +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; function func(key, value){ arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); str += arrTag[i]; i++; return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. } -var options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} that.parse(options); console.log(str); // Output: // key:0 value:0key:2 value:1key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:3 value:1key:1 value:0 -// Notes: -// The key represents the current event type, and the value represents the depth of the current parsing. You can know the parsed event according to EVENTTYPE. For example, the result 'key: value' in this example means: -// 0(START_DOCUMENT):0(Parse to the START_DOCUMENT, and the depth is 0), 2(START_TAG):1(Parse to the START_TAG node, and the depth is 1), 10(WHITESPACE):1(Parse to the WHITESPACE space, and the depth is 1), 2(START_TAG):2(Parse to the START_TAG title, and the depth is 2), ... +// Note: +// key indicates the event type, and value indicates the parsing depth. You can learn the specific parsed event based on EVENTTYPE. In this example, key: value means: +// 0(START_DOCUMENT):0 (START_DOCUMENT is being parsed, and the depth is 0), 2(START_TAG):1 (START_TAG is being parsed, and the depth is 1), 10(WHITESPACE):1 (WHITESPACE is being parsed, and the depth is 1), 2(START_TAG):2 (START_TAG is being parsed, and the depth is 2), ... ``` @@ -387,7 +387,7 @@ Provides APIs to manage the parsed XML information. getColumnNumber(): number -Obtains the column line number, which starts from 1. +Obtains the column line number, starting from 1. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/arkui-js/js-components-basic-input.md b/en/application-dev/reference/arkui-js/js-components-basic-input.md index 1f10982593566d8ad21467a9613d260ab6e6a3ec..2ce4c7d3b07a6e8dbdcd47c4d3143ec8e4b285df 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-input.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-input.md @@ -20,44 +20,44 @@ Not supported In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. -| Name | Type | Default Value | Mandatory| Description | -| -------------------------------- | ----------------------- | --------- | ---- | ------------------------------------------------------------ | -| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded.| -| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | -| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | -| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name.| -| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text**, **email**, **date**, **time**, **number**, or **password**.| -| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit.| -| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard.| -| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG.| -| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | -| menuoptions5+ | Array<MeunOption> | - | No | Menu options displayed after users click the **More** button. | -| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**.| -| selectedstart6+ | number | -1 | No | Start position for text selection. | -| selectedend6+ | number | -1 | No | End position for text selection. | -| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | -| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | +| Name | Type | Default Value | Mandatory | Description | +| -------------------------------- | ----------------------- | ------------- | --------- | ---------------------------------------- | +| type | string | text
| No | Type of the input component. Available values include **text**, **email**, **date**, **time**, **number**, **password**, **button**, **checkbox**, and **radio**.
The **text**, **email**, **date**, **time**, **number**, and **password** types can be dynamically switched and modified.
The **button**, **checkbox**, and **radio** types cannot be dynamically modified.
- **button**: a button that can be clicked.
- **checkbox**: a check box.
- **radio**: a radio button that allows users to select one from multiple others with the same name.
- **text**: a single-line text field.
- **email**: a field used for an email address.
- **date**: date component, including the year, month, and day, but excluding time.
- **time**: time component, without the time zone.
- **number**: field for entering digits.
- **password**: password field, in which characters will be shielded. | +| checked | boolean | false | No | Whether the **\** component is selected. This attribute is valid only when **type** is set to **checkbox** or **radio**. | +| name | string | - | No | Name of the **\** component.
This attribute is mandatory when **type** is set to **radio**. | +| value | string | - | No | Value of the **\** component. When **type** is **radio**, this attribute is mandatory and the value must be unique for radio buttons with the same name. | +| placeholder | string | - | No | Content of the hint text. This attribute is available only when the component type is set to **text** \|email\|date\|time\|number\|**password**. | +| maxlength | number | - | No | Maximum number of characters that can be entered in the input box. The empty value indicates no limit. | +| enterkeytype | string | default | No | Type of the **Enter** key on the soft keyboard. The value cannot be dynamically updated.
Available values include:
- default
- next
- go
- done
- send
- search
Except for the **next** type, clicking the Enter key hides the soft keyboard. | +| headericon | string | - | No | Icon resource path before text input. This icon does not support click events and is unavailable for **button**, **checkbox**, and **radio** types. The supported icon image formats are JPG, PNG, and SVG. | +| showcounter5+ | boolean | false | No | Whether to display the character counter for an input box. This attribute takes effect only when **maxlength** is set. | +| menuoptions5+ | Array<MenuOption> | - | No | Menu options displayed after users click the **More** button. | +| autofocus6+ | boolean | false | No | Whether to automatically obtain focus.
This attribute setting does not take effect on the application home page. You can enable a text box on the home page to automatically obtain focus, by delaying the **focus** method call (for about 100–500 ms) in **onActive**. | +| selectedstart6+ | number | -1 | No | Start position for text selection. | +| selectedend6+ | number | -1 | No | End position for text selection. | +| softkeyboardenabled6+ | boolean | true | No | Whether to display the soft keyboard during editing. | +| showpasswordicon6+ | boolean | true | No | Whether to display the icon at the end of the password text box. This attribute is available only when **type** is set to **password**. | **Table 1** MenuOption5+ -| Name | Type | Description | -| ------- | ------ | ----------- | -| icon | string | Path of the icon for a menu option.| -| content | string | Text content of a menu option.| +| Name | Type | Description | +| ------- | ------ | ----------------------------------- | +| icon | string | Path of the icon for a menu option. | +| content | string | Text content of a menu option. | ## Styles In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. -| Name | Type | Default Value | Mandatory| Description | -| ------------------------ | -------------------------- | ---------- | ---- | ------------------------------------------------------------ | -| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | -| font-size | <length> | 16px | No | Font size of the single-line text box or button. | -| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| -| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**.| -| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md).| -| caret-color6+ | <color> | - | No | Color of the input cursor. | +| Name | Type | Default Value | Mandatory | Description | +| ------------------------ | ---------------- | ------------- | --------- | ---------------------------------------- | +| color | <color> | \#e6000000 | No | Font color of the single-line text box or button. | +| font-size | <length> | 16px | No | Font size of the single-line text box or button. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart. | +| placeholder-color | <color> | \#99000000 | No | Color of the hint text in the single-line text box. This attribute is available only when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | +| font-weight | number \| string | normal | No | Font weight of the single-line text box or button. For details, see **font-weight** of the [**\**](../arkui-js/js-components-basic-text.md) component. | +| caret-color6+ | <color> | - | No | Color of the caret. | ## Events @@ -65,30 +65,32 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. - When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the following events are supported. - | Name | Parameter | Description | + + | Name | Parameter | Description | | ------------------------- | ---------------------------------------- | ---------------------------------------- | - | change | {
 value: inputValue
 } | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered.| - | enterkeyclick | {
 value: enterKey
 } | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set.| - | translate5+ | {
 value: selectedText
 } | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned.| - | share5+ | {
 value: selectedText
 } | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned.| - | search5+ | {
 value: selectedText
 } | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned.| - | optionselect5+ | {
 index: optionIndex,
 value: selectedText
 } | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned.| - | selectchange6+ | {
start: number,
end: number
 } | Triggered when the text selection changes. | + | change | {
value: inputValue
} | Triggered when the content entered in the input box changes. The most recent content entered by the user is returned.
If you change the **value** attribute directly, this event will not be triggered. | + | enterkeyclick | {
value: enterKey
} | Triggered when the **Enter** key on the soft keyboard is clicked. The type of the **Enter** key is returned, which is of the number type. Available values are as follows:
- **2**: returned if **enterkeytype** is **go**.
- **3**: returned if **enterkeytype** is **search**.
- **4**: returned if **enterkeytype** is **send**.
- **5**: returned if **enterkeytype** is **next**.
- **6**: returned if **enterkeytype** is **default**, **done**, or is not set. | + | translate5+ | {
value: selectedText
} | Triggered when users click the translate button in the menu displayed after they select a text segment. The selected text content is returned. | + | share5+ | {
value: selectedText
} | Triggered when users click the share button in the menu displayed after they select a text segment. The selected text content is returned. | + | search5+ | {
value: selectedText
} | Triggered when users click the search button in the menu displayed after they select a text segment. The selected text content is returned. | + | optionselect5+ | {
index: optionIndex,
value: selectedText
} | Triggered when users click a menu option in the menu displayed after they select a text segment. This event is valid only when the **menuoptions** attribute is set. The option index and selected text content are returned. | + | selectchange6+ | {
start: number,
end: number
} | Triggered when the text selection changes. | - When **type** is set to **checkbox** or **radio**, the following events are supported. - | Name | Parameter | Description | - | ------ | ---------------------------------------- | ---------------------------------------- | - | change | {
 checked:true \| false 
} | Triggered when the checked status of the **checkbox** or **radio** button changes.| + + | Name | Parameter | Description | + | ------ | --------------------------------- | ---------------------------------------- | + | change | {
checked:true \| false
} | Triggered when the checked status of the **checkbox** or **radio** button changes. | ## Methods In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. -| Name | Parameter | Description | -| ------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| focus | {
 focus: true\|false
 }:
If **focus** is not passed, the default value **true** is used.| Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or password, the input method can be displayed or hidden.| -| showError | {
 error: string 
} | Displays the error message. This attribute is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**.| -| delete6+ | - | Deletes the text content based on the current cursor position when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**; deletes the last character and displays the cursor if the current input component does not have a cursor.| +| Name | Parameter | Description | +| ------------------- | ---------------------------------------- | ---------------------------------------- | +| focus | {
focus: true\|false
}:
If **focus** is not passed, the default value **true** is used. | Obtains or loses focus. When **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**, the input method can be displayed or collapsed. | +| showError | {
error: string
} | Displays the error message. This method is available when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**. | +| delete6+ | - | Deletes text based on the current caret position when **type** is set to **text**, **email**, **date**, **time**, **number**, or **password**; deletes the last character and displays the caret if the current input component does not have a caret. | ## Example diff --git a/en/application-dev/reference/arkui-js/js-components-basic-qrcode.md b/en/application-dev/reference/arkui-js/js-components-basic-qrcode.md index 2c353515b816e544af9948e162a9b18d1aefb815..5c3ac41ddfbe254387501071a8a21b3149495e91 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-qrcode.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-qrcode.md @@ -1,119 +1,67 @@ -# qrcode +# qrcode -The **** component is used to generate and display a QR code. +The **\** component is used to generate and display a QR code. -## Required Permissions +> **NOTE** +> +> This component is supported since API version 5. Updates will be marked with a superscript to indicate their earliest API version. + + +## Required Permissions None -## Child Components + +## Child Components Not supported -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

value

-

string

-

-

-

Yes

-

Content used to generate the QR code

-

type

-

string

-

rect

-

No

-

QR code type. Available values are as follows:

-
  • rect: rectangular QR code
  • circle: round QR code
-
- -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

color

-

<color>

-

#000000

-

No

-

QR code color

-

background-color

-

<color>

-

#ffffff

-

No

-

QR code background color

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- If the values of **width** and **height** are different, the smaller value is used as the length of the QR code. The generated QR code is center displayed. ->- If either **width** or **height** is set, the value is used as the length of the QR code. If neither of them is set, the default length is 200 px. - -## Events - -Events in [Universal Events](js-components-common-events.md) are supported. - -## Methods - -Methods in [Universal Methods](js-components-common-methods.md) are supported. - -## Example -``` +## Attributes + +In addition to the [universal attributes](../arkui-js/js-components-common-attributes.md), the following attributes are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ----- | ------ | ---- | ---- | ---------------------------------------- | +| value | string | - | Yes | Content used to generate the QR code. | +| type | string | rect | No | QR code type. Available values are as follows:
- **rect**: rectangular QR code
- **circle**: round QR code| + + +## Styles + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Default Value | Mandatory | Description | +| ---------------- | ------------- | -------- | ---- | -------- | +| color | <color> | \#000000 | No | Color of the QR code. | +| background-color | <color> | \#ffffff | No | Background color of the QR code.| + +> **NOTE** +> - If the values of **width** and **height** are different, the smaller value is used as the length of the QR code. The generated QR code is centered. +> +> +> - If either **width** or **height** is set, the value is used as the length of the QR code. If neither of them is set, the default length 200 px is used. +> + + +## Events + +The [universal events](../arkui-js/js-components-common-events.md) are supported. + +## Methods + +The [universal methods](../arkui-js/js-components-common-methods.md) are supported. + + +## Example + +```html
+ Value + 123 Type Color @@ -127,7 +75,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported.
``` -``` +```css /* xxx.css */ .container { width: 100%; @@ -146,10 +94,11 @@ select{ } ``` -``` +```js /* index.js */ export default { data: { + qr_value:'', qr_type: 'rect', qr_size: '300px', qr_col: '#87ceeb', @@ -176,5 +125,4 @@ export default { } ``` -![](figures/12.gif) - +![12](figures/12.gif) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-select.md b/en/application-dev/reference/arkui-js/js-components-basic-select.md index 98b7075a6b76bf36a92f480f5b897bef73f42939..32aab0871d34f16e5740a03247fb9d3c373e3c42 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-select.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-select.md @@ -1,83 +1,52 @@ -# select - -The **** component provides a drop-down list that allows users to select among multiple options. - -## Required Permissions - -None - -## Child Component - -The **<[option](js-components-basic-option.md)\>** child component is supported. - -## Attributes - -Attributes in [Universal Attributes](js-components-common-attributes.md) are supported. - -## Styles - -In addition to the styles in [Universal Styles](js-components-common-styles.md), the following styles are supported. - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

font-family

-

string

-

sans-serif

-

No

-

Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font that exists in the system or the font specified by Custom Font Styles in the family is selected as the font for the text.

-
- -## Events - -In addition to the events in [Universal Events](js-components-common-events.md), the following events are supported. - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{newValue: newValue}

-

Triggered after a value is selected from the drop-down list. The value of newValue is the attribute value of the child component option.

-
- ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->- The **** component does not support the **click** event. - -## Method - -Methods in [Universal Methods](js-components-common-methods.md) are supported. - -## Example Code +# select -``` +The **** component provides a drop-down list that allows users to select among multiple options. + +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. + + +## Child Components + +The **<[option](js-components-basic-option.md)\>** child component is supported. + + +## Attributes + +The [universal attributes](../arkui-js/js-components-common-attributes.md) are supported. + + +## Ad Asset + +In addition to the [universal styles](../arkui-js/js-components-common-styles.md), the following styles are supported. + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| font-family | string | No | Font family, in which fonts are separated by commas (,). The first font in the family or the specified [custom font](./js-components-common-customizing-font.md) is used for the text.
Default value: **sans-serif**| + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + +| Name | Parameter | Description | +| ------ | ------------------------- | ------------------------------------------------------------ | +| change | {newValue: newValue} | Triggered when an option is selected from the drop-down list to return an object. The value of **newValue** is the value of the selected option.| + +> **NOTE** +> +> The **\ @@ -94,7 +63,7 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. ``` -``` +```css /* xxx.css */ .container { display: flex; @@ -103,5 +72,13 @@ Methods in [Universal Methods](js-components-common-methods.md) are supported. } ``` -![](figures/en-us_image_0000001152588538.png) +```js +// ×××.js +export default { + changeFruit(e){ + console.log("newValue:" + e.newValue) + } +} +``` +![en-us_image_0000001152588538](figures/en-us_image_0000001152588538.png) diff --git a/en/application-dev/reference/arkui-js/js-components-basic-web.md b/en/application-dev/reference/arkui-js/js-components-basic-web.md index 7130a68b89c88a8e02cc9872a0eaa29d17807105..0342d75b5b9183f396ab4fec35c212de5ea9617d 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-web.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-web.md @@ -1,7 +1,8 @@ # web The **\** component displays web page content. ->![](../../public_sys-resources/icon-note.gif) **NOTE** -> This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. +>**NOTE** +> +>This component is supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. ## Required Permissions ohos.permission.INTERNET, required only for accessing online web pages. @@ -25,6 +26,7 @@ Universal style settings are not supported. ## Events The following events are supported. + | Name| Parameter| Description| | -------- | -------- | -------- | | pagestart | {url: string} | Triggered when web page loading starts.| @@ -33,12 +35,13 @@ The following events are supported. ## Methods The following methods are supported. + | Name| Parameter| Description| | -------- | -------- | -------- | | reload | - | Reloads a page.| ## Example -``` +```html
@@ -46,7 +49,7 @@ The following methods are supported.
``` -``` +```js // xxx.js export default { reloadWeb() { diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md index 8a29479f73e396ee3b4d7a591025ce538b70967e..edf0d3afa3412cb67b3d97f38036218f46e1de33 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvas.md @@ -1,171 +1,88 @@ -# canvas +# canvas -The **** component is used for customizing drawings. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component is used for customizing drawings. + +## Required Permissions None -## Child Components + +## Child Component Not supported -## Attributes - -Attributes in [Universal Attributes](js-components-common-attributes.md) are supported. - -## Styles - -Styles in [Universal Styles](js-components-common-styles.md) are supported. - -## Events - -Events in [Universal Events](js-components-common-events.md) are supported. - -## Methods - -In addition to the methods in [Universal Methods](js-components-common-methods.md), the following events are supported. - -### getContext - -getContext\(type: '2d', options?: ContextAttrOptions\): CanvasRendering2dContext - -Obtains the canvas drawing context. This API cannot be called in **onInit** or **onReady**. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

Yes

-

The value is set to '2d', indicating that a 2D drawing object is returned. This object can be used to draw rectangles, texts, and images on the canvas component.

-

options6+

-

ContextAttrOptions

-

No

-

Whether to enable anti-aliasing. By default, anti-aliasing is disabled.

-
- - **Table 1** ContextAttrOptions - - - - - - - - - - - - -

Name

-

Type

-

Description

-

antialias

-

boolean

-

Whether to enable anti-aliasing. The default value is false.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

CanvasRenderingContext2D

-

2D drawing object, which can be used to draw rectangles, images, and texts on the canvas component.

-
- - -### toDataURL6+ - -toDataURL\(type?: string, quality?: number\): string + +## Attributes + +The [universal attributes](../arkui-js/js-components-common-attributes.md) are supported. + + +## Styles + +The [universal styles](../arkui-js/js-components-common-styles.md) are supported. + + +## Events + +The [universal events](../arkui-js/js-components-common-events.md) are supported. + + +## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + + +### getContext + +getContext(type: '2d', options?: ContextAttrOptions): CanvasRendering2dContext + +Obtains the canvas drawing context. This API cannot be called in **onInit** or **onReady**. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------------------ | ---- | ---------------------------------------- | +| type | string | Yes | Object type. The value is set to **'2d'**, indicating that a 2D drawing object is returned. This object can be used to draw rectangles, texts, and images on the canvas component.| +| options6+ | ContextAttrOptions | No | Whether to enable anti-aliasing. By default, anti-aliasing is disabled. | + +**Table 1** ContextAttrOptions + +| Name | Type | Description | +| --------- | ------- | ------------------- | +| antialias | boolean | Whether to enable anti-aliasing. The default value is **false**.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------------------- | +| [CanvasRenderingContext2D](../arkui-js/js-components-canvas-canvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts, on the canvas component. | + +### toDataURL6+ + +toDataURL(type?: string, quality?: number): string Generates a URL containing image display information. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

No

-

Image format. The default value is image/png.

-

quality

-

number

-

No

-

Image quality, which ranges from 0 to 1, when the image format is image/jpeg or image/webp. If the set value is beyond the value range, the default value 0.92 is used.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

string

-

Image URL.

-
- - -## Example +**Parameters** -``` +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------------------------------------- | +| type | string | No | Image format. The default value is **image/png**. | +| quality | number | No | Image quality, which ranges from 0 to 1, when the image format is **image/jpeg** or **image/webp**. If the set value is beyond the value range, the default value **0.92** is used.| + +**Return value** + +| Type | Description | +| ------ | --------- | +| string | Image URL.| + +## Example + +```html
@@ -173,7 +90,7 @@ Generates a URL containing image display information.
``` -``` +```js // xxx.js export default { handleClick() { @@ -184,4 +101,3 @@ export default { } } ``` - diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md index 7a94f110d4680dbd6115fbab80684f2287086722..9bc724d26a7610fa4b7fdbd48b21811a2f472cf2 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasgradient.md @@ -4,7 +4,7 @@ > > This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -**CanvasGradient** provides a gradient object. +**CanvasGradient** provides a gradient object. ## addColorStop @@ -20,6 +20,7 @@ Adds a color stop for the **CanvasGradient** object based on the specified offse | color | string | Gradient color to set. | **Example** + ```html
diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md index 0747f7fa8f9b9800ff315dc6f0102736cbd00ab6..4100f9429985f1df7dd1e52087c842f128496226 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-canvasrenderingcontext2d.md @@ -48,25 +48,25 @@ ## Attributes -| Name | Type | Default Value | Description | -| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | -| [fillStyle](#fillstyle) | \ \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | - | Style to fill an area.
- When the type is **\**, this parameter indicates the color of the filling area.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method. | -| [lineWidth](#linewidth) | number | - | Line width. | -| [strokeStyle](#strokestyle) | \ \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | - | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method. | -| [lineCap](#linecap) | string | butt | Style of the specified line endpoint. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.| -| [lineJoin](#linejoin) | string | miter | Style of the intersection point between line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.| -| [miterLimit](#miterlimit) | number | 10 | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet. | -| [font](#font) | string | "normal normal 14px sans-serif" | Font style.
Syntax: ctx.font="font-style font-weight font-size font-family"5+
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**. | -| [textAlign](#textalign) | string | left | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
In the **ltr** layout mode, the value **start** equals **left**. In the **rtl** layout mode, the value **start** equals **right**.| -| [textBaseline](#textbaseline) | string | alphabetic | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
- **ideographic**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.| -| [globalAlpha](#globalalpha) | number | - | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | -| [lineDashOffset](#linedashoffset) | number | 0.0 | Offset of the dashed line. The precision is float. | -| [globalCompositeOperation](#globalcompositeoperation) | string | source-over | Composition operation type. Available values are as follows: **source-over**, **source-atop**, **source-in**, **source-out**, **destination-over**, **destination-atop**, **destination-in**, **destination-out**, **lighter**, copy, and **xor**. For details, see [Operation types](#globalcompositeoperation).| -| [shadowBlur](#shadowblur) | number | 0.0 | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float. | -| [shadowColor](#shadowcolor) | <color> | - | Shadow color. | -| [shadowOffsetX](#shadowoffsetx) | number | - | X-axis shadow offset relative to the original object. | -| [shadowOffsetY](#shadowoffsety) | number | - | Y-axis shadow offset relative to the original object. | -| [imageSmoothingEnabled](#imagesmoothingenabled6)6+ | boolean | true | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite. | +| Name | Type | Description | +| ---------------------------------------- | ---------------------------------------- | ---------------------------------------- | +| [fillStyle](#fillstyle) | <color> \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | Style to fill an area.
- When the type is **\**, this parameter indicates the color of the filling area.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method.| +| [lineWidth](#linewidth) | number | Line width. | +| [strokeStyle](#strokestyle) | <color> \| [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md) \| CanvasPattern | Stroke style.
- When the type is **\**, this parameter indicates the stroke color.
- When the type is **CanvasGradient**, this parameter indicates a gradient object, which is created using the **createLinearGradient()** method.
- When the type is **CanvasPattern**, this parameter indicates a canvas pattern, which is created using the **createPattern()** method.| +| [lineCap](#linecap) | string | Style of the specified line endpoint. The options are as follows:
- **butt**: The endpoints of the line are squared off.
- **round**: The endpoints of the line are rounded.
- **square**: The endpoints of the line are squared off, and each endpoint has added a rectangle whose length is the same as the line thickness and whose width is half of the line thickness.
Default value: **butt**| +| [lineJoin](#linejoin) | string | Style of the intersection point between line segments. The options are as follows:
- **round**: The intersection is a sector, whose radius at the rounded corner is equal to the line width.
- **bevel**: The intersection is a triangle. The rectangular corner of each line is independent.
- **miter**: The intersection has a miter corner by extending the outside edges of the lines until they meet. You can view the effect of this attribute in **miterLimit**.
Default value: **miter**| +| [miterLimit](#miterlimit) | number | Maximum miter length. The miter length is the distance between the inner corner and the outer corner where two lines meet.
Default value: **10** | +| [font](#font) | string | Font style.
Syntax: ctx.font="font-style font-weight font-size font-family"5+
- (Optional) **font-style**: font style. Available values are **normal** and **italic**.
- (Optional) **font-weight**: font weight. Available values are as follows: **normal**, **bold**, **bolder**, **lighter**, **100**, **200**, **300**, **400**, **500**, **600**, **700**, **800**, **900**.
- (Optional) **font-size**: font size and row height. The unit can only be pixels.
- (Optional) **font-family**: font family. Available values are **sans-serif**, **serif**, and **monospace**.
Default value: **"normal normal 14px sans-serif"**| +| [textAlign](#textalign) | string | Text alignment mode. Available values are as follows:
- **left**: The text is left-aligned.
- **right**: The text is right-aligned.
- **center**: The text is center-aligned.
- **start**: The text is aligned with the start bound.
- **end**: The text is aligned with the end bound.
In the **ltr** layout mode, the value **start** equals **left**. In the **rtl** layout mode, the value **start** equals **right**.
Default value: **left**| +| [textBaseline](#textbaseline) | string | Horizontal alignment mode of text. Available values are as follows:
- **alphabetic**: The text baseline is the normal alphabetic baseline.
- **top**: The text baseline is on the top of the text bounding box.
- **hanging**: The text baseline is a hanging baseline over the text.
- **middle**: The text baseline is in the middle of the text bounding box.
- **ideographic**: The text baseline is the ideographic baseline. If a character exceeds the alphabetic baseline, the ideographic baseline is located at the bottom of the excessive character.
- **bottom**: The text baseline is at the bottom of the text bounding box. Its difference from the ideographic baseline is that the ideographic baseline does not consider letters in the next line.
Default value: **alphabetic**| +| [globalAlpha](#globalalpha) | number | Opacity.
**0.0**: completely transparent.
**1.0**: completely opaque. | +| [lineDashOffset](#linedashoffset) | number | Offset of the dashed line. The precision is float.
Default value: **0.0** | +| [globalCompositeOperation](#globalcompositeoperation) | string | Composition operation type. Available values are as follows: **source-over**, **source-atop**, **source-in**, **source-out**, **destination-over**, **destination-atop**, **destination-in**, **destination-out**, **lighter**, copy, and **xor**. For details, see [Operation types](#globalcompositeoperation).
Default value: **ource-over**| +| [shadowBlur](#shadowblur) | number | Blur level during shadow drawing. A larger value indicates a more blurred effect. The precision is float.
Default value: **0.0**| +| [shadowColor](#shadowcolor) | <color> | Shadow color. | +| [shadowOffsetX](#shadowoffsetx) | number | X-axis shadow offset relative to the original object. | +| [shadowOffsetY](#shadowoffsety) | number | Y-axis shadow offset relative to the original object. | +| [imageSmoothingEnabled](#imagesmoothingenabled6)6+ | boolean | Whether to adjust the image smoothness during image drawing. The value **true** means to enable this feature, and **false** means the opposite.
Default value: **true**| ### fillStyle @@ -380,7 +380,8 @@ export default { ### globalCompositeOperation -Operation types +Enumerates the operation types. + | Value | Description | | ---------------- | ------------------------ | | source-over | Displays the new drawing above the existing drawing. This attribute is used by default. | @@ -425,7 +426,7 @@ export default { } ``` - ![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) +![en-us_image_0000001213192781](figures/en-us_image_0000001213192781.png) In the above example, the blue rectangle represents the new drawing, and the red rectangle represents the existing drawing. @@ -571,6 +572,7 @@ fillRect(x: number, y: number, width:number, height: number): void Fills a rectangle on the canvas. **Parameters** + | Name | Type | Description | | ------ | ------ | ------------- | | x | number | X-coordinate of the upper left corner of the rectangle.| @@ -607,6 +609,7 @@ clearRect(x: number, y: number, width:number, height: number): void Clears the content in a rectangle on the canvas. **Parameters** + | Name | Type | Description | | ------ | ------ | ------------- | | x | number | X-coordinate of the upper left corner of the rectangle.| @@ -645,6 +648,7 @@ strokeRect(x: number, y: number, width:number, height: number): void Draws a rectangle stroke on the canvas. **Parameters** + | Name | Type | Description | | ------ | ------ | ------------ | | x | number | X-coordinate of the upper left corner of the rectangle stroke.| @@ -681,6 +685,7 @@ fillText(text: string, x: number, y: number): void Draws filled text on the canvas. **Parameters** + | Name | Type | Description | | ---- | ------ | --------------- | | text | string | Text to draw. | @@ -716,6 +721,7 @@ strokeText(text: string, x: number, y: number): void Draws a text stroke on the canvas. **Parameters** + | Name | Type | Description | | ---- | ------ | --------------- | | text | string | Text to draw. | @@ -751,11 +757,13 @@ measureText(text: string): TextMetrics Returns a **TextMetrics** object used to obtain the width of specified text. **Parameters** + | Name | Type | Description | | ---- | ------ | ---------- | | text | string | Text to be measured.| **Return value** + | Type | Description | | ----------- | -------------------------------------- | | TextMetrics | Object that contains the text width. You can obtain the width by **TextMetrics.width**.| @@ -854,6 +862,7 @@ moveTo(x: number, y: number): void Moves a drawing path to a target position on the canvas. **Parameters** + | Name | Type | Description | | ---- | ------ | --------- | | x | number | X-coordinate of the target position.| @@ -890,6 +899,7 @@ lineTo(x: number, y: number): void Connects the current point to a target position using a straight line. **Parameters** + | Name | Type | Description | | ---- | ------ | --------- | | x | number | X-coordinate of the target position.| @@ -958,12 +968,14 @@ createPattern(image: Image, repetition: string): Object Creates a pattern for image filling based on a specified source image and repetition mode. **Parameters** + | Name | Type | Description | | ---------- | ------ | ---------------------------------------- | | image | Image | Source image. For details, see [Image](../arkui-js/js-components-canvas-image.md).| | repetition | string | Repetition mode. The value can be **"repeat"**, **"repeat-x"**, **"repeat-y"**, or **"no-repeat"**.| **Return value** + | Type | Description | | ------ | ----------------- | | Object | Pattern of image filling.| @@ -1000,6 +1012,7 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, Draws a cubic bezier curve on the canvas. **Parameters** + | Name | Type | Description | | ---- | ------ | -------------- | | cp1x | number | X-coordinate of the first parameter of the bezier curve.| @@ -1040,6 +1053,7 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void Draws a quadratic curve on the canvas. **Parameters** + | Name | Type | Description | | ---- | ------ | ----------- | | cpx | number | X-coordinate of the bezier curve parameter.| @@ -1078,6 +1092,7 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, Draws an arc on the canvas. **Parameters** + | Name | Type | Description | | ------------- | ------- | ---------- | | x | number | X-coordinate of the center point of the arc.| @@ -1117,6 +1132,7 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void Draws an arc based on the radius and points on the arc. **Parameters** + | Name | Type | Description | | ------ | ------ | --------------- | | x1 | number | X-coordinate of the first point on the arc.| @@ -1155,6 +1171,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number Draws an ellipse in the specified rectangular region on the canvas. **Parameters** + | Name | Type | Description | | ------------- | ------ | ------------------------------------ | | x | number | X-coordinate of the ellipse center. | @@ -1196,6 +1213,7 @@ rect(x: number, y: number, width: number, height: number): void Creates a rectangle on the canvas. **Parameters** + | Name | Type | Description | | ------ | ------ | ------------- | | x | number | X-coordinate of the upper left corner of the rectangle.| @@ -1292,6 +1310,7 @@ rotate(rotate: number): void Rotates a canvas clockwise around its coordinate axes. **Parameters** + | Name | Type | Description | | ------ | ------ | ---------------------------------------- | | rotate | number | Clockwise rotation angle. You can use **Math.PI / 180** to convert the angle to a radian.| @@ -1325,6 +1344,7 @@ scale(x: number, y: number): void Scales the canvas based on scale factors. **Parameters** + | Name | Type | Description | | ---- | ------ | ----------- | | x | number | Horizontal scale factor.| @@ -1367,6 +1387,7 @@ Defines a transformation matrix. To transform a graph, you only need to set para > - y' = skewX \* x + scaleY \* y + translateY **Parameters** + | Name | Type | Description | | ---------- | ------ | -------- | | scaleX | number | X-axis scale.| @@ -1411,6 +1432,7 @@ setTransform(scaleX: number, skewX: number, skewY: number, scale: number, transl Resets the existing transformation matrix and creates a new transformation matrix by using the same parameters as the **transform()** function. **Parameters** + | Name | Type | Description | | ---------- | ------ | -------- | | scaleX | number | X-axis scale.| @@ -1452,6 +1474,7 @@ translate(x: number, y: number): void Moves the origin of the coordinate system. **Parameters** + | Name | Type | Description | | ---- | ------ | -------- | | x | number | X-axis translation.| @@ -1487,6 +1510,7 @@ createPath2D(path: Path2D, cmds: string): Path2D Creates a **Path2D** object. **Parameters** + | Name | Type | Description | | ---- | ------ | -------------- | | path | Path2D | **Path2D** object. | @@ -1494,10 +1518,9 @@ Creates a **Path2D** object. **Return value** -[Path2D object](../arkui-js/js-components-canvas-path2d.md) + [Path2D object](../arkui-js/js-components-canvas-path2d.md) **Example** - ```html
@@ -1534,6 +1557,7 @@ drawImage(image: Image | PixelMap, sx: number, sy: number, sWidth: number, sHeig Draws an image on the canvas. **Parameters** + | Name | Type | Description | | ------- | ------------------------------ | ---------------------------------------- | | image | Image \| PixelMap9+ | Image resource. For details, see [Image](../arkui-js/js-components-canvas-image.md) or [PixelMap](../apis/js-apis-image.md#pixelmap7).| @@ -1626,6 +1650,7 @@ createLinearGradient(x0: number, y0: number, x1: number, y1: number): Object Creates a linear gradient and returns a **CanvasGradient** object. For details, see [CanvasGradient](../arkui-js/js-components-canvas-canvasgradient.md). **Parameters** + | Name | Type | Description | | ---- | ------ | -------- | | x0 | number | X-coordinate of the start point.| @@ -1634,6 +1659,7 @@ Creates a linear gradient and returns a **CanvasGradient** object. For details, | y1 | number | Y-coordinate of the end point.| **Return value** + | Type | Description | | ------ | ---------------------- | | Object | Created **CanvasGradient** object.| @@ -1675,6 +1701,7 @@ createRadialGradient(x0: number, y0: number, r0: number, x1: number, y1: number, Creates a radial gradient and returns a **CanvasGradient** object. **Parameters** + | Name | Type | Description | | ---- | ------ | ----------------- | | x0 | number | X-coordinate of the center of the start circle. | @@ -1685,6 +1712,7 @@ Creates a radial gradient and returns a **CanvasGradient** object. | r1 | number | Radius of the end circle, which must be a non-negative finite number.| **Return value** + | Type | Description | | ------ | ---------------------- | | Object | Created **CanvasGradient** object.| @@ -1726,6 +1754,7 @@ createImageData(width: number, height: number, imageData: Object): Object Creates an **ImageData** object. For details, see [ImageData](../arkui-js/js-components-canvas-imagedata.md). **Parameters** + | Name | Type | Description | | --------- | ------ | ----------------- | | width | number | Width of the **ImageData** object. | @@ -1733,6 +1762,7 @@ Creates an **ImageData** object. For details, see [ImageData](../arkui-js/js-com | imagedata | Object | **ImageData** object with the same width and height copied from the original **ImageData** object.| **Return value** + | Type | Description | | ------ | ----------------- | | Object | Created **ImageData** object.| @@ -1764,6 +1794,7 @@ getImageData(sx: number, sy: number, sw: number, sh: number): Object Obtains the **ImageData** object created with the pixels within the specified area on the canvas. **Parameters** + | Name | Type | Description | | ---- | ------ | --------------- | | sx | number | X-coordinate of the upper left corner of the output area.| @@ -1772,6 +1803,7 @@ Obtains the **ImageData** object created with the pixels within the specified ar | sh | number | Height of the output area. | **Return value** + | Type | Description | | ------ | ----------------------- | | Object | **ImageData** object that contains pixels in the specified area on the canvas.| @@ -1802,6 +1834,7 @@ putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: Puts the **ImageData** onto a rectangular area on the canvas. **Parameters** + | Name | Type | Description | | ----------- | ------ | ----------------------------- | | imagedata | Object | **ImageData** object with pixels to put onto the canvas. | @@ -1888,6 +1921,7 @@ setLineDash(segments: Array): void Sets the dash line style. **Parameters** + | Name | Type | Description | | -------- | ----- | -------------------- | | segments | Array | An array describing the interval of alternate line segments and length of spacing.| @@ -1922,6 +1956,7 @@ getLineDash(): Array Obtains the dash line style. **Return value** + | Type | Description | | ----- | ------------------------ | | Array | An array describing the interval of alternate line segments and length of spacing.| @@ -1952,6 +1987,7 @@ transferFromImageBitmap(bitmap: ImageBitmap): void Displays the specified **ImageBitmap** object. **Parameters** + | Name | Type | Description | | ------ | ----------- | ------------------ | | bitmap | ImageBitmap | **ImageBitmap** object to display.| diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-offscreencanvas.md b/en/application-dev/reference/arkui-js/js-components-canvas-offscreencanvas.md index ff809fb5f91c182738670f03821508e6de31e301..16a15bb2edfbd402b9065980bdee6a3357c5d4f1 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-offscreencanvas.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-offscreencanvas.md @@ -1,190 +1,87 @@ -# OffscreenCanvas - ->![](../../public_sys-resources/icon-note.gif) **NOTE:** ->**OffscreenCanvas** is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - -**OffscreenCanvas** defines a canvas object that can be rendered off the screen. - -## Attributes - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

width

-

number

-

Width of the OffscreenCanvas object.

-

height

-

number

-

Height of the OffscreenCanvas object.

-
- -## Methods - -### getContext - -getContext\(type: string, options?: CanvasRenderingContext2DSettings\): OffscreenCanvasRenderingContext2D - -Obtains the **OffscreenCanvas** context. This method returns a 2D drawing object. - -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

contextId

-

string

-

Yes

-

The value can only be "2d".

-

options

-

CanvasRenderingContext2DSettings

-

No

-

2D drawing object, which can be used to draw rectangles, images, and texts, on the OffscreenCanvas.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

OffscreenCanvasRenderingContext2D

-

2D drawing object, which can be used to draw rectangles, images, and texts, on the OffscreenCanvas.

-
- - -### toDataURL - -toDataURL\(type?: string, quality?:number\): +# OffscreenCanvas + +> **NOTE** +> +> The APIs of this component are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. + + +**OffscreenCanvas** defines a canvas object that can be rendered off the screen. + + +## Attributes + +| Name | Type | Description | +| ------ | ------ | --------------------------- | +| width | number | Width of the **OffscreenCanvas** object.| +| height | number | Height of the **OffscreenCanvas** object.| + + +## Methods + + +### getContext + +getContext(type: string, options?: CanvasRenderingContext2DSettings): OffscreenCanvasRenderingContext2D + +Obtains the **OffscreenCanvas** context. This API returns a 2D drawing object. + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | ---------------------- | +| contextId | string | Yes | Context ID. The value can only be **"2d"**. | +| options | [CanvasRenderingContext2DSettings](../arkui-js/js-offscreencanvasrenderingcontext2d.md) | No | 2D drawing object, which can be used to draw rectangles, images, and texts, on the **OffscreenCanvas**. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------------- | +| [OffscreenCanvasRenderingContext2D](../arkui-js/js-offscreencanvasrenderingcontext2d.md) | 2D drawing object, which can be used to draw rectangles, images, and texts, on the **OffscreenCanvas**. | + + +### toDataURL + +toDataURL(type?: string, quality?:number): Generates a URL containing image display information. -- Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

type

-

string

-

No

-

Image format. The default value is image/png.

-

quality

-

number

-

No

-

Image quality, which ranges from 0 to 1, when the image format is image/jpeg or image/webp. If the set value is beyond the value range, the default value 0.92 is used.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

string

-

Image URL.

-
- - -### transferToImageBitmap - -transferToImageBitmap\(\): ImageBitmap - -Creates an **ImageBitmap** object on the most recently rendered image of the **OffscreenCanvas**. - -- Return values - - - - - - - - - - -

Type

-

Description

-

ImageBitmap

-

Pixel data rendered on the OffscreenCanvas.

-
- - -## Example +**Parameters** -``` +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------------------------------------- | +| type | string | No | Image format. The default value is **image/png**. | +| quality | number | No | Image quality, which ranges from 0 to 1, when the image format is **image/jpeg** or **image/webp**. If the set value is beyond the value range, the default value **0.92** is used.| + +**Return value** + +| Type | Description | +| ------ | --------- | +| string | Image URL.| + + +### transferToImageBitmap + +transferToImageBitmap(): ImageBitmap + +Creates an **ImageBitmap** object on the most recently rendered image of the **OffscreenCanvas**. + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------- | +| [ImageBitmap](../arkui-js/js-components-canvas-imagebitmap.md) | Pixel data rendered on the **OffscreenCanvas**.| + + +## Example + +```html
``` -``` +```js //xxx.js export default { onShow() { @@ -202,4 +99,3 @@ export default { } } ``` - diff --git a/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md b/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md index f0d8345a3bac2c96c323c94731e3244b1ff8df77..f5f4179442862246d1c3171dde95879efbe4c532 100644 --- a/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md +++ b/en/application-dev/reference/arkui-js/js-components-canvas-path2d.md @@ -19,6 +19,7 @@ Adds a path to this path. | path | Object | Path to be added to this path. | **Example** + ```html
@@ -60,6 +61,7 @@ Sets the path transformation matrix. | translateY | number | Translation distance of the y-axis. | **Example** + ```html
@@ -130,6 +132,7 @@ Moves the current coordinate point of the path to the target point, without draw | y | number | Y-coordinate of the target point. | **Example** + ```html
@@ -216,6 +219,7 @@ Draws a cubic bezier curve on the canvas. | y | number | Y-coordinate of the end point on the bezier curve. | **Example** + ```html
@@ -256,6 +260,7 @@ Draws a quadratic curve on the canvas. | y | number | Y-coordinate of the end point on the bezier curve. | **Example** + ```html
@@ -298,6 +303,7 @@ Draws an arc on the canvas. | anticlockwise | boolean | Whether to draw the arc counterclockwise. | **Example** + ```html
@@ -338,6 +344,7 @@ Draws an arc based on the radius and points on the arc. | radius | number | Radius of the arc. | **Example** + ```html
@@ -381,6 +388,7 @@ Draws an ellipse in the specified rectangular region. | anticlockwise | number | Whether to draw the ellipse in the anticlockwise direction. The value **0** indicates clockwise and the value **1** indicates anticlockwise. This parameter is optional. The default value is **0**. | **Example** + ```html
@@ -420,6 +428,7 @@ Creates a rectangle. | height | number | Height of the rectangle. | **Example** + ```html
diff --git a/en/application-dev/reference/arkui-js/js-components-common-animation.md b/en/application-dev/reference/arkui-js/js-components-common-animation.md index 24676a73232a85ae609e6ea07b403bdd78961bb4..72969d608a86f4ce8fdf8ad2eb95431e18b93528 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-animation.md +++ b/en/application-dev/reference/arkui-js/js-components-common-animation.md @@ -6,20 +6,20 @@ Components support dynamic rotation, translation, and scaling effects. These eff > > The initial APIs of this component are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -| Name | Type | Default Value | Description | -| ------------------------- | ------------------------------------------------------------ | ------------------------------------- | ------------------------------------------------------------ | -| transform-origin | string6+ \| \ \| \ string6+ \| \ \| \ | center center | Origin position of the transformed element. The unit can be px or a percentage (relative to the animation target component). If only one value is specified, the other one is **50%**. The available values for the first string are **left**, **center**, and **right**. The available values for the second string are **top**, **center**, and **bottom**.
Example:
transform-origin: 200px 30%
transform-origin: 100px topt
ransform-origin: center center | -| transform | string | - | Translation, rotation, and scaling attributes.
For details, see **transform**. | -| animation6+ | string | 0s ease 0s 1 normal none running none | Animation attributes in the format of **duration \| timing-function \| delay \| iteration-count \| direction \| fill-mode \| play-state \| name**. The order of the parameters is not specified, but the **duration** and **delay** parameters are parsed based on where they are placed. | -| animation-name | string | - | @keyframes rule. For details, see **@keyframes**. | -| animation-delay | \