diff --git a/CODEOWNERS b/CODEOWNERS index 63dee6787f1bea126047ec423f333ad3de9fe5e9..52fd5a5404d2809b3e021c09d932c9f4a9cc050f 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -85,6 +85,7 @@ zh-cn/device-dev/subsystems/subsys-security-sigverify.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-rightmanagement.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-communicationverify.md @duangavin123_admin zh-cn/device-dev/subsystems/subsys-security-devicesecuritylevel.md @duangavin123_admin +zh-cn/device-dev/subsystems/subsys-security-huks-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-appspawn.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-bootstrap.md @Austin23 zh-cn/device-dev/subsystems/subsys-boot-faqs.md @Austin23 @@ -243,7 +244,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-storage.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-system-storage.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-settings.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-settings.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-document.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-environment.md @qinxiaowang @@ -261,15 +262,18 @@ zh-cn/application-dev/reference/apis/js-apis-sms.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-telephony-data.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-net-connection.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-http.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-request.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-request.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-socket.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-tagSession.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-rpc.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-wifi.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-wifiext.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-accessibility.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-wifi.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-wifiext.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-accessibility.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hichecker.md @zengyawen @@ -277,34 +281,34 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-system-time.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-system-time.md @bmeangel +zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @bmeangel zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-battery-info.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-brightness.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-device-info.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-battery-info.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-brightness.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-device-info.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-device-manager.md zh-cn/application-dev/reference/apis/js-apis-geolocation.md @sun-yue14 zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-power.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-runninglock.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-power.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-runninglock.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-sensor.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-thermal.md @sun-yue14 +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-vibrator.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-appAccount.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @sun-yue14 -zh-cn/application-dev/reference/apis/js-apis-osAccount.md @sun-yue14 +zh-cn/application-dev/reference/apis/js-apis-appAccount.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-osAccount.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-convertxml.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-process.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-uri.md @zengyawen @@ -344,4 +348,7 @@ zh-cn/application-dev/quick-start/syscap.md @RayShih zh-cn/application-dev/napi/napi-guidelines.md @RayShih zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen \ No newline at end of file +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 \ No newline at end of file diff --git a/README.md b/README.md index 7e19add93fd8c1818e41387bfd4c8ad34efa2b71..0b1fe4ea284ed5df055c0031d96d3cfb759948a3 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,11 @@ This repository stores device and application development documents provided by - OpenHarmony 3.1 Release. [Learn more](en/release-notes/OpenHarmony-v3.1-release.md) + This version is upgraded to OpenHarmony 3.1.1 LTS. [Learn more](en/release-notes/OpenHarmony-v3.1.1-release.md) + - OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md) - This version is upgraded to OpenHarmony 3.0.3 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.3-LTS.md) + This version is upgraded to OpenHarmony 3.0.5 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.5-LTS.md) - OpenHarmony 2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md) @@ -41,10 +43,14 @@ OpenHarmony_v1.x_release: OpenHarmony v1.1.4 LTS. [Learn more](en/release-notes/ Third-party license: [Third-Party Open-Source Software and License Notice](en/contribute/third-party-open-source-software-and-license-notice.md) -## How to Contribute +## Contribution A great open-source project wouldn't be possible without the hard work of many contributors. We'd like to invite anyone from around the world to [participate](en/contribute/how-to-contribute.md) in this exciting journey, and we're grateful for your time, passion, and efforts! You can evaluate available documents, make simple modifications, provide feedback on document quality, and contribute your original content. For details, see [Documentation Contribution](en/contribute/documentation-contribution.md). Excellent contributors will be awarded and the contributions will be publicized in the developer community. + +- Mail list: docs@openharmony.io + +- Zulip group: documentation_sig \ No newline at end of file diff --git a/docker/Dockerfile b/docker/Dockerfile index 70560a93c1dd890bf8b6ff1d9f03d2e778adbfe0..46dd8e3d0fe4ee945af2b5e0154ee0b876850d1a 100755 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -35,14 +35,15 @@ RUN sed -i "s@http://.*archive.ubuntu.com@http://repo.huaweicloud.com@g" /etc/ap && pip3 install six --upgrade --ignore-installed six \ && mkdir -p /home/tools \ && mkdir -p /home/tools/gn \ - && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/clang/10.0.1-62608/linux/llvm.tar.gz \ + && wget -P /home/tools https://repo.huaweicloud.com/openharmony/compiler/clang/12.0.1-530132/linux/clang-530132-linux-x86_64.tar.bz2 \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/hc-gen/0.65/linux/hc-gen-0.65-linux.tar \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/gcc_riscv32/7.3.0/linux/gcc_riscv32-linux-7.3.0.tar.gz \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/ninja/1.9.0/linux/ninja.1.9.0.tar \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/gn/1717/linux/gn-linux-x86-1717.tar.gz \ && wget -P /home/tools https://mirrors.huaweicloud.com/nodejs/v14.15.4/node-v14.15.4-linux-x64.tar.xz \ && wget -P /home/tools https://hm-verify.obs.cn-north-4.myhuaweicloud.com/qemu-5.2.0.tar.xz \ - && tar -xvf /home/tools/llvm.tar.gz -C /home/tools \ + && tar -jxvf /home/tools/clang-530132-linux-x86_64.tar.bz2 -C /home/tools \ + && mv /home/tools/clang-530132 /home/tools/llvm \ && tar -xvf /home/tools/hc-gen-0.65-linux.tar -C /home/tools \ && tar -xvf /home/tools/gcc_riscv32-linux-7.3.0.tar.gz -C /home/tools \ && tar -xvf /home/tools/ninja.1.9.0.tar -C /home/tools \ diff --git a/en/application-dev/ability/fa-serviceability.md b/en/application-dev/ability/fa-serviceability.md index 75a605c39be73f29e1db8cecf988535c5495ee4a..48270359d9d49f9ea7d7111b021cd8b81da3df82 100644 --- a/en/application-dev/ability/fa-serviceability.md +++ b/en/application-dev/ability/fa-serviceability.md @@ -30,7 +30,7 @@ A Service ability is used to run tasks in the background, such as playing music }, onConnect(want) { console.log('ServiceAbility OnConnect'); - return null; + return new FirstServiceAbilityStub('test'); }, onDisconnect(want) { console.log('ServiceAbility OnDisConnect'); @@ -113,8 +113,6 @@ let promise = featureAbility.startAbility( Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. - - ### Connecting to a Local Service Ability If you need to connect a Service ability to a Page ability or to a Service ability in another application, you must first implement the **IAbilityConnection** API for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**. @@ -124,7 +122,7 @@ You can use either of the following methods to connect to a Service ability: 1. Using the IDL to automatically generate code - Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see [“Development Using TS” in OpenHarmony IDL Specifications and User Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/IDL/idl-guidelines.md#development-using-ts). + Use OpenHarmony Interface Definition Language (IDL) to automatically generate the corresponding client, server, and **IRemoteObject** code. For details, see “Development Using TS" in [OpenHarmony IDL Specifications and User Guide](../IDL/idl-guidelines.md). 2. Writing code in the corresponding file @@ -134,42 +132,37 @@ You can use either of the following methods to connect to a Service ability: ```javascript import prompt from '@system.prompt' - - let mRemote; - function onConnectCallback(element, remote){ - console.log('onConnectLocalService onConnectDone element: ' + element); - console.log('onConnectLocalService onConnectDone remote: ' + remote); - mRemote = remote; - if (mRemote == null) { - prompt.showToast({ - message: "onConnectLocalService not connected yet" - }); - return; - } - let option = new rpc.MessageOption(); - let data = new rpc.MessageParcel(); - let reply = new rpc.MessageParcel(); - data.writeInt(1); - data.writeInt(99); - mRemote.sendRequest(1, data, reply, option).then((result) => { - console.log('sendRequest success'); - let msg = reply.readInt(); + + var option = { + onConnect: function onConnectCallback(element, proxy) { + console.log(`onConnectLocalService onConnectDone`) + if (proxy === null) { + prompt.showToast({ + message: "Connect service failed" + }) + return + } + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + let option = new rpc.MessageOption() + data.writeInterfaceToken("connect.test.token") + proxy.sendRequest(0, data, reply, option) prompt.showToast({ - message: "onConnectLocalService connect result: " + msg, - duration: 3000 - }); - }).catch((e) => { - console.log('sendRequest error:' + e); - }); - - } - - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect Callback') - } - - function onFailedCallback(code){ - console.log('ConnectAbility onFailed Callback') + message: "Connect service success" + }) + }, + onDisconnect: function onDisconnectCallback(element) { + console.log(`onConnectLocalService onDisconnectDone element:${element}`) + prompt.showToast({ + message: "Disconnect service success" + }) + }, + onFailed: function onFailedCallback(code) { + console.log(`onConnectLocalService onFailed errCode:${code}`) + prompt.showToast({ + message: "Connect local service onFailed" + }) + } } ``` @@ -196,45 +189,28 @@ You can use either of the following methods to connect to a Service ability: ```javascript import rpc from "@ohos.rpc"; - - let mMyStub; - export default { - onStart() { - class MyStub extends rpc.RemoteObject{ - constructor(des) { - if (typeof des === 'string') { - super(des); - } - return null; - } - onRemoteRequest(code, data, reply, option) { - console.log("ServiceAbility onRemoteRequest called"); - if (code === 1) { - let op1 = data.readInt(); - let op2 = data.readInt(); - console.log("op1 = " + op1 + ", op2 = " + op2); - reply.writeInt(op1 + op2); - } else { - console.log("ServiceAbility unknown request code"); - } - return true; - } - } - mMyStub = new MyStub("ServiceAbility-test"); - }, - onCommand(want, startId) { - console.log('ServiceAbility onCommand'); - }, - onConnect(want) { - console.log('ServiceAbility OnConnect'); - return mMyStub; - }, - onDisconnect(want) { - console.log('ServiceAbility OnDisConnect'); - }, - onStop() { - console.log('ServiceAbility onStop'); - }, + + class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { + if (typeof des === 'string') { + super(des) + } else { + return + } + } + + onRemoteRequest(code: number, data: any, reply: any, option: any) { + console.log(printLog + ` onRemoteRequest called`) + if (code === 1) { + let string = data.readString() + console.log(printLog + ` string=${string}`) + let result = Array.from(string).sort().join('') + console.log(printLog + ` result=${result}`) + reply.writeString(result) + } else { + console.log(printLog + ` unknown request code`) + } + return true; } ``` @@ -253,40 +229,36 @@ The following code snippet shows how to implement the callbacks: ```ts import prompt from '@system.prompt' -let mRemote; -function onConnectCallback(element, remote){ - console.log('onConnectRemoteService onConnectDone element: ' + element); - console.log('onConnectRemoteService onConnectDone remote: ' + remote); - mRemote = remote; - if (mRemote == null) { - prompt.showToast({ - message: "onConnectRemoteService not connected yet" - }); - return; - } - let option = new rpc.MessageOption(); - let data = new rpc.MessageParcel(); - let reply = new rpc.MessageParcel(); - data.writeInt(1); - data.writeInt(99); - mRemote.sendRequest(1, data, reply, option).then((result) => { - console.log('sendRequest success'); - let msg = reply.readInt(); +var option = { + onConnect: function onConnectCallback(element, proxy) { + console.log(`onConnectRemoteService onConnectDone`) + if (proxy === null) { + prompt.showToast({ + message: "Connect service failed" + }) + return + } + let data = rpc.MessageParcel.create() + let reply = rpc.MessageParcel.create() + let option = new rpc.MessageOption() + data.writeInterfaceToken("connect.test.token") + proxy.sendRequest(0, data, reply, option) prompt.showToast({ - message: "onConnectRemoteService connect result: " + msg, - duration: 3000 - }); - }).catch((e) => { - console.log('sendRequest error:' + e); - }); -} - -function onDisconnectCallback(element){ - console.log('ConnectRemoteAbility onDisconnect Callback') -} - -function onFailedCallback(code){ - console.log('ConnectRemoteAbility onFailed Callback') + message: "Connect service success" + }) + }, + onDisconnect: function onDisconnectCallback(element) { + console.log(`onConnectRemoteService onDisconnectDone element:${element}`) + prompt.showToast({ + message: "Disconnect service success" + }) + }, + onFailed: function onFailedCallback(code) { + console.log(`onConnectRemoteService onFailed errCode:${code}`) + prompt.showToast({ + message: "Connect local service onFailed" + }) + } } ``` @@ -372,23 +344,25 @@ The following code snippet shows how the Service ability instance returns itself ```ts import rpc from "@ohos.rpc"; -class FirstServiceAbilityStub extends rpc.RemoteObject{ - constructor(des) { +class FirstServiceAbilityStub extends rpc.RemoteObject { + constructor(des: any) { if (typeof des === 'string') { - super(des); + super(des) } else { - return null; + return } } - onRemoteRequest(code, data, reply, option) { - console.log("ServiceAbility onRemoteRequest called"); + + onRemoteRequest(code: number, data: any, reply: any, option: any) { + console.log(printLog + ` onRemoteRequest called`) if (code === 1) { - let op1 = data.readInt(); - let op2 = data.readInt(); - console.log("op1 = " + op1 + ", op2 = " + op2); - reply.writeInt(op1 + op2); + let string = data.readString() + console.log(printLog + ` string=${string}`) + let result = Array.from(string).sort().join('') + console.log(printLog + ` result=${result}`) + reply.writeString(result) } else { - console.log("ServiceAbility unknown request code"); + console.log(printLog + ` unknown request code`) } return true; } diff --git a/en/application-dev/ability/stage-call.md b/en/application-dev/ability/stage-call.md index aaa9a9918345c52015969245c3bbba3efbb81048..6b5823e76db2c95190111a55b9d2ef43ddd2d946 100644 --- a/en/application-dev/ability/stage-call.md +++ b/en/application-dev/ability/stage-call.md @@ -19,7 +19,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r |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: CaleeCallBack): void|Callback invoked when the callee registers a method.| +|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.| @@ -28,7 +28,7 @@ The table below describes the ability call APIs. For details, see [Ability](../r ## 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. For details about the complete project code, see [Samples](#samples). +> 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. diff --git a/en/application-dev/database/Readme-EN.md b/en/application-dev/database/Readme-EN.md index 9f7ccd0d08e8683aca6e6c86ddef80f8e0e5aad4..a8aff91550cb265137a89d8718f6232c34e1aa43 100644 --- a/en/application-dev/database/Readme-EN.md +++ b/en/application-dev/database/Readme-EN.md @@ -3,12 +3,19 @@ - Distributed Data Service - [Distributed Data Service Overview](database-mdds-overview.md) - [Distributed Data Service Development](database-mdds-guidelines.md) + - Relational Database - [RDB Overview](database-relational-overview.md) - [RDB Development](database-relational-guidelines.md) + - Preferences - [Preferences Overview](database-preference-overview.md) - [Preferences Development](database-preference-guidelines.md) + - Distributed Data Object - [Distributed Data Object Overview](database-distributedobject-overview.md) - [Distributed Data Object Development](database-distributedobject-guidelines.md) + +- Data Share + - [DataShare Overview](database-datashare-overview.md) + - [DataShare Development](database-datashare-guidelines.md) diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..251c33fbc54aadba8aa07b92f0292ab86f322d70 --- /dev/null +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -0,0 +1,191 @@ +# DataShare Development +The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between the applications on the same device. + +## Available APIs + +**Table 1** APIs of the data provider + +|API|Description| +|:------|:------| +|onCreate?(want: Want, callback: AsyncCallback<void>): void|Called to initialize service logic when the data provider application is created, for example, when a database is created.| +|insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void|Inserts data into the database.| +|update?(uri: string, predicates: DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>): void|Updates data in the database.| +|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). + +**Table 2** APIs of the data consumer + +| API | Description | +| :----------------------------------------------------------- | :--------------------------------- | +| createDataShareHelper(context: Context, uri: string, callback: AsyncCallback<DataShareHelper>): void | Creates a **DataShareHelper** instance. | +| insert(uri: string, value: ValuesBucket, callback: AsyncCallback<number>): void | Inserts a single data record into the database. | +| update(uri: string, predicates: DataSharePredicates, value: ValuesBucket, callback: AsyncCallback<number>): void | Updates data in the database. | +| 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). + +## When to Use + +**DataShare** can be divided into the following: + +- Data provider: Implement functions of adding, deleting, modifying, and querying data, and opening files, and share data. +- Data consumer: Access the data provided by the provider using **DataShareHelper**. + +Examples are given below. + +### Data Provider Application Development (Only for System Applications) + +1. Import the dependencies. + + ```ts + import Extension from '@ohos.application.DataShareExtensionAbility' + import rdb from '@ohos.data.rdb'; + 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. + +3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. + + ```ts + let DB_NAME = "DB00.db"; + let TBL_NAME = "TBL00"; + let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; + + let rdbStore; + let result; + + export default class DataShareExtAbility extends Extension { + private rdbStore_; + + // Override the onCreate() API. + onCreate(want, callback) { + result = this.context.cacheDir + '/datashare.txt' + // Create an RDB. + rdb.getRdbStore(this.context, { + name: DB_NAME + }, 1, function (err, data) { + rdbStore = data; + rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { + console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err)); + }); + callback(); + }); + } + + // Override the query() API. + query(uri, predicates, columns, callback) { + if (predicates == null || predicates == undefined) { + console.info('invalid predicates'); + } + try { + rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) { + if (resultSet != undefined) { + console.info('resultSet.rowCount: ' + resultSet.rowCount); + } + if (callback != undefined) { + callback(err, resultSet); + } + }); + } catch (err) { + console.error('error' + err); + } + } + // Override other APIs as required. + // ... + }; + ``` + +4. Define **DataShareExtensionAbility** in **module.json5**. + + | Field| Description | + | ------------ | ------------------------------------------------------------ | + | "name" | Ability name, corresponding to the **ExtensionAbility** class name derived from **Ability**. | + | "type" | Ability type. The value is **dataShare**, indicating the development is based on the **Datashare** template.| + | "uri" | URI used for communication. It is the unique identifier for the client to connect to the server. | + | "visible" | Whether it is visible to other applications. Communication with other applications is allowed only when the value is **true**.| + + **module.json5 example** + + ```json + "extensionAbilities": [ + { + "srcEntrance": "./ets/DataShareExtAbility/DataShareExtAbility.ts", + "name": "DataShareExtAbility", + "icon": "$media:icon", + "description": "$string:description_datashareextability", + "type": "dataShare", + "uri": "datashare://com.samples.datasharetest.DataShare", + "visible": true + } + ] + ``` + +### Data Consumer Application Development + +1. Import basic dependencies. + + ```ts + import Ability from '@ohos.application.Ability' + import dataShare from '@ohos.data.dataShare' + import dataSharePredicates from '@ohos.data.dataSharePredicates' + ``` + +2. Define the URI string for communicating with the data provider. + + ```ts + // Different from the URI defined in the module.json5 file, the URI passed in the parameter has an extra slash (/), because there is a DeviceID parameter between the second and the third slash (/). + let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); + ``` + +2. 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)=>{ + 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. + + ```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("*"); + let people = new Array( + {"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); + }); + // Delete the specified 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); + }); + // Query data. + dsHelper.query(dseUri, da, valArray, (err,data) => { + console.log("dsHelper query result: " + data); + }); + ``` + diff --git a/en/application-dev/database/database-datashare-overview.md b/en/application-dev/database/database-datashare-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..857e9fa4205cd0545803643af1515da485b83d8a --- /dev/null +++ b/en/application-dev/database/database-datashare-overview.md @@ -0,0 +1,54 @@ +# DataShare Overview + +## Introduction + +The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between the applications on the same device. + +**DataShare** is used in application scenarios, such as contacts, short message service (SMS), and media gallery. However, not all data, such as accounts and passwords, can be accessed by other applications. Some data, such as SMS messages, can only be queried by other applications. **DataShare** provides a secure data sharing mechanism for applications. + +The data provider can directly use the **DataShare** framework to share data with other applications without complex encapsulation. The data consumer only needs to learn and use a set of interfaces because the data access mode does not vary with the data provisioning mode. This greatly reduces the learning time and development difficulty. + +## Basic Concepts + + +Before you get started, familiarize yourself with the following concepts: + + +- Data provider + + An application that provides data and implements related services. It is also called a producer or server. + +- Data consumer + + An application that accesses the data or services provided by a data provider. It is also called a client. + +- Value bucket (**ValuesBucket**) + + One or more data records stored in the form of key-value (KV) pairs. The keys are of the string type. The values can be of the number, string, Boolean, or Unit8Array type. + +- Result set + + A collection of query results. Flexible data access modes are provided for users to obtain data. + +- Predicate + + Conditions specified for updating, deleting, or querying data in the database. + +## Working Principles + +**Figure 1** DataShare mechanism + + +![](figures/en_DataShare.png) + +- The **DataShareExtAbility** module, as the data provider, implements data sharing between applications. +- The **DataShareHelper** module, as the data consumer, provides interfaces for accessing data, including adding, deleting, modifying, and querying data. +- The data consumer communicates with the data provider using inter-process communication (IPC). The data provider can be implemented through a database or other data storage. + +- The **ResultSet** module is implemented through shared memory. Share memory stores the result sets, and interfaces are provided to traverse result sets. + +## Constraints + +- **DataShare** is subject to the limitations on the database used by the data provider. For example, the supported data models, length of the keys and values, and maximum number of databases that can be accessed at a time by each application vary with the database in use. + +- The payloads of **ValuesBucket**, predicates, and result sets are restricted by IPC. diff --git a/en/application-dev/database/database-distributedobject-guidelines.md b/en/application-dev/database/database-distributedobject-guidelines.md index dde1feb495e9827ab1f0fd1fad903f71acb9cbb3..cfde2b66f2a3094355d6166bcaa4fb17856fbfaf 100644 --- a/en/application-dev/database/database-distributedobject-guidelines.md +++ b/en/application-dev/database/database-distributedobject-guidelines.md @@ -17,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance. **Table 1** API for creating a distributed data object instance | 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 **distributedObject** set.
- **DistributedObject**: returns the distributed object created.| ### Generating a Session ID @@ -35,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s **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 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.| ### Observing 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| 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.| ### Observing Online or Offline Status @@ -85,7 +85,11 @@ The following example shows how to implement a distributed data object synchroni ```js 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. Request the permission. + + Add the required permission in the **config.json** file. The sample code is as follows: + ``` { "module": { @@ -97,10 +101,11 @@ The following example shows how to implement a distributed data object synchroni } } ``` - 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: - ```js + 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: + + ``` import featureAbility from '@ohos.ability.featureAbility'; - + function grantPermission() { console.info('grantPermission'); let context = featureAbility.getContext(); @@ -108,11 +113,13 @@ The following example shows how to implement a distributed data object synchroni 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: @@ -130,7 +137,7 @@ The following example shows how to implement a distributed data object synchroni ```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"}]}); + parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]}); local_object.setSessionId(sessionId); // Remote object @@ -140,8 +147,10 @@ The following example shows how to implement a distributed data object synchroni // 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. +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. + The sample code is as follows: ```js @@ -152,26 +161,32 @@ The following example shows how to implement a distributed data object synchroni 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)); ``` -6. Modify object attributes.
The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). - +6. Modify object attributes. + + 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.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: + > ![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: + ```js // Supported modification. local_object.parent = {mother:"mom", father:"dad"}; @@ -179,13 +194,18 @@ The following example shows how to implement a distributed data object synchroni 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. - +7. Access the distributed data object. + + Obtain the distributed data object attribute, which is the latest data on the network. + The sample code is as follows: ```js console.info("name " + local_object["name"]); ``` -8. Unsubscribe from data changes.
You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. + +8. Unsubscribe from data changes. + + You can specify the callback to unregister. If you do not specify the callback, all data change callbacks of the distributed data object will be unregistered. The sample code is as follows: ```js @@ -194,6 +214,7 @@ The following example shows how to implement a distributed data object synchroni // Unregister all data change callbacks. local_object.off("change"); ``` + 9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. The sample code is as follows: ```js @@ -207,58 +228,62 @@ The following example shows how to implement a distributed data object synchroni 10. Save a distributed data object and revoke the data saving operation. - Callback - - ```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."); - }); - ``` -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. + + ``` + ​```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."); + }); + ​``` + ``` + + + +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. The sample code is as follows: - ```js + ```js // Unregister the specified status change callback. local_object.off("status", this.statusCallback); // Unregister all status change callbacks. local_object.off("status"); - ``` + ``` + 12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object. The sample code is as follows: ```js local_object.setSessionId(""); ``` -## Development Example - -The following example is provided for you to better understand the development of distributed data objects: - -- [Distributed Notepad](https://gitee.com/openharmony/distributeddatamgr_objectstore/tree/master/samples/distributedNotepad) - - -When an event of the Notepad app occurs on a device, such as a note is added, the tile or content of a note is changed, or the event list is cleared, the change will be synchronized to other devices in the trusted network. diff --git a/en/application-dev/database/database-mdds-guidelines.md b/en/application-dev/database/database-mdds-guidelines.md index c5608c6eabd526c38a87bd3907fba89fb1a11629..dd1594215a10d1c93c9825444253484ed8956e05 100644 --- a/en/application-dev/database/database-mdds-guidelines.md +++ b/en/application-dev/database/database-mdds-guidelines.md @@ -6,22 +6,20 @@ 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). -The table below describes the APIs provided by the OpenHarmony DDS module. **Table 1** APIs provided by the DDS -| Category | API | Description | -| ------------ | ------------- | ------------- | -| Creating a distributed database| createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void
createKVManager(config: KVManagerConfig): Promise<KVManager> | Creates a **KVManager** object for database management.| -| Obtaining a distributed KV store| getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void
getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> | Obtains the KV store with the specified **Options** and **storeId**.| -| Managing data in a distributed KV store| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback<void>): void
put(key: string, value: Uint8Array \| string \| number \| boolean): Promise<void> | Inserts and updates data.| -| Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback<void>): void
delete(key: string): Promise<void> | Deletes data. | -| Managing data in a distributed KV store| get(key: string, callback: AsyncCallback<Uint8Array \| string \| boolean \| number>): void
get(key: string): Promise<Uint8Array \| string \| boolean \| number> | Queries data. | -| Subscribing to changes in the distributed 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.| -| Synchronizing data across devices| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. | +| 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. | @@ -36,11 +34,14 @@ The following uses a single KV store as an example to describe the development p ``` 2. 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 = { @@ -62,9 +63,12 @@ The following uses a single KV store as an example to describe the development p 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. + (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: @@ -92,8 +96,9 @@ The following uses a single KV store as an example to describe the development p } ``` - > ![icon-note.gif](public_sys-resources/icon-note.gif) **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. + > **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. 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: @@ -104,7 +109,9 @@ The following uses a single KV store as an example to describe the development p ``` 5. Write data to 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: @@ -126,7 +133,9 @@ The following uses a single KV store as an example to describe the development p ``` 6. Query data in 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: @@ -152,7 +161,11 @@ The following uses a single KV store as an example to describe the development p 7. Synchronize data to other devices.
Select the devices in the same network and the synchronization mode to synchronize data. - The following is the sample code for data synchronization in a single KV store. **deviceIds** can be obtained by deviceManager by calling **getTrustedDeviceListSync()**, and **1000** indicates that the maximum delay time is 1000 ms. + > **NOTE** + > + > The APIs of the `deviceManager` module are system interfaces. + + The following is the sample code for synchronizing data in a single KV store: ```js import deviceManager from '@ohos.distributedHardware.deviceManager'; @@ -161,7 +174,7 @@ The following uses a single KV store as an example to describe the development p deviceManager.createDeviceManager("bundleName", (err, value) => { if (!err) { devManager = value; - // Obtain deviceIds. + // deviceIds is obtained by deviceManager by calling getTrustedDeviceListSync(). let deviceIds = []; if (devManager != null) { var devices = devManager.getTrustedDeviceListSync(); @@ -170,6 +183,7 @@ 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); @@ -177,7 +191,3 @@ The following uses a single KV store as an example to describe the development p } }); ``` -## Samples -The following samples are provided to help you better understand the distributed data development: -- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore) -- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData) diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index b56401dbedca72e76af3b15efdd63883885bf3d6..f6c7395339d66cb1c79bf71d424c15072f77f1b6 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -7,7 +7,7 @@ A relational database (RDB) store allows you to operate local data with or witho ## Available APIs -For details about RDB APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). +Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For details about the APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md). ### Creating or Deleting an RDB Store @@ -15,51 +15,48 @@ The table below describes the APIs available for creating and deleting an RDB st **Table 1** APIs for creating and deleting an RDB store -| API| Description| -| -------- | -------- | -|getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void| Obtains an RDB store. This API uses a callback to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: RDB version.
- **callback**: callback invoked to return the RDB store obtained.| -|getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements, and then call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: RDB version.| -|deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void> ): void | Deletes an RDB store. This API uses a callback to return the result.
- **context**: context of the application or function.
- **name**: RDB store to delete.
- **callback**: callback invoked to return the result.| -| deleteRdbStore(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: context of the application or function.
- **name**: RDB store to delete.| +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> | Obtains an RDB store. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: version of the RDB store.| +| deleteRdbStore(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: context of the application or function.
- **name**: name of the RDB store to delete.| ### Managing Data in an RDB Store The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store. -- **Inserting data** +- **Inserting Data** The RDB provides APIs for inserting data through a **ValuesBucket** in a data table. If the data is inserted, the row ID of the data inserted will be returned; otherwise, **-1** will be returned. - **Table 2** APIs for inserting data + **Table 2** API for inserting data - | Class| API| Description| - | -------- | -------- | -------- | - | RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback<number>):void | Inserts a row of data into a table. This API uses a callback to return the result.
- **table**: name of the target table.
- **values**: data to be inserted into the table.
- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.| - | 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.
- **table**: name of the target table.
- **values**: data to be inserted into the table.| + | 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.| -- **Updating data** +- **Updating Data** Call the **update()** method to pass new data and specify the update conditions by using **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned. - **Table 3** APIs for updating data + **Table 3** API for updating data - | Class| API| Description| - | -------- | -------- | -------- | - | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback<number>):void | Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a callback to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **predicates**: conditions for updating data.
- **callback**: callback invoked to return the number of rows updated.| - | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
- **values**: data to update, which is stored in a **ValuesBucket**.
- **predicates**: conditions for updating data.| + | Class | API | Description | + | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | update(values:ValuesBucket,predicates:RdbPredicates):Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data.
Return value: number of rows updated. | -- **Deleting data** +- **Deleting Data** Call the **delete()** method to delete data meeting the conditions specified by **RdbPredicates**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned. - **Table 4** APIs for deleting data + **Table 4** API for deleting data - | Class| API| Description| - | -------- | -------- | -------- | - | RdbStore | 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.
- **predicates**: conditions for deleting data.
- **callback**: callback invoked to return the number of rows updated.| - | 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.| + | 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. | -- **Querying data** + + +- **Querying Data** You can query data in an RDB store in either of the following ways: @@ -68,76 +65,48 @@ 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>, callback: AsyncCallback<ResultSet>): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This API uses a callback 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.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | Queries data in the RDB store based on the specified **RdbPredicates** object. 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>, callback: AsyncCallback<ResultSet>):void | Queries data in the RDB store using the specified SQL statement. This API uses a callback to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.
- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | Queries data in the RDB store using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | Class | API | Description | + | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | + | RdbStore | query(predicates:RdbPredicates,columns?:Array<string>):Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| + | RdbStore | querySql(sql:string,bindArgs?:Array<ValueType>):Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.| + | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicates** that specifies the query condition.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| ### Using Predicates The RDB provides **RdbPredicates** for you to set database operation conditions. +The following lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates). + **Table 6** APIs for using RDB store predicates -| Class| API| Description| -| -------- | -------- | -------- | -| RdbPredicates |inDevices(devices: Array\): RdbPredicates | Specifies remote devices on the network with RDB stores to be synchronized.
- **devices**: IDs of the remote devices on the network.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates |inAllDevices(): RdbPredicates | Connects to all remote devices on the network with RDB stores to be synchronized.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets the **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 specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **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 specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | beginWrap(): RdbPredicates | Adds a left parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a left parenthesis.| -| RdbPredicates | endWrap(): RdbPredicates | Adds a right parenthesis to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with a right parenthesis.| -| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the OR condition.| -| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** with the AND condition.| -| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string containing the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified string.| -| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that starts with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that ends with the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | isNotNull(field: string): RdbPredicates | Sets the **RdbPredicates** to match the field whose value is not null.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | like(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match a string that is similar to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | glob(field: string, value: string): RdbPredicates | Sets the **RdbPredicates** to match the specified string.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range.
- **field**: column name in the database table.
- **low**: minimum value that matches the **RdbPredicates**.
- **high**: maximum value that matches the **RdbPredicates**.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value.
- **field**: column name in the database table.
- **value**: value specified.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByAsc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in ascending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | orderByDesc(field: string): RdbPredicates | Sets the **RdbPredicates** to match the column with values sorted in descending order.
- **field**: column name in the database table.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | distinct(): RdbPredicates | Sets the **RdbPredicates** to filter out duplicate records.
- **RdbPredicates**: returns a **RdbPredicates** object that can filter out duplicate records.| -| RdbPredicates | limitAs(value: number): RdbPredicates | Sets the **RdbPredicates** to specify the maximum number of records.
- **value**: maximum number of records.
- **RdbPredicates**: returns a **RdbPredicates** object that can be used to set the maximum number of records.| -| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | Sets the **RdbPredicates** to specify the start position of the returned result.
- **rowOffset**: start position of the returned result. The value is a positive integer.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the start position of the returned result.| -| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | Sets the **RdbPredicates** to group rows that have the same value into summary rows.
- **fields**: names of the columns grouped for querying data.
- **RdbPredicates**: returns a **RdbPredicates** object that groups rows with the same value.| -| RdbPredicates | indexedBy(indexName: string): RdbPredicates | Sets the **RdbPredicates** to specify the index column.
- **indexName**: name of the index column.
- **RdbPredicates**: returns a **RdbPredicates** object that specifies the index column.| -| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| -| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range.
- **field**: column name in the database table.
- **value**: array of **ValueType** to match.
- **RdbPredicates**: returns a **RdbPredicates** object that matches the specified field.| +| 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.| + ### Using the Result Set -A result set can be regarded as a row of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. +A result set can be regarded as a row of data in the queried results. It allows you to traverse and access the data you have queried. + +For details about how to use result set APIs, see [Result Set](../reference/apis/js-apis-data-resultset.md). > **NOTICE**
> After a result set is used, you must call the **close()** method to close it explicitly. **Table 7** APIs for using the result set -| Class| API| Description| -| -------- | -------- | -------- | -| ResultSet | goTo(offset:number): boolean | Moves the result set forwards or backwards by the specified offset relative to its current position.| -| ResultSet | goToRow(position: number): boolean | Moves the result set to the specified row.| -| ResultSet | goToNextRow(): boolean | Moves the result set to the next row.| -| ResultSet | goToPreviousRow(): boolean | Moves the result set to the previous row.| -| ResultSet | getColumnIndex(columnName: string): number | Obtains the column index based on the specified column name.| -| ResultSet | getColumnName(columnIndex: number): string | Obtains the column name based on the specified column index.| -| ResultSet | goToFirstRow(): boolean | Checks whether the result set is located in the first row.| -| ResultSet | goToLastRow(): boolean | Checks whether the result set is located in the last row.| -| ResultSet | getString(columnIndex: number): string | Obtains the value in the specified column of the current row, in a string.| -| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the values in the specified column of the current row, in a byte array.| -| ResultSet | getDouble(columnIndex: number): number | Obtains the values in the specified column of the current row, in double.| -| ResultSet | isColumnNull(columnIndex: number): boolean | Checks whether the value in the specified column of the current row is null.| -| ResultSet | close(): void | Closes the result set.| +| 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. | @@ -147,68 +116,73 @@ A result set can be regarded as a row of data in the queried results. It allows **Setting Distributed Tables** -**Table 8** APIs for setting distributed tables +**Table 8** API for setting distributed tables -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore | setDistributedTables(tables: Array\, callback: AsyncCallback\): void | Sets a list of distributed tables. This API uses a callback to return the result.
- **tables**: names of the distributed tables to set.
- **callback**: callback invoked to return the result.| -| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets a list of distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.| **Obtaining the Distributed Table Name for a Remote Device** You can obtain the distributed table name for a remote device based on the local table name. The distributed table name can be used to query the RDB store of the remote device. -**Table 9** APIs for obtaining the distributed table name of a remote device +**Table 9** API for obtaining the distributed table name of a remote device -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore | obtainDistributedTableName(device: string, table: string, callback: AsyncCallback\): void | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses an asynchronous callback to return the result.
- **device**: remote device.
- **table**: local table name.
- **callback**: callback used to return the result. If the operation is successful, the distributed table name of the remote device will be returned. | -| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is used to query the RDB store of the remote device. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.| **Synchronizing Data Between Devices** -**Table 10** APIs for synchronizing data between devices +**Table 10** API for synchronizing data between devices -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates, callback: AsyncCallback\>): void | Synchronizes data between devices. This API uses a callback to return the result.
- **mode**: data synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized.
- **callback**: callback invoked to return the result. In the result, **string** indicates the device ID, and **number** indicates the synchronization status of each device. The value **0** indicates a success, and other values indicate a failure.| -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: data synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: data and devices to be synchronized. | +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| **Registering an RDB Store Observer** **Table 11** API for registering an observer -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore |on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void| Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.| **Unregistering an RDB Store Observer** **Table 12** API for unregistering an observer -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer to unregister.| +| Class | API | Description | +| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| RdbStore | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.
- **observer**: observer to unregister.| ### Backing Up and Restoring an RDB Store **Backing Up an RDB Store** -**Table 13** APIs for backing up an RDB store +**Table 13** API for backing up an RDB store -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore |backup(destName:string, callback: AsyncCallback<void>):void| Backs up an RDB store. This API uses an asynchronous callback to return the result.
- **destName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| -| 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.| +| 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.| **Restoring an RDB Store** -**Table 14** APIs for restoring an RDB store +**Table 14** API for restoring an RDB store + +| 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.| + +**Transaction** -| Class| API| Description| -| -------- | -------- | -------- | -| RdbStore |restore(srcName:string, callback: AsyncCallback<void>):void| Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.
- **srcName**: name of the RDB backup file.
- **callback**: callback invoked to return the result.| -| RdbStore |restore(srcName:string): Promise<void>| Restores an RDB store using a backup file. This API uses a promise to return the result.
- **srcName**: name of the RDB backup file.| +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. | ## How to Develop @@ -226,7 +200,7 @@ You can obtain the distributed table name for a remote device based on the local 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.') @@ -243,7 +217,7 @@ You can obtain the distributed table name for a remote device based on the local ```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) ``` @@ -270,17 +244,17 @@ You can obtain the distributed table name for a remote device based on the local const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) resultSet.close() }) - ``` + ``` 4. Set the distributed tables to be synchronized. (1) Add the following permission to the permission configuration file: - ```js + ```json "requestPermissions": - { - "name": "ohos.permission.DISTRIBUTED_DATASYNC" - } + { + "name": "ohos.permission.DISTRIBUTED_DATASYNC" + } ``` (2) Obtain the required permissions. @@ -321,7 +295,7 @@ You can obtain the distributed table name for a remote device based on the local promise.then((result) => { console.log('sync done.') for (let i = 0; i < result.length; i++) { - console.log('device=' + result[i][0] + ' status=' + result[i][1]) + console.log('device=' + result[i][0] + 'status=' + result[i][1]) } }).catch((err) => { console.log('sync failed') @@ -339,7 +313,7 @@ You can obtain the distributed table name for a remote device based on the local ```js function storeObserver(devices) { for (let i = 0; i < devices.length; i++) { - console.log('device=' + device[i] + ' data changed') + console.log('device=' + device[i] + 'data changed') } } try { @@ -361,8 +335,34 @@ You can obtain the distributed table name for a remote device based on the local let tableName = rdbStore.obtainDistributedTableName(deviceId, "test"); let resultSet = rdbStore.querySql("SELECT * FROM " + tableName) ``` - -8. Back up and restore an RDB store. + +8. Query data of a remote device. + + + (1) Construct a predicate object for querying distributed tables, and specify the remote distributed table name and the remote device. + + (2) Call the resultSet() API to obtain the result. + + The sample code is as follows: + + ```js + let rdbPredicate = new data_rdb.RdbPredicates('employee') + predicates.greaterThan("id", 0) + let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate) + promiseQuery.then((resultSet) => { + while (resultSet.goToNextRow()) { + let idx = resultSet.getLong(0); + let name = resultSet.getString(1); + let age = resultSet.getLong(2); + console.info(idx + " " + name + " " + age); + } + resultSet.close(); + }).catch((err) => { + console.info("failed to remoteQuery, err: " + err) + }) + ``` + +9. Back up and restore an RDB store. (1) Back up the current RDB store. @@ -372,23 +372,18 @@ You can obtain the distributed table name for a remote device based on the local ```js let promiseBackup = rdbStore.backup("dbBackup.db") - promiseBackup.then(()=>{ + promiseBackup.then(() => { console.info('Backup success.') - }).catch((err)=>{ + }).catch((err) => { console.info('Backup failed, err: ' + err) }) ``` ```js let promiseRestore = rdbStore.restore("dbBackup.db") - promiseRestore.then(()=>{ + promiseRestore.then(() => { console.info('Restore success.') - }).catch((err)=>{ + }).catch((err) => { console.info('Restore failed, err: ' + err) }) ``` -## Samples -The following samples are provided for you to better understand the RDB development: -- [`Rdb`: eTS RDB (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Rdb) -- [`DistributedRdb`: eTS Distributed Relational Database (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/DistributedRdb) -- [Relational Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData) diff --git a/en/application-dev/database/figures/en_DataShare.png b/en/application-dev/database/figures/en_DataShare.png new file mode 100644 index 0000000000000000000000000000000000000000..e0243b935e8cc61d61c5f572a20c66aadc5edbd3 Binary files /dev/null and b/en/application-dev/database/figures/en_DataShare.png differ diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md index fb107049c515d0ff1961313a9f0bebb39c4e4c9d..01fe1ed68b3eb05341438da3d81270afdc4a92e3 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md @@ -421,13 +421,13 @@ import stats from '@ohos.bundleState'; ```javascript import stats from '@ohos.bundleState' - //promise + // Promise mode stats.unRegisterGroupCallBack().then(() => { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); }).catch(err => { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); }); - //callback + // Asynchronous callback mode stats.unRegisterGroupCallBack((err) => { if (err) { console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code); diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index a32decd05ac0ba0d6db06749c18dcd31d3a7645b..c61c9288eecb35ce4235fb00ce91b595b9160b44 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -84,7 +84,7 @@ To learn more about the APIs for obtaining device location information, see [Geo } ``` - For details about the fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). + For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index d65d0abfc4d4649f7f1847abdbe6fb0a832e194e..faf977c7b42644a03066947e45996a936529f8cc 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -39,28 +39,28 @@ function printfDescription(obj) { // Set the player callbacks. function setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered. }); - audioPlayer.on('play', () => { // Set the `play` event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. }); - audioPlayer.on('pause', () => { // Set the `pause` event callback. + audioPlayer.on('pause', () => { // Set the 'pause' event callback. console.info('audio pause success'); audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback. }); - audioPlayer.on('stop', () => { // Set the `stop` event callback. + audioPlayer.on('stop', () => { // Set the 'stop' event callback. console.info('audio stop success'); audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. }); - audioPlayer.on('reset', () => { // Set the `reset` event callback. + audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.info('audio reset success'); audioPlayer.release(); // Release the AudioPlayer instance. audioPlayer = undefined; }); - audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the `timeUpdate` event callback. + audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. if (typeof(seekDoneTime) == 'undefined') { console.info('audio seek fail'); return; @@ -68,7 +68,7 @@ function setCallBack(audioPlayer) { console.info('audio seek success, and seek time is ' + seekDoneTime); audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. }); - audioPlayer.on('volumeChange', () => { // Set the `volumeChange` event callback. + audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. console.info('audio volumeChange success'); audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. if (typeof (arrlist) != 'undefined') { @@ -107,7 +107,7 @@ async function audioPlayerDemo() { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. } ``` @@ -119,11 +119,11 @@ import fileIO from '@ohos.fileio' export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the `play` event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); }); audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. @@ -147,7 +147,7 @@ export class AudioDemo { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. } } ``` @@ -161,15 +161,15 @@ export class AudioDemo { // Set the player callbacks. private isNextMusic = false; setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. }); - audioPlayer.on('play', () => { // Set the `play` event callback. + audioPlayer.on('play', () => { // Set the 'play' event callback. console.info('audio play success'); audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback. }); - audioPlayer.on('reset', () => { // Set the `reset` event callback. + audioPlayer.on('reset', () => { // Set the 'reset' event callback. console.info('audio play success'); if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. this.nextMusic(audioPlayer); // Changing songs is implemented. @@ -223,7 +223,7 @@ import fileIO from '@ohos.fileio' export class AudioDemo { // Set the player callbacks. setCallBack(audioPlayer) { - audioPlayer.on('dataLoad', () => { // Set the `dataLoad` event callback, which is triggered when the src attribute is set successfully. + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. console.info('audio set source success'); audioPlayer.loop = true; // Set the loop playback attribute. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback. @@ -247,7 +247,7 @@ export class AudioDemo { }).catch((err) => { console.info('open fd failed err is' + err); }); - audioPlayer.src = fdPath; // Set the src attribute and trigger the `dataLoad` event callback. + audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback. } } ``` diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index e58eed34cccb7dd820e1144a616dfb93a10f4d34..86854eb072b19c7ee359dcb70413ce22580cb8f7 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -14,6 +14,7 @@ You can `import` the native .so that contains the JS processing logic. For examp * Add **static** to the **nm_register_func** function to prevent symbol conflicts with other .so files. * The name of the module registration entry, that is, the function decorated by **\_\_attribute\_\_((constructor))**, must be unique. + ### .so Naming Rules Each module has a .so file. For example, if the module name is `hello`, name the .so file **libhello.so**. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. @@ -25,6 +26,10 @@ The Ark engine prevents NAPIs from being called to operate JS objects in non-JS * The NAPIs can be used only in JS threads. * **env** is bound to a thread and cannot be used across threads. The JS object created by a NAPI can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread. +### Importing Header Files + +Before using NAPI objects and methods, include **napi/native_api.h**. Otherwise, when only the third-party library header file is included, an error will be reporting, indicating that the interface cannot be found. + ### napi_create_async_work **napi_create_async_work** has two callbacks: @@ -635,3 +640,8 @@ export default { } } ``` +## Samples +The following samples are provided for native API development: +- [`NativeAPI`: NativeAPI (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) +- [First Native C++ Application (eTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) +- [Native Component (eTS) (API9) ](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index 8450f3d8c7f6d0ddfed16215bc8345c2b036c400..d5a6d7bdfbc6dcdd5b94d36e155d4650fc70630c 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -98,11 +98,11 @@ import commonEvent from '@ohos.commonEvent'; ```js // Publish a common event. commonEvent.publish("event", (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish1") - } + if (err.code) { + console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) + } else { + console.info("[CommonEvent]Publish1") + } }) ``` @@ -118,8 +118,8 @@ import commonEvent from '@ohos.commonEvent' ```js // Attributes of a common event. var options = { - code: 1, // Result code of the common event - data: "initial data";// Result data of the common event + code: 1, // Result code of the common event + data: "initial data",// Result data of the common event } ``` @@ -128,11 +128,11 @@ var options = { ```js // Publish a common event. commonEvent.publish("event", options, (err) => { - if (err.code) { - console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) - } else { - console.info("[CommonEvent]Publish2") - } + if (err.code) { + console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err)) + } else { + console.info("[CommonEvent]Publish2") + } }) ``` diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 6b5bbc8aa3d671c4cf0b01316db441d33c0f189f..edee55c375b0cc31b8f6305ed7fb24397bad12b0 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -19,6 +19,7 @@ - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - [@ohos.application.StartOptions](js-apis-application-StartOptions.md) - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) + - [@ohos.application.WindowExtensionAbility](js-apis-application-WindowExtensionAbility.md) - application/[AbilityContext](js-apis-ability-context.md) - application/[ApplicationContext](js-apis-application-applicationContext.md) - application/[AbilityStageContext](js-apis-abilitystagecontext.md) @@ -68,18 +69,25 @@ - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) + - [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) + - [@ohos.distributedBundle)](js-apis-Bundle-distributedBundle.md) - [@ohos.zlib](js-apis-zlib.md) - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) - bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md) - bundle/[BundleInfo](js-apis-bundle-BundleInfo.md) + - bundle/[BundleInstaller](js-apis-bundle-BundleInstaller.md) - bundle/[CustomizeData](js-apis-bundle-CustomizeData.md) + - bundle/[DispatchInfo](js-apis-dispatchInfo.md) - bundle/[ElementName](js-apis-bundle-ElementName.md) - bundle/[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md) - bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md) + - bundle/[LauncherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md) - bundle/[Metadata](js-apis-bundle-Metadata.md) - bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md) - + - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) + - bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) + - bundle/[ShortcutInfo](js-apis-bundle-ShortcutInfo.md) - UI Page - [@ohos.animator](js-apis-animator.md) @@ -90,6 +98,7 @@ - Graphics + - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) - [@ohos.display ](js-apis-display.md) - [@ohos.effectKit](js-apis-effectKit.md) - [@ohos.screen](js-apis-screen.md) diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md new file mode 100644 index 0000000000000000000000000000000000000000..3691d636ac769e8bfad9099f92554a2476925d40 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -0,0 +1,307 @@ +# innerBundleManager + +The **innerBundleManager** module manages internal bundles. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import innerBundleManager from '@ohos.bundle.innerBundleManager'; +``` + +## System Capability + +SystemCapability.BundleManager.BundleFramework + +## Required Permissions + +| Permission | Permission Level | Description | +| ------------------------------------------ | ------------ | ---------------------------- | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications. | +| ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant | Permission to listen for application changes.| + +For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). + +## innerBundleManager.getLauncherAbilityInfos + +getLauncherAbilityInfos(bundleName: string, userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; + +Obtains the launcher ability information based on a given bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | + + + +## innerBundleManager.getLauncherAbilityInfos + +getLauncherAbilityInfos(bundleName: string, userId: number) : Promise<Array<LauncherAbilityInfo>> + +Obtains the launcher ability information based on a given bundle name. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ----------------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise\> | Promise used to return an array of the launcher ability information.| + +## innerBundleManager.on + +on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback, callback: AsyncCallback<string>) : void; + +Registers a callback to receive bundle status changes. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.LISTEN_BUNDLE_CHANGE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | --------------------- | ---- | ---------------------------------------------------- | +| type | "BundleStatusChange" | Yes | Event type. | +| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register. | +| callback | AsyncCallback\ | Yes | Callback used to return a successful result or error information.| + +## innerBundleManager.on + +on(type:"BundleStatusChange", bundleStatusCallback : BundleStatusCallback): Promise<string> + +Registers a callback to receive bundle status changes. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.LISTEN_BUNDLE_CHANGE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------- | ---- | ------------------ | +| type | "BundleStatusChange" | Yes | Event type. | +| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register.| + +**Return value** + +| Type | Description | +| --------------- | ----------------------------------- | +| Promise\ | Promise used to return a successful result or error information.| + +## innerBundleManager.off + +off(type:"BundleStatusChange", callback: AsyncCallback<string>) : void; + +Deregisters the callback that receives bundle status changes. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.LISTEN_BUNDLE_CHANGE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------------------- | +| type | "BundleStatusChange" | Yes | Event type. | +| callback | AsyncCallback\ | Yes | Callback used to return a successful result or error information.| + +## innerBundleManager.off + +off(type:"BundleStatusChange"): Promise<string> + +Deregisters the callback that receives bundle status changes. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.LISTEN_BUNDLE_CHANGE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | -------------------- | ---- | ---------------- | +| type | "BundleStatusChange" | Yes | Event type.| + +**Return value** + +| Type | Description | +| --------------- | ----------------------------------- | +| Promise\ | Promise used to return a successful result or error information.| + +## innerBundleManager.getAllLauncherAbilityInfos + +getAllLauncherAbilityInfos(userId: number, callback: AsyncCallback<Array<LauncherAbilityInfo>>) : void; + +Obtains the information about all launcher abilities. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | + +## innerBundleManager.getAllLauncherAbilityInfos + +getAllLauncherAbilityInfos(userId: number) : Promise<Array<LauncherAbilityInfo>> + +Obtains the information about all launcher abilities. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------------------- | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise\> | Promise used to return an array of the launcher ability information.| + +## innerBundleManager.getShortcutInfos + +getShortcutInfos(bundleName :string, callback: AsyncCallback<Array<ShortcutInfo>>) : void; + +Obtains the shortcut information based on a given bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| callback | AsyncCallback\> | Yes | Callback used to return an array of the shortcut information.| + +## innerBundleManager.getShortcutInfos + +getShortcutInfos(bundleName : string) : Promise<Array<ShortcutInfo>> + +Obtains the shortcut information based on a given bundle name. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ------------------------ | +| bundleName | string | Yes | Bundle name of an application.| + +**Return value** + +| Type | Description | +| -------------------------------------------------------- | ----------------------------- | +| Promise\> | Promise used to return an array of the shortcut information.| diff --git a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md new file mode 100644 index 0000000000000000000000000000000000000000..f321aca70ed972845f73ca702501e574aeafe5e0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @@ -0,0 +1,139 @@ +# distributedBundle + +The **distributedBundle** module manages distributed bundles. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import distributedBundle from '@ohos.distributedBundle'; +``` + +## System Capability + +SystemCapability.BundleManager.DistributedBundleFramework + +## Required Permissions + +| Permission | Permission Level | Description | +| ------------------------------------------ | ------------ | ------------------ | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | Permission to query information about all applications.| + +For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void; + +Obtains information about the remote ability that matches the given element name. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.DistributedBundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**. | +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Yes | Callback used to return the remote ability information.| + + + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo> + +Obtains information about the remote ability that matches the given element name. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.DistributedBundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | -------------------------------------------- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Promise used to return the remote ability information.| + +## distributedBundle.getRemoteAbilityInfos + +getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void; + +Obtains information about remote abilities that match the given element names. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.DistributedBundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | +| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return an array of the remote ability information.| + + + +## distributedBundle.getRemoteAbilityInfos + +getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>> + +Obtains information about remote abilities that match the given element names. This API uses a promise to return the result. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability** + +SystemCapability.BundleManager.DistributedBundleFramework + +**System API** + +This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------------- | ---- | ----------------------- | +| elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\> | Promise used to return an array of the remote ability information.| diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 94d93df6aa2f25bfce6b2094cfe06a88429df346..e487baedfd496a9ac0a6e90332aa99f3323a4fc2 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -39,11 +39,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -81,12 +81,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** @@ -119,11 +119,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** @@ -155,10 +155,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------- | ---- | --------------------------------------- | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory| Description | +| ---------- | ---------- | ---- | ------------------------------------------------------------ | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -195,10 +195,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | --------------------------------- | ---- | --------------------------------------- | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -229,11 +229,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | --------------------------------- | ---- | --------------------------------------- | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | **Example** @@ -268,7 +268,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- | --------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | options | [BundleOptions](#bundleoptions) | No | Includes **userId**. | **Return value** @@ -309,11 +309,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -346,12 +346,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** @@ -847,10 +847,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | --------------------------------------- | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -889,11 +889,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------------------- | ---- | --------------------------------------- | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -926,10 +926,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | -------------------------------------- | ---- | --------------------------------------- | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the application information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** @@ -959,7 +959,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| **Return value** | Type | Description | @@ -994,7 +994,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than or equal to 0.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles.| **Example** @@ -1474,7 +1474,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ------------------------------------- | | want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. For details on the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -1518,12 +1518,12 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------- | -| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. For details on the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** @@ -1559,11 +1559,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------- | ---- | ------------------------------------- | -| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | -| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. The value must be greater than or equal to 0.| -| callback | AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. The default value is **0**. For details on the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index ce415ad942510c481755380bdd90adb7eb1c75ae..c432f719593a2aa3f32db509b339b2cc783ea5b4 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -4,8 +4,7 @@ The **Context** module provides context for abilities or applications. It allows > **NOTE** > -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the FA model. ## Usage @@ -30,9 +29,9 @@ If this API is called for the first time, a root directory will be created. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the local root directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the local root directory.| **Example** @@ -58,8 +57,8 @@ If this API is called for the first time, a root directory will be created. **Return value** -| Type | Description | -| ---------------- | ---------------------- | +| Type | Description | +| ---------------- | ----------- | | Promise\ | Promise used to return the local root directory.| **Example** @@ -84,11 +83,11 @@ Verifies whether a specific PID and UID have the given permission. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ------------------------------------- | -| permission | string | Yes | Name of the permission to verify. | -| options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | -| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------------- | ---- | -------------------- | +| permission | string | Yes | Name of the permission to verify. | +| options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | +| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -113,10 +112,10 @@ Verifies whether the current PID and UID have the given permission. This API use **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------- | ---- | ------------------------------------- | -| permission | string | Yes | Name of the permission to verify. | -| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------- | ---- | -------------------- | +| permission | string | Yes | Name of the permission to verify. | +| callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -136,15 +135,15 @@ Verifies whether a specific PID and UID have the given permission. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------------- | ---- | ---------------- | -| permission | string | Yes | Name of the permission to verify.| -| options | [PermissionOptions](#permissionoptions) | No | Permission options. | +| Name | Type | Mandatory | Description | +| ---------- | --------------------------------------- | ---- | -------- | +| permission | string | Yes | Name of the permission to verify.| +| options | [PermissionOptions](#permissionoptions) | No | Permission options. | **Return value** -| Type | Description | -| ---------------- | ----------------------------------------------------------- | +| Type | Description | +| ---------------- | ---------------------------------- | | Promise\ | Promise used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** @@ -171,11 +170,11 @@ Requests certain permissions from the system. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | -| permissions | Array\ | Yes | Permissions to request. This parameter cannot be **null**. | -| requestCode | number | Yes | Request code to be passed to **PermissionRequestResult**.| -| resultCallback | AsyncCallback<[PermissionRequestResult](#permissionrequestresult)> | Yes | Permission request result. | +| Name | Type | Mandatory | Description | +| -------------- | ---------------------------------------- | ---- | ----------------------------------- | +| permissions | Array\ | Yes | Permissions to request. This parameter cannot be **null**. | +| requestCode | number | Yes | Request code to be passed to **PermissionRequestResult**.| +| resultCallback | AsyncCallback<[PermissionRequestResult](#permissionrequestresult)> | Yes | Permission request result. | **Example** @@ -207,9 +206,9 @@ Obtains information about the current application. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the application information.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | ------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the application information.| **Example** @@ -231,8 +230,8 @@ Obtains information about the current application. This API uses a promise to re **Return value** -| Type | Description | -| ------------------------- | ------------------ | +| Type | Description | +| ------------------------- | --------- | | Promise\ | Promise used to return the application information.| **Example** @@ -258,9 +257,9 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -282,8 +281,8 @@ Obtains the bundle name of this ability. This API uses a promise to return the r **Return value** -| Type | Description | -| ---------------- | ------------------------- | +| Type | Description | +| ---------------- | ---------------- | | Promise\ | Promise used to return the bundle name.| **Example** @@ -307,9 +306,9 @@ Obtains the display orientation of this ability. This API uses an asynchronous c **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------ | +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| **Example** @@ -329,9 +328,9 @@ Obtains the display orientation of this ability. This API uses a promise to retu **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Promise used to return the display orientation.| +| Type | Description | +| ---------------------------------------- | --------- | +| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation.| **Example** @@ -348,16 +347,16 @@ context.getDisplayOrientation().then((data) => { setDisplayOrientation(orientation: bundle.DisplayOrientation, callback: AsyncCallback\): void -Obtains the display orientation for this ability. This API uses an asynchronous callback to return the result. +Sets the display orientation for this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| orientation | [bundle.DisplayOrientation](js-apis-bundle.md#displayorientation) | Yes | Display orientation to set.| -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | ------------ | +| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | Yes | Display orientation to set.| +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation. | **Example** @@ -375,16 +374,16 @@ context.setDisplayOrientation(orientation, (err) => { setDisplayOrientation(orientation: bundle.DisplayOrientation): Promise\; -Obtains the display orientation for this ability. This API uses a promise to return the result. +Sets the display orientation for this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| orientation | [bundle.DisplayOrientation](js-apis-bundle.md#displayorientation) | Yes | Display orientation to set.| -| Promise\<[bundle.DisplayOrientation](js-apis-bundle.md#displayorientation)> | Promise used to return the display orientation.| +| Type | Description | +| ---------------------------------------- | ---------------------------------------- | +| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | +| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation. | **Example** @@ -403,16 +402,16 @@ context.setDisplayOrientation(orientation).then((data) => { setShowOnLockScreen(show: boolean, callback: AsyncCallback\): void -Sets whether to show this feature at the top of the lock screen each time the lock screen is displayed so that the feature remains activated. This API uses an asynchronous callback to return the result. +Sets whether to show this feature at the top of the lock screen so that the feature remains activated. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | ---------------------------------------- | +| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -429,21 +428,21 @@ context.setShowOnLockScreen(show, (err) => { setShowOnLockScreen(show: boolean): Promise\; -Sets whether to show this feature at the top of the lock screen each time the lock screen is displayed so that the feature remains activated. This API uses a promise to return the result. +Sets whether to show this feature at the top of the lock screen so that the feature remains activated. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| +| Name | Type | Mandatory | Description | +| ---- | ------- | ---- | ---------------------------------------- | +| show | boolean | Yes | Whether to show this feature at the top of the lock screen. The value **true** means to show this feature at the top of the lock screen, and **false** means the opposite.| **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise\| Promise used to return the result.| +| Type | Description | +| -------------- | --------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -467,10 +466,10 @@ Sets whether to wake up the screen when this feature is restored. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | ---- | --------------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -493,15 +492,15 @@ Sets whether to wake up the screen when this feature is restored. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------- | -| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | --------------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite.| **Return value** -| Type | Description | -| ---------------- | ------------------------- | -| Promise\| Promise used to return the result.| +| Type | Description | +| -------------- | --------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -528,9 +527,9 @@ Obtains information about the current process, including the PID and process nam **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the process information.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the process information.| **Example** @@ -552,8 +551,8 @@ Obtains information about the current process, including the PID and process nam **Return value** -| Type | Description | -| --------------------- | -------------- | +| Type | Description | +| --------------------- | ------- | | Promise\ | Promise used to return the process information.| **Example** @@ -581,9 +580,9 @@ This API is available only to Page abilities. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ---------------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the **ohos.bundle.ElementName** object.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the **ohos.bundle.ElementName** object.| **Example** @@ -607,8 +606,8 @@ This API is available only to Page abilities. **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | +| Type | Description | +| --------------------- | ------------------------------------ | | Promise\ | Promise used to return the **ohos.bundle.ElementName** object.| **Example** @@ -632,9 +631,9 @@ Obtains the name of the current process. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the process name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the process name.| **Example** @@ -656,8 +655,8 @@ Obtains the name of the current process. This API uses a promise to return the r **Return value** -| Type | Description | -| ---------------- | -------------------- | +| Type | Description | +| ---------------- | ---------- | | Promise\ | Promise used to return the process name.| **Example** @@ -683,9 +682,9 @@ Obtains the bundle name of the calling ability. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** @@ -707,8 +706,8 @@ Obtains the bundle name of the calling ability. This API uses a promise to retur **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | -------------- | | Promise\ | Promise used to return the bundle name.| **Example** @@ -732,9 +731,9 @@ Obtains the cache directory of the application in the internal storage. This API **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the cache directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | --------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the cache directory.| **Example** @@ -760,8 +759,8 @@ Obtains the cache directory of the application in the internal storage. This API **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | --------------- | | Promise\ | Promise used to return the cache directory.| **Example** @@ -785,9 +784,9 @@ Obtains the file directory of the application in the internal storage. This API **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the file directory.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the file directory.| **Example** @@ -813,8 +812,8 @@ Obtains the file directory of the application in the internal storage. This API **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ------------------- | | Promise\ | Promise used to return the file directory.| **Example** @@ -840,9 +839,9 @@ If the distributed file path does not exist, the system will create one and retu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| **Example** @@ -870,8 +869,8 @@ If the distributed file path does not exist, the system will create one and retu **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ----------------------------------- | | Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a new path will be created.| **Example** @@ -894,9 +893,9 @@ Obtains the application type. This API uses an asynchronous callback to return t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the application type.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the application type.| **Example** @@ -922,8 +921,8 @@ Obtains the application type. This API uses a promise to return the result. **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------- | ------------------ | | Promise\ | Promise used to return the application type.| **Example** @@ -946,9 +945,9 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| **Example** @@ -974,8 +973,8 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | ------------------ | | Promise\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| **Example** @@ -998,9 +997,9 @@ Obtains the version information of this application. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[AppVersionInfo](#appversioninfo)> | Yes | Callback used to return the version information.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| callback | AsyncCallback\<[AppVersionInfo](#appversioninfo)> | Yes | Callback used to return the version information.| **Example** @@ -1026,8 +1025,8 @@ Obtains the version information of this application. This API uses a promise to **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | --------- | | Promise\<[AppVersionInfo](#appversioninfo)> | Promise used to return the version information.| **Example** @@ -1050,9 +1049,9 @@ Obtains information about this ability. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------------------------------------- | +| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| **Example** @@ -1078,8 +1077,8 @@ Obtains information about this ability. This API uses a promise to return the re **Return value** -| Type | Description | -| --------------- | ------------------------- | +| Type | Description | +| ---------------------------------------- | ------------------ | | Promise\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Promise used to return the ability information.| **Example** @@ -1102,9 +1101,9 @@ Obtains the context of the application. **Return value** -| Type | Description | -| --------- |------ | -| Context | Application context.| +| Type | Description | +| ------- | ---------- | +| Context | Application context.| **Example** @@ -1117,15 +1116,15 @@ var context = featureAbility.getContext().getApplicationContext(); isUpdatingConfigurations(callback: AsyncCallback\): void; -Checks whether the configuration of this ability is being changed. This API uses an asynchronous callback to return the result. +Checks whether the configuration of this ability is being updated. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ------------------------- | -| callback | AsyncCallback\ | Yes | Returns **true** if the configuration of the capability is being changed; returns **false** otherwise.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ---- | ----------------------------- | +| callback | AsyncCallback\ | Yes | Returns **true** if the configuration of the capability is being updated; returns **false** otherwise.| **Example** @@ -1145,15 +1144,15 @@ context.isUpdatingConfigurations((err, data) => { isUpdatingConfigurations(): Promise\; -Checks whether the configuration of this ability is being changed. This API uses a promise to return the result. +Checks whether the configuration of this ability is being updated. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Return value** -| Type | Description | -| --------------- | ------------------------- | -|Promise\ | Returns **true** if the configuration of the capability is being changed; returns **false** otherwise.| +| Type | Description | +| ----------------- | ----------------------------- | +| Promise\ | Returns **true** if the configuration of the capability is being updated; returns **false** otherwise.| **Example** @@ -1175,9 +1174,9 @@ Notifies the system of the time required to draw this page function. This API us **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** @@ -1203,9 +1202,9 @@ Notifies the system of the time required to draw this page function. This API us **Return value** -| Type | Description | -| --------------- | ------------------------- | -|Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | --------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -1222,27 +1221,27 @@ context.printDrawnCompleted().then((data) => { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Readable/Writable| Type | Mandatory| Description | -| ---- | -------- | ------ | ---- | ------ | -| pid | Read-only | number | No | Process ID.| -| uid | Read-only | number | No | User ID.| +| Name | Readable/Writable| Type | Mandatory | Description | +| ---- | ---- | ------ | ---- | ----- | +| pid | Read-only | number | No | Process ID.| +| uid | Read-only | number | No | User ID.| ## PermissionRequestResult7+ **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------- | ---- | ------------------ | -| requestCode | Read-only | number | Yes | Request code passed.| -| permissions | Read-only | Array\ | Yes | Permissions requested. | -| authResults | Read-only | Array\ | Yes | Permission request result. | +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | -------------- | ---- | ---------- | +| requestCode | Read-only | number | Yes | Request code passed.| +| permissions | Read-only | Array\ | Yes | Permissions requested. | +| authResults | Read-only | Array\ | Yes | Permission request result. | ## AppVersionInfo7+ **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type| Readable | Writable | Description| -| ------ | ------ | ------| ------ | ------ | -| appName | string | Yes | No | Module name. | -| versionCode | number | Yes | No | Module description. | -| versionName | string | Yes | No | Module description ID. | +| Name | Type | Readable | Writable | Description | +| ----------- | ------ | ---- | ---- | ------- | +| appName | string | Yes | No | Module name. | +| versionCode | number | Yes | No | Module description.| +| versionName | string | Yes | No | Module description ID.| diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md index e2333a523a918e229c6a35c4e341df9383bfb26a..3b5d0bba1bb5954d3365d97cde619f5931c0f7a3 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -2,7 +2,7 @@ The **AbilityContext** module, inherited from **Context**, implements the context for abilities. -This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a pop-up window. +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** > @@ -40,13 +40,11 @@ Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -71,13 +69,11 @@ Starts an ability with start options specified. This API uses an asynchronous ca **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 **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| @@ -106,13 +102,11 @@ Starts an ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -**System API**: This is a system API and cannot be called by third-party applications. - **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| **Return value** @@ -153,7 +147,7 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want |[Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| @@ -181,7 +175,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want |[Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| @@ -214,7 +208,7 @@ Starts an ability. This API uses a promise to return the result when the ability | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| @@ -239,7 +233,7 @@ Starts an ability. This API uses a promise to return the result when the ability ## AbilityContext.startAbilityForResultWithAccount -startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback): void; +startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. @@ -253,8 +247,8 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -289,8 +283,8 @@ Starts an ability with start options specified. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -312,7 +306,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca ``` - ## AbilityContext.startAbilityForResultWithAccount +## AbilityContext.startAbilityForResultWithAccount startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; @@ -328,8 +322,8 @@ Starts an ability with start options specified. This API uses a promise to retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| **Return value** @@ -358,7 +352,271 @@ Starts an ability with start options specified. This API uses a promise to retur console.log('---------- startAbilityForResultWithAccount fail, err: -----------', err); }) ``` +## AbilityContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.startServiceExtensionAbility(want, (err) => { + console.log('---------- startServiceExtensionAbility fail, err: -----------', err); + }); + ``` + +## AbilityContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want): Promise\; + +Starts a new Service Extension ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.startServiceExtensionAbility(want) + .then((data) => { + console.log('---------- startServiceExtensionAbility success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startServiceExtensionAbility fail, err: -----------', err); + }) + ``` +## AbilityContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**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.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startServiceExtensionAbilityWithAccount(want,accountId, (err) => { + console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); + }); + ``` + +## AbilityContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**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.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.startServiceExtensionAbilityWithAccount(want,accountId) + .then((data) => { + console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); + }) + ``` +## AbilityContext.stopServiceExtensionAbility +stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. + +**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.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.stopServiceExtensionAbility(want, (err) => { + console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); + }); + ``` + +## AbilityContext.stopServiceExtensionAbility + +stopServiceExtensionAbility(want: Want): Promise\; + +Stops a Service Extension ability in the same application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + this.context.stopServiceExtensionAbility(want) + .then((data) => { + console.log('---------- stopServiceExtensionAbility success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); + }) + ``` + +## AbilityContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**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.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.stopServiceExtensionAbilityWithAccount(want,accountId, (err) => { + console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); + }); + ``` + +## AbilityContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS + +**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.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Example** + + ```js + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "MainAbility" + }; + var accountId = 100; + this.context.stopServiceExtensionAbilityWithAccount(want,accountId) + .then((data) => { + console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data); + }) + .catch((err) => { + console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); + }) + ``` ## AbilityContext.terminateSelf @@ -412,7 +670,7 @@ Terminates this ability. This API uses a promise to return the result. terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. This API uses an asynchronous callback to return the information to the caller of **startAbilityForResult**. +Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -426,11 +684,17 @@ Terminates this ability. This API uses an asynchronous callback to return the in **Example** ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }, (error) => { + var want = { + "bundleName": "com.extreme.myapplication", + "abilityName": "SecondAbility" + } + var resultCode = 100; + // AbilityResult information returned to the caller. + var abilityResult = { + want, + resultCode + } + this.context.terminateSelfWithResult(abilityResult, (error) => { console.log("terminateSelfWithResult is called = " + error.code) } ); @@ -441,7 +705,7 @@ Terminates this ability. This API uses an asynchronous callback to return the in terminateSelfWithResult(parameter: AbilityResult): Promise<void>; -Terminates this ability. This API uses a promise to return information to the caller of **startAbilityForResult**. +Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -460,11 +724,17 @@ Terminates this ability. This API uses a promise to return information to the ca **Example** ```js - this.context.terminateSelfWithResult( - { - want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, - resultCode: 100 - }).then((result) => { + var want = { + "bundleName": "com.extreme.myapplication", + "abilityName": "SecondAbility" + } + var resultCode = 100; + // AbilityResult information returned to the caller. + var abilityResult = { + want, + resultCode + } + this.context.terminateSelfWithResult(abilityResult).then((result) => { console.log("terminateSelfWithResult") } ) @@ -484,8 +754,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | No| Remote object instance.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | No| Parameters for the connection.| **Return value** @@ -515,7 +785,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to connectAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability. +Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -527,8 +797,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | No| Parameters for the connection.| **Return value** @@ -626,7 +896,7 @@ Obtains the caller interface of the specified ability, and if the specified abil | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including the ability 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 target ability, including the ability name, bundle name, and device ID. If the device ID is left blank or the default value is used, it indicates the local device.| **Return value** @@ -671,8 +941,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -706,8 +976,8 @@ Starts an ability with the account ID and start options specified. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -745,8 +1015,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| **Example** @@ -774,7 +1044,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; -Requests permissions from the user by displaying a pop-up window. This API uses an asynchronous callback to return the result. +Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -783,7 +1053,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the permission request result.| +| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result.| **Example** @@ -800,7 +1070,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; -Requests permissions from the user by displaying a pop-up window. This API uses a promise to return the result. +Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -814,7 +1084,7 @@ Requests permissions from the user by displaying a pop-up window. This API uses | Type| Description| | -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the permission request result.| +| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result.| **Example** @@ -1006,7 +1276,7 @@ Checks whether this ability is in the terminating state. | Type| Description| | -------- | -------- | -| bool | The value **true** means that the ability is in terminating state, and **false** means the opposite.| +| boolean| The value **true** means that the ability is in the terminating state, and **false** means the opposite.| **Example** 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 c2bb08c5314a44dcf6f4ad9246e6ee08a313ecd8..545da5d468feefce2440a356812356e6206e11e3 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -1,6 +1,6 @@ # wantConstant -The **wantConstant** module provides the action, entity, and flags used in **Want** objects. +The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. > **NOTE** > @@ -23,15 +23,15 @@ Enumerates the action constants of the **Want** object. | ACTION_HOME | ohos.want.action.home | Action of returning to the home page. | | ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | | ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. | -| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides radio network settings, for example, Wi-Fi option. | +| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides wireless network settings, for example, Wi-Fi options. | | ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. | | ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. | | ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. | -| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all clock alarms. | +| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all alarms. | | ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. | | ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | | ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | -| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS. | +| 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_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. | diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 2b17d252af9d09d5519f36ece4306834e8085c5a..003a5efd92057dc7127b74aa35553f3220bd890e 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -49,7 +49,7 @@ Checks whether an application has been granted the specified permission. This AP | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to verify.| **Return value** @@ -105,7 +105,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl Grants a user granted permission to an application. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS @@ -143,7 +143,7 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl Grants a user granted permission to an application. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.GRANT_SENSITIVE_PERMISSIONS @@ -179,7 +179,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF Revokes a user granted permission given to an application. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS @@ -217,7 +217,7 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.REVOKE_SENSITIVE_PERMISSIONS @@ -253,7 +253,7 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise<number&g Obtains the flags of the specified permission of a given application. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +This is a system API. **Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS, ohos.permission.GRANT_SENSITIVE_PERMISSIONS, or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index f216c6b08806daa6c5bc87471a3effd749130094..ef0e355c63726bc167dac72801adfdce030827f3 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -89,7 +89,7 @@ Adds an app account name and additional information (information that can be con ### addAccount -addAccount(name: string, extraInfo: string): Promise<void> +addAccount(name: string, extraInfo?: string): Promise<void> Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses a promise to return the result. @@ -100,7 +100,7 @@ Adds an app account name and additional information (information that can be con | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | | name | string | Yes | Name of the app account to add. | -| extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| +| extraInfo | string | No | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| **Return value** @@ -1696,7 +1696,7 @@ Checks whether an app account has specific labels. This API uses an asynchronous | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| | labels | Array<string> | Yes | Labels to check. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | **Example** @@ -1710,7 +1710,7 @@ Checks whether an app account has specific labels. This API uses an asynchronous ### checkAccountLabels9+ -checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<void> +checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> Checks whether an app account has specific labels. This API uses a promise to return the result. @@ -1771,7 +1771,7 @@ Selects the accounts accessible to the requester based on the options. This API ### selectAccountsByOptions9+ -selectAccountsByOptions(options: SelectAccountsOptions): Promise<void> +selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> Selects the accounts accessible to the requester based on the options. This API uses a promise to return the result. @@ -1836,7 +1836,7 @@ Verifies the user credential. This API uses an asynchronous callback to return t ### verifyCredential9+ -verifyCredential(name: string, owner: string, options, callback: AuthenticatorCallback): void; +verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; Verifies the user credential. This API uses an asynchronous callback to return the result. @@ -1952,11 +1952,11 @@ Defines OAuth token information. **System capability**: SystemCapability.Account.AppAccount -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | -------- | -| authType | string | Yes | Authentication type.| -| token | string | Yes | Value of the token. | -| account9+ | AppAccountInfo | No | Account information of the token. | +| Name | Type | Mandatory | Description | +| -------------------- | -------------- | ----- | ---------------- | +| authType | string | Yes | Authentication type. | +| token | string | Yes | Value of the token. | +| account9+ | AppAccountInfo | No | Account information of the token.| ## AuthenticatorInfo8+ @@ -1978,7 +1978,7 @@ Represents the options for selecting accounts. | Name | Type | Mandatory | Description | | --------------- | --------------------------- | ----- | ------------------- | -| allowedAccounts | Array<[AppAccountInfo](#appAccountinfo)> | No | Allowed accounts. | +| allowedAccounts | Array<[AppAccountInfo](#appaccountinfo)> | No | Allowed accounts. | | allowedOwners | Array<string> | No | Allowed account owners.| | requiredLabels | Array<string> | No | Labels required for the authenticator. | @@ -2012,21 +2012,21 @@ Enumerates the constants. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value | Description | -| ----------------------------- | ---------------------- | ------------- | -| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation of adding an account implicitly. | -| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | -| KEY_NAME | "name" | App account name. | -| KEY_OWNER | "owner" | Owner of an app account.| -| KEY_TOKEN | "token" | Token. | -| KEY_ACTION | "action" | Operation. | -| KEY_AUTH_TYPE | "authType" | Authentication type. | -| KEY_SESSION_ID | "sessionId" | Session ID. | -| KEY_CALLER_PID | "callerPid" | PID of the caller. | -| KEY_CALLER_UID | "callerUid" | UID of the caller. | -| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Bundle name of the caller. | -| KEY_REQUIRED_LABELS | "requiredLabels" | Required labels. | -| KEY_BOOLEAN_RESULT | "booleanResult" | Return value of the Boolean type. | +| Name | Default Value | Description | +| -------------------------------- | ---------------------- | ----------------------- | +| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation of adding an account implicitly. | +| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | +| KEY_NAME | "name" | App account name. | +| KEY_OWNER | "owner" | Owner of an app account.| +| KEY_TOKEN | "token" | Token. | +| KEY_ACTION | "action" | Operation. | +| KEY_AUTH_TYPE | "authType" | Authentication type. | +| KEY_SESSION_ID | "sessionId" | Session ID. | +| KEY_CALLER_PID | "callerPid" | PID of the caller. | +| KEY_CALLER_UID | "callerUid" | UID of the caller. | +| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | Bundle name of the caller. | +| KEY_REQUIRED_LABELS9+ | "requiredLabels" | Required labels. | +| KEY_BOOLEAN_RESULT9+ | "booleanResult" | Return value of the Boolean type. | ## ResultCode8+ @@ -2125,7 +2125,7 @@ Called to redirect a request. ### onRequestContinued9+ -onRequestContinued: () => void +onRequestContinued?: () => void Called to continue to process the request. 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 f51fee8402c98f9c36e81f355df105a3154e0105..43786f3925b5277d3b806cf638ab7238fe40fd6b 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -23,23 +23,94 @@ import Want from '@ohos.application.Want'; | abilityName | Read only | string | No | Name of the ability. If both **package** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| | uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| | type | Read only | string | No | MIME type, for example, **text/plain** or **image/***. | -| flags | Read only | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-featureAbility.md#flags).| +| flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).| | action | Read only | string | No | Action option. | -| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID of the caller. The **userId** parameter in the [Bundle](js-apis-Bundle.js) module can be used to obtain application and bundle information. | +| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID of the caller. The **userId** parameter in the [Bundle](js-apis-Bundle.md) module can be used to obtain application and bundle information. | | entities | Read only | Array\ | No | List of entities. | | moduleName9+ | Read only | string | No | Module to which the ability belongs.| **Example** -``` js - var want = { - "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", - "moduleName": "entry" // moduleName is optional. - }; - this.context.startAbility(want, (error) => { - // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters uniquely identify an ability. - console.log("error.code = " + error.code) - }) -``` +- Basic usage + + ``` js + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName is optional. + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- Passing a file descriptor (FD) + + ``` js + var fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- Passing **RemoteObject** data + + ``` js + class Stub extends rpc.RemoteObject { + constructor(des) { + if (typeof des == 'string') { + super(des); + } else { + return null; + } + } + + onRemoteRequest(code, data, reply, option) { + if (code === 1) { + console.log('onRemoteRequest called') + let token = data.readInterfaceToken(); + let num = data.readInt(); + this.method(); + return true; + } + return false; + } + + method() { + console.log('method called'); + } + } + + var remoteObject = new Stub('want-test'); + var want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.extreme.test", + "abilityName": "MainAbility", + "moduleName": "entry" // moduleName is optional. + "parameters": { + "keyRemoteObject":{"type":"RemoteObject", "value":remoteObject} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index 42974b5fd683af842146b53fec22022edca84de6..54264312fcc88ad0177473a7e4d256f566e6c2d2 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -1,6 +1,6 @@ # AbilityLifecycleCallback -The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onAbilityWindowStageCreate**, and **onAbilityWindowStageDestroy**, to receive lifecycle state changes in the application context. +The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. > **NOTE** > @@ -30,9 +30,9 @@ Called when an ability is created. | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| -## AbilityLifecycleCallback.onAbilityWindowStageCreate +## AbilityLifecycleCallback.onWindowStageCreate -onAbilityWindowStageCreate(ability: Ability): void; +onWindowStageCreate(ability: Ability, windowStage: window.WindowStage): void; Called when the window stage of an ability is created. @@ -43,11 +43,44 @@ Called when the window stage of an ability is created. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| -## AbilityLifecycleCallback.onAbilityWindowStageDestroy +## AbilityLifecycleCallback.onWindowStageActive -onAbilityWindowStageDestroy(ability: Ability): void; +onWindowStageActive(ability: Ability, windowStage: window.WindowStage): void; + +Called when the window stage of an ability gains focus. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + + +## AbilityLifecycleCallback.onWindowStageInactive + +onWindowStageInactive(ability: Ability, windowStage: window.WindowStage): void; + +Called when the window stage of an ability loses focus. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + + +## AbilityLifecycleCallback.onWindowStageDestroy + +onWindowStageDestroy(ability: Ability, windowStage: window.WindowStage): void; Called when the window stage of an ability is destroyed. @@ -58,6 +91,7 @@ Called when the window stage of an ability is destroyed. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| + | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onAbilityDestroy @@ -132,12 +166,22 @@ Called when an ability is continued on another device. onAbilityCreate(ability){ console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); }, - onAbilityWindowStageCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityWindowStageCreate ability:" + JSON.stringify(ability)); - }, - onAbilityWindowStageDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityWindowStageDestroy ability:" + JSON.stringify(ability)); - }, + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + }, onAbilityDestroy(ability){ console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); }, diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md index cf5291224477451554ea36e823ecedc0629cbfe0..16d5fd0c3d79d097bc8f78ef24cae8f91869b8e3 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -19,7 +19,7 @@ import AbilityContext from '@ohos.application.Ability' let context = this.context.createBundleContext(test); } } - ``` +``` ## Attributes @@ -53,15 +53,15 @@ Creates a context for a given application. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Application bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Application bundle name.| **Return value** -| Type| Description| -| -------- | -------- | -| Context | Context created.| + | Type| Description| + | -------- | -------- | + | Context | Context created.| **Example** @@ -87,15 +87,15 @@ Creates a context for a given HAP. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| moduleName | string | Yes| HAP name in the application.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | moduleName | string | Yes| HAP name in the application.| **Return value** -| Type| Description| -| -------- | -------- | -| Context | Context created.| + | Type| Description| + | -------- | -------- | + | Context | Context created.| **Example** @@ -123,16 +123,16 @@ Creates a context for a given HAP in an application. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | Yes| Application bundle name.| -| moduleName | string | Yes| HAP name in the application.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Application bundle name.| + | moduleName | string | Yes| HAP name in the application.| **Return value** -| Type| Description| -| -------- | -------- | -| Context | Context created.| + | Type| Description| + | -------- | -------- | + | Context | Context created.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md index 05ff78e77e6d6d54527148782b18d0dbca007cd6..1b2bd22548deeed3145803c1a3939e59399b904c 100644 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ b/en/application-dev/reference/apis/js-apis-appmanager.md @@ -22,9 +22,9 @@ Checks whether this application is undergoing a stability test. This API uses an **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -46,9 +46,9 @@ Checks whether this application is undergoing a stability test. This API uses a **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -72,9 +72,9 @@ Checks whether this application is running on a RAM constrained device. This API **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -96,9 +96,9 @@ Checks whether this application is running on a RAM constrained device. This API **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| **Example** @@ -119,9 +119,9 @@ Obtains the memory size of this application. This API uses a promise to return t **Return value** - | Type| Description| - | -------- | -------- | - | Promise<number> | Size of the application memory.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Size of the application memory.| **Example** @@ -143,9 +143,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | No| Size of the application memory.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | No| Size of the application memory.| **Example** @@ -155,7 +155,11 @@ Obtains the memory size of this application. This API uses an asynchronous callb console.log('startAbility result success:' + JSON.stringify(data)); }) ``` -## appManager.getProcessRunningInfos8+ +## appManager.getProcessRunningInfos(deprecated) + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. getProcessRunningInfos(): Promise\>; @@ -181,7 +185,11 @@ Obtains information about the running processes. This API uses a promise to retu }); ``` -## appManager.getProcessRunningInfos8+ +## appManager.getProcessRunningInfos(deprecated) + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. getProcessRunningInfos(callback: AsyncCallback\>): void; @@ -206,11 +214,62 @@ Obtains information about the running processes. This API uses an asynchronous c }) ``` +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(): Promise\>; + +Obtains information about the running processes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the process information.| + +**Example** + + ```js + app.getProcessRunningInformation().then((data) => { + console.log('success:' + JSON.stringify(data)); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(callback: AsyncCallback\>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | No| Callback used to return the process information.| + +**Example** + + ```js + app.getProcessRunningInformation((err, data) => { + console.log('startAbility result failed :' + JSON.stringify(err)); + console.log('startAbility result success:' + JSON.stringify(data)); + }) + ``` + ## appManager.registerApplicationStateObserver8+ registerApplicationStateObserver(observer: ApplicationStateObserver): number; -Registers the application state observer. +Registers an observer to listen for the state of all applications. **Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER @@ -222,7 +281,7 @@ Registers the application state observer. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observer | ApplicationStateObserver | No| Numeric code of the observer.| +| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| **Example** @@ -244,6 +303,48 @@ Registers the application state observer. const observerCode = app.registerApplicationStateObserver(applicationStateObserver); console.log('-------- observerCode: ---------', observerCode); + ``` + +## appManager.registerApplicationStateObserver9+ + +registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array): number; + +Registers an observer to listen for the state of a specified application. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**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| +| -------- | -------- | -------- | -------- | +| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| +| bundleNameList | Array | No| **bundleName** array to be registered for listening. The maximum value is 128.| + +**Example** + + ```js + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + } + } + var bundleNameList = ['bundleName1', 'bundleName2']; + const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList); + console.log('-------- observerCode: ---------', observerCode); + ``` ## appManager.unregisterApplicationStateObserver8+ @@ -258,7 +359,7 @@ Deregisters the application state observer. This API uses an asynchronous callba **System API**: This is a system API and cannot be called by third-party applications. **Parameters** - + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | observerId | number | No| Numeric code of the observer.| @@ -319,7 +420,7 @@ Deregisters the application state observer. This API uses a promise to return th getForegroundApplications(callback: AsyncCallback\>): void; -Obtains applications that run in the foreground. This API uses an asynchronous callback to return the result. +Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -350,7 +451,7 @@ Obtains applications that run in the foreground. This API uses an asynchronous c getForegroundApplications(): Promise\>; -Obtains applications that run in the foreground. This API uses a promise to return the result. +Obtains applications that are running in the foreground. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_RUNNING_INFO @@ -380,7 +481,7 @@ Obtains applications that run in the foreground. This API uses a promise to retu killProcessWithAccount(bundleName: string, accountId: number): Promise\ -Kills the process by bundle name and account ID. This API uses a promise to return the result. +Kills a process by bundle name and account ID. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES @@ -390,10 +491,10 @@ Kills the process by bundle name and account ID. This API uses a promise to retu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| Account ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Example** @@ -414,7 +515,7 @@ app.killProcessWithAccount(bundleName, accountId) killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void -Kills the process by bundle name and account ID. This API uses an asynchronous callback to return the result. +Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -424,11 +525,11 @@ Kills the process by bundle name and account ID. This API uses an asynchronous c **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| Account ID.| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name of an application.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -708,7 +809,7 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); | bundleName8+ | string | Yes | No | Bundle name of an application. | | abilityName8+ | string | Yes | No | Ability name. | | uid8+ | number | Yes | No | User ID. | -| state8+ | number | Yes | No | Application information. | +| state8+ | number | Yes | No | Ability state. | | moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | | abilityType8+ | string | Yes | No | Ability type. | @@ -736,3 +837,16 @@ console.log('-------- processDiedInfo: ---------', processDiedInfo); | uid9+ | Read only | number | No | User ID.| | processName9+ | Read only | string | No | Process name.| | bundleNames9+ | Read only | Array\ | No | **bundleName** array in the running processes.| + +## ApplicationStateObserver + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| [onForegroundApplicationChanged8+](#applicationstateobserveronforegroundapplicationchanged8) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | +| [onAbilityStateChanged8+](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | +| [onProcessCreated8+](#applicationstateobserveronprocesscreated8) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | +| [onProcessDied8+](#applicationstateobserveronprocessdied8) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 473c530ac8c4a2af7fc1bd049bdac984d0740429..a518c72880e74ad35cc76e2f0f8c15f92a0b764f 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -2148,11 +2148,10 @@ Subscribes to audio capturer change events. **System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** - | Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ------------------------------------------------------------------- ---- | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | | type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | -| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | +| callback | Callback\<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | **Example** ``` diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index cbb0ff47c767fd26e499913f44ba88d7e6187f17..67b4a955e1cfe2d9bd557cc47fdc938b010a8de6 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -1,6 +1,6 @@ -# BackgroundTaskManager +# Background Task Management -This module provides background task management. +The **BackgroundTaskManager** module provides APIs to manage background tasks. If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type. @@ -15,7 +15,7 @@ If an application has a service that can be intuitively perceived by users and n ## Modules to Import -``` +```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; ``` @@ -144,12 +144,12 @@ Requests a continuous task from the system. This API uses an asynchronous callba **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ------------------------ | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------- | ---- | ---------------------------------------- | +| context | Context | Yes | Application context.
For 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).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js @@ -196,11 +196,11 @@ Requests a continuous task from the system. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ----------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------- | ---- | ---------------------------------------- | +| context | Context | Yes | Application context.
For 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).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** | Type | Description | @@ -245,10 +245,10 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------- | ---- | ---------------------- | -| context | [Context](js-apis-Context.md) | Yes | Application context. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ---------------------------------------- | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js @@ -276,9 +276,9 @@ Requests to cancel a continuous task. This API uses a promise to return the resu **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------- | ---- | --------- | -| context | [Context](js-apis-Context.md) | Yes | Application context.| +| 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).| **Return value** | Type | Description | @@ -314,14 +314,14 @@ Provides the information about the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -| Name | Value| Description | -| ----------------------- | ------ | ------------------------------------------------------------ | -| DATA_TRANSFER | 1 | Data transfer. | -| AUDIO_PLAYBACK | 2 | Audio playback. | -| AUDIO_RECORDING | 3 | Audio recording. | -| LOCATION | 4 | Positioning and navigation. | -| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | -| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | -| WIFI_INTERACTION | 7 | WLAN-related.
This is a system API and cannot be called by third-party applications.| -| VOIP | 8 | Audio and video calls.
This is a system API and cannot be called by third-party applications.| -| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| DATA_TRANSFER | 1 | Data transfer. | +| AUDIO_PLAYBACK | 2 | Audio playback. | +| AUDIO_RECORDING | 3 | Audio recording. | +| LOCATION | 4 | Positioning and navigation. | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | +| WIFI_INTERACTION | 7 | WLAN-related.
This is a system API.| +| VOIP | 8 | Audio and video calls.
This is a system API. | +| TASK_KEEPING | 9 | Computing task (effective only for specific devices). | diff --git a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 74ba45c52450241572aff5ab9cba2a55debd9124..3cb5f2792733b4ad88914023b7debb7354fa74b4 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,16 +1,11 @@ # AbilityInfo - +Unless otherwise specified, ability information is obtained through **GET_BUNDLE_DEFAULT**. > **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. - - -Provides the ability information. - - +## AbilityInfo **System capability**: SystemCapability.BundleManager.BundleFramework @@ -25,24 +20,24 @@ Provides the ability information. | iconId | number | Yes | No | Ability icon ID. | | moduleName | string | Yes | No | Name of the HAP file to which the ability belongs. | | process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| -| targetAbility | string | Yes | No | Target ability that the ability alias points to. | -| backgroundModes | number | Yes | No | Background service mode of the ability. | +| targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| +| backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | | isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | -| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability. | -| type | AbilityType | Yes | No | Ability type. | +| formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| +| type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | | orientation | DisplayOrientation | Yes | No | Ability display orientation. | | launchMode | LaunchMode | Yes | No | Ability launch mode. | -| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.| +| permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_PERMISSION**.| | deviceTypes | Array\ | Yes | No | Device types supported by the ability. | | deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | -| readPermission | string | Yes | No | Permission required for reading the ability data. | -| writePermission | string | Yes | No | Permission required for writing data to the ability. | -| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information. | -| uri | string | Yes | No | URI of the ability. | +| readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| +| writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing **GET_ABILITY_INFO_WITH_APPLICATION**.| +| uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| | labelId | number | Yes | No | Ability label ID. | -| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. | -| metaData8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Custom metadata of the ability. | -| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. | +| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| +| metaData8+ | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Custom metadata of the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_METADATA**.| +| metadata9+ | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_METADATA**.| | enabled8+ | boolean | Yes | No | Whether the ability is enabled. | | supportWindowMode9+ | Array\<[SupportWindowMode](js-apis-Bundle.md)> | Yes | No | Window modes supported by the ability. | | maxWindowRatio9+ | number | Yes | No | Maximum window ratio supported by the ability. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index 94182ce2915f60bd6998f512d17288920549d3f8..ae94a539b922fc9aca76dbfe80f3b942171c631c 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -18,9 +18,11 @@ The **ApplicationInfo** module provides application information. Unless otherwis | systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | | enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | | label | string | Yes | No | Application label. | -| labelId | string | Yes | No | Application label ID. | +| labelId(deprecated) | string | Yes | No | Application label ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **labelIndex** instead. | +| labelIndex9+ | number | Yes | No | Index of the application label.| | icon | string | Yes | No | Application icon. | -| iconId | string | Yes | No | Application icon ID. | +| iconId(deprecated) | string | Yes | No | Application icon ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **iconIndex** instead. | +| iconIndex9+ | number | Yes | No | Index of the application icon.| | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | | supportedModes | number | Yes | No | Running modes supported by the application. | | moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md new file mode 100644 index 0000000000000000000000000000000000000000..7c86528db55ea364316caaa927b29a90f88b253c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -0,0 +1,100 @@ +# BundleInstaller + +The **BundleInstaller** module provides APIs for installing, updating, and deleting bundles on devices. + +> **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. + +## System Capability + +SystemCapability.BundleManager.BundleFramework + +## BundleInstaller.install + +install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; + +Installs bundles. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.INSTALL_BUNDLE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | +| bundleFilePaths | Array<string> | Yes | Paths where the bundles are stored. Each path should point to a relative directory of the current application's data directory.| +| param | [InstallParam](#installparam) | Yes | Parameters required for the installation or uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status. | + +## BundleInstaller.uninstall + +uninstall(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; + +Uninstalls a bundle. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.INSTALL_BUNDLE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| param | [InstallParam](#installparam) | Yes | Parameters required for the installation or uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| + +## BundleInstaller.recover + +recover(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; + +Recovers a bundle. This API uses an asynchronous callback to return the result. + +**Required permissions** + +ohos.permission.INSTALL_BUNDLE + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | +| bundleName | string | Yes | Bundle name. | +| param | [InstallParam](#installparam) | Yes | Parameters required for the installation or uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| + +## InstallParam + +Describes the parameters required for bundle installation or uninstall. + + **System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Description | +| ----------- | ------- | ------------------ | +| userId | number | User ID. | +| installFlag | number | Installation flag. | +| isKeepData | boolean | Whether data is kept.| + +## InstallStatus + +Describes the bundle installation status. + + **System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | +| status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. | +| statusMessage | string | Yes | No | Installation or uninstall status message.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md index ede83cd6de76637220005f0821471c0141c9721f..205c9f15192c4c2c9abfcb08b1f1ae156d7baf75 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -1,14 +1,14 @@ # ElementName +The **ElementName** module provides the element name information. + > **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. -Provides the element name information. - ## ElementName - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | diff --git a/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..7b932cacbc2195e8c52976aa80e71bd3b638921d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @@ -0,0 +1,20 @@ +# LauncherAbilityInfo + +The **LauncherAbilityInfo** module provides information about a launcher ability. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## LauncherAbilityInfo + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| --------------- | ---------------------------------------------------- | ---- | ---- | ------------------------------------ | +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the launcher ability.| +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the launcher ability. | +| labelId | number | Yes | No | Label ID of the launcher ability. | +| iconId | number | Yes | No | Icon ID of the launcher ability. | +| userId | number | Yes | No | User ID of the launcher ability. | +| installTime | number | Yes | No | Time when the launcher ability is installed. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md new file mode 100644 index 0000000000000000000000000000000000000000..4ebc8d40516c596de2977ea19583e019cce2ac1f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -0,0 +1,19 @@ +# PermissionDef + +The **PermissionDef** module provides permission details defined in the configuration file. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## **PermissionDef** + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | ---- | -------------- | +| permissionName | string | Yes | No | Name of the permission. | +| grantMode | number | Yes | No | Grant mode of the permission.| +| labelId | number | Yes | No | Label ID of the permission. | +| descriptionId | number | Yes | No | Description ID of the permission. | + diff --git a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..8b2cf350047aa0d4c8e165b71b030f3816f6f75f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -0,0 +1,41 @@ +# ShortcutInfo + +The **ShortcutInfo** module provides shortcut information defined in the configuration file. + +> **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. + +## ShortcutWant + +Describes the information about the target to which the shortcut points. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------ | ---- | ---- | -------------------- | +| targetBundle | string | Yes | No | Target bundle of the shortcut.| +| targetModule9+ | string | Yes | No | Target module of the shortcut. | +| targetClass | string | Yes | No | Target class required by the shortcut.| + +## ShortcutInfo + +Describes the shortcut attribute information. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ------------------------------------------ | ---- | ---- | ---------------------------- | +| id | string | Yes | No | ID of the application to which the shortcut belongs. | +| bundleName | string | Yes | No | Name of the bundle that contains the shortcut. | +| hostAbility | string | Yes | No | Local ability information of the shortcut. | +| icon | string | Yes | No | Icon of the shortcut. | +| iconId8+ | number | Yes | No | Icon ID of the shortcut. | +| label | string | Yes | No | Label of the shortcut. | +| labelId8+ | number | Yes | No | Label ID of the shortcut. | +| disableMessage | string | Yes | No | Message displayed when the shortcut is disabled. | +| wants | Array<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | +| isStatic | boolean | Yes | No | Whether the shortcut is static. | +| isHomeShortcut | boolean | Yes | No | Whether the shortcut is a home shortcut.| +| isEnabled | boolean | Yes | No | Whether the shortcut is enabled. | +| moduleName9+ | string | Yes | No | Module name of the shortcut. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..4210ac52230c5e86855c8afacd7c442999efdea6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -0,0 +1,17 @@ +# RemoteAbilityInfo + +The **RemoteAbilityInfo** module provides information about a remote ability. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## RemoteAbilityInfo + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the ability. | +| label | string | Yes | No | Label of the ability. | +| icon | string | Yes | No | Icon of the ability.| diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md index 72fcfaca8fb39e4345c2392e761b19b364922499..544a4ba0d27e6c39794e063fc63282ba5455bf5e 100644 --- a/en/application-dev/reference/apis/js-apis-bytrace.md +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -19,6 +19,10 @@ startTrace(name: string, taskId: number, expectedTime?: number): void Marks the start of a timeslice trace task. +> **NOTE** +> +> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example. + **System capability**: SystemCapability.Developtools.Bytrace **Parameters** @@ -29,9 +33,6 @@ Marks the start of a timeslice trace task. | taskId | number | Yes| ID of a timeslice trace task.| | expectedTime | number | No| Expected duration of the trace, in ms.| -> **NOTE** -> -> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example. **Example** @@ -47,6 +48,10 @@ finishTrace(name: string, taskId: number): void Marks the end of a timeslice trace task. +> **NOTE** +> +> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**. + **System capability**: SystemCapability.Developtools.Bytrace **Parameters** @@ -56,9 +61,6 @@ Marks the end of a timeslice trace task. | name | string | Yes| Name of a timeslice trace task.| | taskId | number | Yes| ID of a timeslice trace task.| -> **NOTE** -> -> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**. **Example** @@ -95,7 +97,7 @@ traceByValue(name: string, count: number): void Defines the variable that indicates the number of timeslice trace tasks. -**System capability**: SystemCapability.Developtools.Bytrace +**System capability**: SystemCapability.HiviewDFX.HiTrace **Parameters** | Name| Type| Mandatory| Description| diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index bb320e0c8b61e2259aa8c31a6d8efa5866c780fa..381796969cdc260896b9ea4857d0461eebf7d519 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -44,7 +44,7 @@ call.dial("138xxxxxxxx", (err, data) => { dial\(phoneNumber: string, options: DialOptions, callback: AsyncCallback\): void -Initiates a call. You can set call options as needed. This API uses an asynchronous callback to return the result. +Initiates a call based on the specified options. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.PLACE\_CALL (a system permission) @@ -73,7 +73,7 @@ call.dial("138xxxxxxxx", { dial\(phoneNumber: string, options?: DialOptions\): Promise -Initiates a call. You can set call options as needed. This API uses a promise to return the result. +Initiates a call based on the specified options. This API uses a promise to return the result. **Required permission**: ohos.permission.PLACE\_CALL (a system permission) @@ -304,7 +304,7 @@ call.isEmergencyPhoneNumber("138xxxxxxxx", (err, data) => { isEmergencyPhoneNumber\(phoneNumber: string, options: EmergencyNumberOptions, callback: AsyncCallback\): void -Checks whether the called number is an emergency number based on the phone number. This API uses an asynchronous callback to return the result. +Checks whether the called number is an emergency number based on the specified phone number options. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CallManager @@ -313,7 +313,7 @@ Checks whether the called number is an emergency number based on the phone numbe | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------------- | ---- | -------------------------------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number option. | +| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: The called number is an emergency number.
- **false**: The called number is not an emergency number. | **Example** @@ -329,7 +329,7 @@ call.isEmergencyPhoneNumber("112", {slotId: 1}, (err, value) => { isEmergencyPhoneNumber\(phoneNumber: string, options?: EmergencyNumberOptions\): Promise -Checks whether the called number is an emergency number based on the phone number. This API uses a promise to return the result. +Checks whether the called number is an emergency number based on the specified phone number options. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CallManager @@ -338,7 +338,7 @@ Checks whether the called number is an emergency number based on the phone numbe | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------------- | ---- | -------------- | | phoneNumber | string | Yes | Phone number. | -| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number option. | +| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. | **Return value** @@ -386,7 +386,7 @@ call.formatPhoneNumber("138xxxxxxxx", (err, data) => { formatPhoneNumber\(phoneNumber: string, options: NumberFormatOptions, callback: AsyncCallback\): void -Formats a phone number based on specified formatting options. This API uses an asynchronous callback to return the result. +Formats a phone number based on the specified formatting options. This API uses an asynchronous callback to return the result. A formatted phone number is a standard numeric string, for example, 555 0100. @@ -397,7 +397,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------- | ---- | ------------------------------------ | | phoneNumber | string | Yes | Phone number. | -| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting option, for example, country code. | +| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. | | callback | AsyncCallback<string> | Yes | Callback used to return the result. | **Example** @@ -415,7 +415,7 @@ call.formatPhoneNumber("138xxxxxxxx",{ formatPhoneNumber\(phoneNumber: string, options?: NumberFormatOptions\): Promise -Formats a phone number based on specified formatting options. This API uses a promise to return the result. +Formats a phone number based on the specified formatting options. This API uses a promise to return the result. A formatted phone number is a standard numeric string, for example, 555 0100. @@ -426,7 +426,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------- | ---- | ---------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting option, for example, country code. | +| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. | **Return value** @@ -514,15 +514,2242 @@ promise.then(data => { }); ``` +## call.muteRinger8+ + +muteRinger\(callback: AsyncCallback\): void + +Mutes the ringtone while it is playing. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.muteRinger((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.muteRinger8+ + +muteRinger\(\): Promise + +Mutes the ringtone while it is playing. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.muteRinger(); +promise.then(data => { + console.log(`muteRinger success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`muteRinger fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.answer7+ + +answer\(callback: AsyncCallback\): void + +Answers a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.answer((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.answer7+ + +answer\(callId: number, callback: AsyncCallback\): void + +Answers a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.answer(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.answer7+ + +answer(callId?: number\): Promise + +Answers a call based on the specified call ID. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.answer(1); +promise.then(data => { + console.log(`answer success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`answer fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.hangup7+ + +hangup\(callback: AsyncCallback\): void + +Ends a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.hangup((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.hangup7+ + +hangup\(callId: number, callback: AsyncCallback\): void + +Ends a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.hangup(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.hangup7+ + +hangup\(callId?: number\): Promise + +Ends a call based on the specified call ID. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.hangup(1); +promise.then(data => { + console.log(`hangup success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`hangup fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.reject7+ + +reject\(callback: AsyncCallback\): void + +Rejects a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.reject((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.reject7+ + +reject\(options: RejectMessageOptions, callback: AsyncCallback\): void + +Rejects a call based on the specified options. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | -------------- | +| options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +call.reject(rejectMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.reject7+ + +reject(callId: number, callback: AsyncCallback): + +Rejects a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.reject(1); +promise.then(data => { + console.log(`reject success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`reject fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.reject7+ + +reject\(callId: number, options: RejectMessageOption, callback: AsyncCallback\): void + +Rejects a call based on the specified call ID and options. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| +| options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +call.reject(1, rejectMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.reject7+ + +reject(callId?: number, options?: RejectMessageOptions\): Promise + +Rejects a call based on the specified call ID and options. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| callId | number | No | Call ID. You can obtain the value by subscribing to **callDetailsChange** events. This parameter is optional from API version 9.| +| options | [RejectMessageOptions](#rejectmessageoptions7) | No | Options for the call rejection message. | + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +let promise = call.reject(1, rejectMessageOptions); +promise.then(data => { + console.log(`reject success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`reject fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.holdCall7+ + +holdCall\(callId: number, callback: AsyncCallback\): void + +Holds a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.holdCall(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.holdCall7+ + +holdCall\(callId: number\): Promise + +Holds a call based on the specified call ID. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.holdCall(1); +promise.then(data => { + console.log(`holdCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`holdCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.unHoldCall7+ + +unHoldCall\(callId: number, callback: AsyncCallback\): void + +Unholds a call based on the specified call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.unHoldCall(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.unHoldCall7+ + +unHoldCall\(callId: number\): Promise + +Unholds a call based on the specified call ID. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.unHoldCall(1); +promise.then(data => { + console.log(`unHoldCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`unHoldCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.switchCall7+ + +switchCall\(callId: number, callback: AsyncCallback\): void + +Switches a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.switchCall(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.switchCall7+ + +switchCall\(callId: number\): Promise + +Switches a call. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.switchCall(1); +promise.then(data => { + console.log(`switchCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`switchCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.combineConference7+ + +combineConference\(callId: number, callback: AsyncCallback\): void + +Combines two calls into a conference call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.combineConference(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.combineConference7+ + +combineConference\(callId: number\): Promise + +Combines two calls into a conference call. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.combineConference(1); +promise.then(data => { + console.log(`combineConference success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`combineConference fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getMainCallId7+ + +getMainCallId\(callId: number, callback: AsyncCallback\): void + +Obtains the main call ID. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | + +**Example** + +```js +call.getMainCallId(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getMainCallId7+ + +getMainCallId\(callId: number\): Promise + +Obtains the main call ID. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.getMainCallId(1); +promise.then(data => { + console.log(`getMainCallId success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getMainCallId fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getSubCallIdList7+ + +getSubCallIdList\(callId: number, callback: AsyncCallback\>\): void + +Obtains the list of subcall IDs. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | ---------------------------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Example** + +```js +call.getSubCallIdList(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getSubCallIdList7+ + +getSubCallIdList\(callId: number\): Promise\> + +Obtains the list of subcall IDs. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ----------------------------- | ----------------------------------- | +| Promise<Array> | Promise used to return the result.| + +**Example** + +```js +let promise = call.getSubCallIdList(1); +promise.then(data => { + console.log(`getSubCallIdList success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getSubCallIdList fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getCallIdListForConference7+ + +getCallIdListForConference\(callId: number, callback: AsyncCallback>\): void + +Obtains the list of call IDs in a conference. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------------------------------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<Array> | Yes | Callback used to return the result. | + +**Example** + +```js +call.getCallIdListForConference(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getCallIdListForConference7+ + +getCallIdListForConference\(callId: number\): Promise\> + +Obtains the list of call IDs in a conference. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ----------------------------- | --------------------------------------- | +| Promise<Array> | Promise used to return the result.| + +**Example** + +```js +let promise = call.getCallIdListForConference(1); +promise.then(data => { + console.log(`getCallIdListForConference success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCallIdListForConference fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getCallWaitingStatus7+ + +getCallWaitingStatus\(slotId: number, callback: AsyncCallback\): void + +Obtains the call waiting status. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback<[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.

- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| + +**Example** + +```js +call.getCallWaitingStatus(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getCallWaitingStatus7+ + +getCallWaitingStatus\(slotId: number\): Promise + +Obtains the call waiting status. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[CallWaitingStatus](#callwaitingstatus7)> | Promise used to return the result.
- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| + +**Example** + +```js +let promise = call.getCallWaitingStatus(0); +promise.then(data => { + console.log(`getCallWaitingStatus success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCallWaitingStatus fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setCallWaiting7+ + +setCallWaiting\(slotId: number, activate: boolean, callback: AsyncCallback\): void + +Sets the call waiting switch. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| activate | boolean | Yes | Whether to enable call waiting.
- **false**: Disable call waiting.
- **true**: Enable call waiting.| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +call.setCallWaiting(0, true, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setCallWaiting7+ + +setCallWaiting\(slotId: number, activate: boolean\): Promise + +Sets the call waiting switch. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ------------------------------------------------------------ | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| activate | boolean | Yes | Whether to enable call waiting.
- **false**: Disable call waiting.
- **true**: Enable call waiting.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.setCallWaiting(0, true); +promise.then(data => { + console.log(`setCallWaiting success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setCallWaiting fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.startDTMF7+ + +startDTMF\(callId: number, character: string, callback: AsyncCallback\): void + +Enables dual-tone multifrequency (DTMF). This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| character | string | Yes | DTMF code. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +call.startDTMF(1, "0", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.startDTMF7+ + +startDTMF\(callId: number, character: string\): Promise + +Enables DTMF. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| +| character | string | Yes | DTMF code.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.startDTMF(1, "0"); +promise.then(data => { + console.log(`startDTMF success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`startDTMF fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.stopDTMF7+ + +stopDTMF\(callId: number, callback: AsyncCallback\): void + +Stops DTMF. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.stopDTMF(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.stopDTMF7+ + +stopDTMF\(callId: number\): Promise + +Stops DTMF. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.stopDTMF(1); +promise.then(data => { + console.log(`stopDTMF success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`stopDTMF fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.isInEmergencyCall7+ + +isInEmergencyCall\(callback: AsyncCallback\): void + +Checks whether a call is an emergency call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +call.isInEmergencyCall((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.isInEmergencyCall7+ + +isInEmergencyCall\(\): Promise + +Checks whether a call is an emergency call. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +let promise = call.isInEmergencyCall(); +promise.then(data => { + console.log(`isInEmergencyCall success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isInEmergencyCall fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.on('callDetailsChange')7+ + +on\(type: 'callDetailsChange', callback: Callback\): void + +Subscribes to **callDetailsChange** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------- | ---- | -------------------------- | +| type | string | Yes | Call details change during a call.| +| callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | Yes | Callback used to return the result. | + +**Example** + +```js +call.on('callDetailsChange', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.on('callEventChange')8+ + +on\(type: 'callEventChange', callback: Callback\): void + +Subscribes to **callEventChange** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | -------------------------- | +| type | string | Yes | Call event change during a call.| +| callback | Callback<[CallEventOptions](#calleventoptions8)> | Yes | Callback used to return the result. | + +**Example** + +```js +call.on('callEventChange', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.on('callDisconnectedCause')8+ + +on\(type: 'callDisconnectedCause', callback: Callback): void + +Subscribes to **callDisconnectedCause** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | -------------------------- | +| type | string | Yes | Cause of the call disconnection.| +| callback | Callback<[DisconnectedDetails](#disconnecteddetails8)> | Yes | Callback used to return the result. | + +**Example** + +```js +call.on('callDisconnectedCause', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.on('mmiCodeResult')9+ + +on\(type: 'mmiCodeResult', callback: Callback\): void + +Subscribes to **mmiCodeResult** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | --------------------- | +| type | string | Yes | Man-machine interface (MMI) code result.| +| callback | Callback<[MmiCodeResults](#mmicoderesults9)> | Yes | Callback used to return the result. | + +**Example** + +```js +isNewCallAllowedcall.on('mmiCodeResult', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.off('callDetailsChange')7+ + +off\(type: 'callDetailsChange', callback?: Callback\): void + +Unsubscribes from **callDetailsChange** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------------- | ---- | ---------------------------------- | +| type | string | Yes | Unsubscription from call details changes when a call ends.| +| callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | No | Callback used to return the result. | + +**Example** + +```js +call.off('callDetailsChange', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.off('callEventChange')8+ + +off\(type: 'callEventChange', callback?: Callback\): void + +Unsubscribes from **callEventChange** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | ---------------------------------- | +| type | string | Yes | Unsubscription from call event changes when a call ends.| +| callback | Callback<[CallEventOptions](#calleventoptions8)> | No | Callback used to return the result. | + +**Example** + +```js +call.off('callEventChange', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.off('callDisconnectedCause')8+ + +off\(type: 'callDisconnectedCause', callback?: Callback\): void + +Unsubscribes from **callDisconnectedCause** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | -------------------- | +| type | 'callDisconnectedCause' | Yes | Unsubscription from the call disconnection cause when a call ends.| +| callback | Callback**<**[DisconnectedDetails](#disconnecteddetails8)> | No | Callback used to return the result. | + +**Example** + +```js +call.off('callDisconnectedCause', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.off('mmiCodeResult')9+ + +off\(type: 'mmiCodeResult', callback?: Callback\): void + +Unsubscribes from **mmiCodeResult** events. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | ----------- | +| type | 'mmiCodeResult' | Yes | MMI code result.| +| callback | Callback<[MmiCodeResults](#mmicoderesults9)> | No | Callback used to return the result. | + +**Example** + +```js +call.off('mmiCodeResult', (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.isNewCallAllowed8+ + +isNewCallAllowed\(callback: AsyncCallback\): void + +Checks whether a new call is allowed. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +call.isNewCallAllowed((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.isNewCallAllowed8+ + +isNewCallAllowed\(\): Promise + +Checks whether a new call is allowed. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +let promise = call.isNewCallAllowed(); +promise.then(data => { + console.log(`isNewCallAllowed success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isNewCallAllowed fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.separateConference8+ + +separateConference\(callId: number, callback: AsyncCallback\): void + +Separates a conference call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.separateConference(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.separateConference8+ + +separateConference\(callId: number\): Promise + +Separates a conference call. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| callId | number | Yes | Call ID.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.separateConference(1); +promise.then(data => { + console.log(`separateConference success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`separateConference fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getCallRestrictionStatus8+ + +getCallRestrictionStatus\(slotId: number, type: CallRestrictionType, callback: AsyncCallback\): void + +Obtains the call restriction status. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [CallRestrictionType](#callrestrictiontype8) | Yes | Call restriction type. | +| callback | AsyncCallback<[RestrictionStatus](#restrictionstatus8)> | Yes | Callback used to return the result. | + +**Example** + +```js +call.getCallRestrictionStatus(0, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getCallRestrictionStatus8+ + +getCallRestrictionStatus\(slotId: number, type: CallRestrictionType\): Promise + +Obtains the call restriction status. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [CallRestrictionType](#callrestrictiontype8) | Yes | Call restriction type. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | --------------------------- | +| Promise<[RestrictionStatus](#restrictionstatus8)> | Promise used to return the result.| + +**Example** + +```js +let promise = call.getCallRestrictionStatus(0, 1); +promise.then(data => { + console.log(`getCallRestrictionStatus success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCallRestrictionStatus fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setCallRestriction8+ + +setCallRestriction\(slotId: number, info: CallRestrictionInfo, callback: AsyncCallback\): void + +Sets the call restriction status. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| info | [CallRestrictionInfo](#callrestrictioninfo8) | Yes | Call restriction information. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let callRestrictionInfo={ + type: 1, + password: "123456", + mode: 1 +} +call.setCallRestriction(0, callRestrictionInfo, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setCallRestriction8+ + +setCallRestriction\(slotId: number, info: CallRestrictionInfo\): Promise + +Sets the call restriction status. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| info | [CallRestrictionInfo](#callrestrictioninfo8) | Yes | Call restriction information. | + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let callRestrictionInfo={ + type: 1, + password: "123456", + mode: 1 +} +let promise = call.setCallRestriction(0, callRestrictionInfo); +promise.then(data => { + console.log(`setCallRestriction success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setCallRestriction fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.getCallTransferInfo8+ + +getCallTransferInfo\(slotId: number, type: CallTransferType, callback: AsyncCallback\): void + +Obtains call transfer information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | +| callback | AsyncCallback<[CallTransferResult](#calltransferresult8)> | Yes | Callback used to return the result. | + +**Example** + +```js +let callTransferTyp={ + CallTransferType: 1 +} +call.getCallTransferInfo(0, callTransferTyp, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.getCallTransferInfo8+ + +getCallTransferInfo\(slotId: number, type: CallTransferType): Promise + +Obtains call transfer information. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | + +**Return value** + +| Type | Description | +| --------------------------------------------------------- | --------------------------- | +| Promise<[CallTransferResult](#calltransferresult8)> | Promise used to return the result.| + +**Example** + +```js +let callTransferTyp={ + CallTransferType: 1 +} +let promise = call.getCallTransferInfo(0, callTransferTyp); +promise.then(data => { + console.log(`getCallTransferInfo success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getCallTransferInfo fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setCallTransfer8+ + +setCallTransfer\(slotId: number, info: CallTransferInfo, callback: AsyncCallback\): void + +Sets call transfer information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| info | [CallTransferInfo](#calltransferinfo8) | Yes | Call transfer information. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let callTransferInfo={ + transferNum: "111", + type: 1, + settingType: 1 +} +call.setCallTransfer(0, callTransferInfo, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setCallTransfer8+ + +setCallTransfer\(slotId: number, info: CallTransferInfo): Promise + +Sets call transfer information. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| info | [CallTransferInfo](#calltransferinfo8) | Yes | Call transfer information. | + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let callTransferInfo={ + transferNum: "111", + type: 1, + settingType: 1 +} +let promise = call.setCallTransfer(0, callTransferInfo); +promise.then(data => { + console.log(`setCallTransfer success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setCallTransfer fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.isRinging8+ + +isRinging\(callback: AsyncCallback\): void + +Checks whether the ringtone is playing. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +call.isRinging((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.isRinging8+ + +isRinging\(\): Promise + +Checks whether the ringtone is playing. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +let promise = call.isRinging(); +promise.then(data => { + console.log(`isRinging success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isRinging fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setMuted8+ + +setMuted\(callback: AsyncCallback\): void + +Sets call muting. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.setMuted((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setMuted8+ + +setMuted\(\): Promise + +Sets call muting. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.setMuted(); +promise.then(data => { + console.log(`setMuted success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setMuted fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.cancelMuted8+ + +cancelMuted(callback: AsyncCallback): void + +Cancels call muting. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.cancelMuted((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.cancelMuted8+ + +cancelMuted(): Promise + +Cancels call muting. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.cancelMuted(); +promise.then(data => { + console.log(`cancelMuted success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`cancelMuted fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.setAudioDevice8+ + +setAudioDevice\(device: AudioDevice, callback: AsyncCallback\): void + +Sets the audio device for a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| device | [AudioDevice](#audiodevice8) | Yes | Audio device.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +call.setAudioDevice(1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setAudioDevice8+ + +setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: AsyncCallback\): void + +Sets the audio device for a call based on the specified options. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | -------------- | +| device | [AudioDevice](#audiodevice8) | Yes | Audio device. | +| options | [AudioDeviceOptions](#audiodeviceoptions9) | Yes | Audio device parameters.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let audioDeviceOptions={ + bluetoothAddress: "IEEE 802-2014" +} +call.setAudioDevice(1, bluetoothAddress, (err, value) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.setAudioDevice8+ + +setAudioDevice(device: AudioDevice, options?: AudioDeviceOptions): Promise + +Sets the audio device for a call based on the specified options. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------ | ---- | ------------------ | +| device | [AudioDevice](#audiodevice8) | Yes | Audio device. | +| options | [AudioDeviceOptions](#audiodeviceoptions9) | No | Audio device parameters.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let audioDeviceOptions={ + bluetoothAddress: "IEEE 802-2014" +} +let promise = call.setAudioDevice(1, audioDeviceOptions); +promise.then(data => { + console.log(`setAudioDevice success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`setAudioDevice fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.joinConference8+ + +joinConference(mainCallId: number, callNumberList: Array, callback: AsyncCallback): void + +Joins a conference call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------- | ---- | --------------- | +| mainCallId | number | Yes | Main call ID. | +| callNumberList | Array | Yes | List of call numbers.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.joinConference(1, "138XXXXXXXX", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.joinConference8+ + +joinConference(mainCallId: number, callNumberList: Array): Promise + +Joins a conference call. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | -------------- | ---- | --------------- | +| mainCallId | number | Yes | Main call ID. | +| callNumberList | Array | Yes | List of call numbers.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.joinConference(1, "138XXXXXXXX"); +promise.then(data => { + console.log(`joinConference success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`joinConference fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.updateImsCallMode8+ + +updateImsCallMode(callId: number, mode: ImsCallMode, callback: AsyncCallback): void + +Updates the IMS call mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | -------------- | +| callId | number | Yes | Call ID. | +| mode | [ImsCallMode](#imscallmode8) | Yes | IMS call mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.updateImsCallMode(1, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.updateImsCallMode8+ + +updateImsCallMode(callId: number, mode: ImsCallMode): Promise + +Updates the IMS call mode. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | -------------- | +| callId | number | Yes | Call ID. | +| mode | [ImsCallMode](#imscallmode8) | Yes | IMS call mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.updateImsCallMode(1, 1); +promise.then(data => { + console.log(`updateImsCallMode success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`updateImsCallMode fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.enableImsSwitch8+ + +enableImsSwitch(slotId: number, callback: AsyncCallback): void + +Enables the IMS switch. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.enableImsSwitch(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.enableImsSwitch8+ + +enableImsSwitch(slotId: number): Promise + +Enables the IMS switch. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.enableImsSwitch(0); +promise.then(data => { + console.log(`enableImsSwitch success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`enableImsSwitch fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.disableImsSwitch8+ + +disableImsSwitch(slotId: number, callback: AsyncCallback): void + +Disables the IMS switch. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +call.disableImsSwitch(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.disableImsSwitch8+ + +disableImsSwitch(slotId: number): Promise + +Disables the IMS switch. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.disableImsSwitch(0); +promise.then(data => { + console.log(`disableImsSwitch success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`disableImsSwitch fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## call.isImsSwitchEnabled8+ + +isImsSwitchEnabled(slotId: number, callback: AsyncCallback): void + +Checks whether the IMS switch is enabled. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. | + +**Example** + +```js +call.isImsSwitchEnabled(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## call.isImsSwitchEnabled8+ + +isImsSwitchEnabled(slotId: number): Promise + +Checks whether the IMS switch is enabled. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let promise = call.isImsSwitchEnabled(0); +promise.then(data => { + console.log(`isImsSwitchEnabled success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`isImsSwitchEnabled fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + ## DialOptions -Provides an option for determining whether a call is a video call. +Defines the dialup options. **System capability**: SystemCapability.Telephony.CallManager -| Name| Type | Mandatory | Description | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| extras | boolean | No | Indication of a video call.
- **true**: video call
- **false** (default): voice call| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| extras | boolean | No | Indication of a video call.
- **true**: video call
- **false** (default): voice call| +| accountId | number | No | Account ID. This API is supported since API version 8. It is a system API. | +| videoState | [VideoStateType](#videostatetype7) | No | Video state type. This API is supported since API version 8. It is a system API. | +| dialScene | [DialScene](#dialscene8) | No | Dialup scenario. This API is supported since API version 8. It is a system API. | +| dialType | [DialType](#dialtype8) | No | Dialup type. This API is supported since API version 8. It is a system API. | ## CallState @@ -539,7 +2766,7 @@ Enumerates call states. ## EmergencyNumberOptions7+ -Provides an option for determining whether a number is an emergency number for the SIM card in the specified slot. +Defines options for determining whether a number is an emergency number. **System capability**: SystemCapability.Telephony.CallManager @@ -549,10 +2776,401 @@ Provides an option for determining whether a number is an emergency number for t ## NumberFormatOptions7+ -Provides an option for number formatting. +Defines the number formatting options. **System capability**: SystemCapability.Telephony.CallManager | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | ---------------------------------------------------------- | | countryCode | string | No | Country code, for example, **CN** (China). All country codes are supported. The default value is **CN**. | + +## ImsCallMode8+ + +Enumerates IMS call modes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------------------- | ---- | ------------------ | +| CALL_MODE_AUDIO_ONLY | 0 | Audio call only. | +| CALL_MODE_SEND_ONLY | 1 | Sending calls only. | +| CALL_MODE_RECEIVE_ONLY | 2 | Receiving calls only. | +| CALL_MODE_SEND_RECEIVE | 3 | Sending and receiving calls.| +| CALL_MODE_VIDEO_PAUSED | 4 | Pausing video calls. | + +## AudioDevice8+ + +Enumerates audio devices. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| -------------------- | ---- | ------------ | +| DEVICE_EARPIECE | 0 | Headset device. | +| DEVICE_SPEAKER | 1 | Speaker device.| +| DEVICE_WIRED_HEADSET | 2 | Wired headset device.| +| DEVICE_BLUETOOTH_SCO | 3 | Bluetooth SCO device. | + +## CallRestrictionType8+ + +Enumerates call restriction types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| --------------------------------------------- | ---- | -------------------------- | +| RESTRICTION_TYPE_ALL_INCOMING | 0 | Barring of all incoming calls. | +| RESTRICTION_TYPE_ALL_OUTGOING | 1 | Barring of all outgoing calls. | +| RESTRICTION_TYPE_INTERNATIONAL | 2 | Barring of international calls. | +| RESTRICTION_TYPE_INTERNATIONAL_EXCLUDING_HOME | 3 | Barring of international calls except those in the home country.| +| RESTRICTION_TYPE_ROAMING_INCOMING | 4 | Barring of incoming roaming calls. | +| RESTRICTION_TYPE_ALL_CALLS | 5 | Barring of all calls. | +| RESTRICTION_TYPE_OUTGOING_SERVICES | 6 | Barring of outgoing services. | +| RESTRICTION_TYPE_INCOMING_SERVICES | 7 | Barring of incoming services. | + +## CallTransferInfo8+ + +Defines the call transfer information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------- | ---- | ---------------- | +| transferNum | string | Yes | Call transfer number. | +| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | +| settingType | [CallTransferSettingType](#calltransfersettingtype8) | Yes | Call transfer setting type.| + +## CallTransferType8+ + +Enumerates call transfer types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| --------------------------- | ---- | ------------ | +| TRANSFER_TYPE_UNCONDITIONAL | 0 | Call forwarding unconditional. | +| TRANSFER_TYPE_BUSY | 1 | Call forwarding busy. | +| TRANSFER_TYPE_NO_REPLY | 2 | Call forwarding on no reply. | +| TRANSFER_TYPE_NOT_REACHABLE | 3 | Call forwarding on no user not reachable.| + +## CallTransferSettingType8+ + +Enumerates call transfer setting types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| -------------------------- | ---- | ------------ | +| CALL_TRANSFER_DISABLE | 0 | Disabling of call transfer.| +| CALL_TRANSFER_ENABLE | 1 | Enabling of call transfer.| +| CALL_TRANSFER_REGISTRATION | 3 | Registration of call transfer.| +| CALL_TRANSFER_ERASURE | 4 | Erasing of call transfer.| + +## CallAttributeOptions7+ + +Defines the call attribute options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------- | ---- | -------------- | +| accountNumber | string | Yes | Account number. | +| speakerphoneOn | boolean | Yes | Speakerphone on.| +| accountId | number | Yes | Account ID. | +| videoState | [VideoStateType](#videostatetype7) | Yes | Video state type. | +| startTime | number | Yes | Start time. | +| isEcc | boolean | Yes | Whether the call is an ECC. | +| callType | [CallType](#calltype7) | Yes | Call type. | +| callId | number | Yes | Call ID. | +| callState | [DetailedCallState](#detailedcallstate7) | Yes | Detailed call state. | +| conferenceState | [ConferenceState](#conferencestate7) | Yes | Conference state. | + +## ConferenceState7+ + +Enumerates conference states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------------------------- | ---- | -------------- | +| TEL_CONFERENCE_IDLE | 0 | Idle state. | +| TEL_CONFERENCE_ACTIVE | 1 | Active state. | +| TEL_CONFERENCE_DISCONNECTING | 2 | Disconnecting state. | +| TEL_CONFERENCE_DISCONNECTED | 3 | Disconnected state.| + +## CallType7+ + +Enumerates call types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ------------- | ---- | ------------ | +| TYPE_CS | 0 | CS call. | +| TYPE_IMS | 1 | IMS call. | +| TYPE_OTT | 2 | OTT call. | +| TYPE_ERR_CALL | 3 | Error call type.| + +## VideoStateType7+ + +Enumerates video state types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------- | ---- | -------- | +| TYPE_VOICE | 0 | Voice state.| +| TYPE_VIDEO | 1 | Video state.| + +## DetailedCallState7+ + +Enumerates detailed call states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ------------------------- | ---- | -------------- | +| CALL_STATUS_ACTIVE | 0 | Active state. | +| CALL_STATUS_HOLDING | 1 | Hold state. | +| CALL_STATUS_DIALING | 2 | Dialing state. | +| CALL_STATUS_ALERTING | 3 | Alerting state. | +| CALL_STATUS_INCOMING | 4 | Incoming state. | +| CALL_STATUS_WAITING | 5 | Waiting state. | +| CALL_STATUS_DISCONNECTED | 6 | Disconnected state.| +| CALL_STATUS_DISCONNECTING | 7 | Disconnecting state. | +| CALL_STATUS_IDLE | 8 | Idle state. | + +## CallRestrictionInfo8+ + +Defines the call restriction information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------ | +| type | [CallRestrictionType](#callrestrictiontype8) | Yes | Call restriction type.| +| password | string | Yes | Password. | +| mode | [CallRestrictionMode](#callrestrictionmode8) | Yes | Call restriction mode.| + +## CallRestrictionMode8+ + +Enumerates call restriction modes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ----------------------------- | ---- | ------------ | +| RESTRICTION_MODE_DEACTIVATION | 0 | Call restriction deactivated.| +| RESTRICTION_MODE_ACTIVATION | 1 | Call restriction activated.| + +## CallEventOptions8+ + +Defines the call event options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------ | ---- | -------------- | +| eventId | [CallAbilityEventId](#callabilityeventid8) | Yes | Call ability event ID.| + +## CallAbilityEventId8+ + +Enumerates call ability event IDs. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ------------------------ | ---- | --------------- | +| EVENT_DIAL_NO_CARRIER | 1 | No available carrier during dialing. | +| EVENT_INVALID_FDN_NUMBER | 2 | Invalid FDN.| + +## DialScene8+ + +Enumerates dialup scenarios. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| --------------- | ---- | ------------ | +| CALL_NORMAL | 0 | Common call. | +| CALL_PRIVILEGED | 1 | Privileged call. | +| CALL_EMERGENCY | 2 | Emergency call.| + +## DialType8+ + +Enumerates dialup types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| -------------------- | ---- | ---------------- | +| DIAL_CARRIER_TYPE | 0 | Carrier. | +| DIAL_VOICE_MAIL_TYPE | 1 | Voice mail.| +| DIAL_OTT_TYPE | 2 | OTT. | + +## RejectMessageOptions7+ + +Defines options for the call rejection message. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | -------- | +| messageContent | string | Yes | Message content.| + +## CallTransferResult8+ + +Defines the call transfer result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------- | ---- | -------- | +| status | [TransferStatus](#transferstatus8) | Yes | Transfer status.| +| number | string | Yes | Number. | + +## CallWaitingStatus7+ + +Enumerates call waiting states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| -------------------- | ---- | ------------ | +| CALL_WAITING_DISABLE | 0 | Call waiting disabled.| +| CALL_WAITING_ENABLE | 1 | Call waiting enabled.| + +## RestrictionStatus8+ + +Enumerates call restriction states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ------------------- | ---- | -------- | +| RESTRICTION_DISABLE | 0 | Call restriction disabled.| +| RESTRICTION_ENABLE | 1 | Call restriction enabled.| + +## TransferStatus8+ + +Enumerates call transfer states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------------- | ---- | -------- | +| TRANSFER_DISABLE | 0 | Call transfer disabled.| +| TRANSFER_ENABLE | 1 | Call transfer enabled.| + +## DisconnectedDetails8+ + +Enumerates causes of call disconnection. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| --------------------------- | ---- | ---------------------- | +| UNASSIGNED_NUMBER | 1 | Unallocated number. | +| NO_ROUTE_TO_DESTINATION | 3 | No route to the destination. | +| CHANNEL_UNACCEPTABLE | 6 | Unacceptable channel. | +| OPERATOR_DETERMINED_BARRING | 8 | Operator determined barring (ODB). | +| NORMAL_CALL_CLEARING | 16 | Normal call clearing. | +| USER_BUSY | 17 | User busy. | +| NO_USER_RESPONDING | 18 | No user response. | +| USER_ALERTING_NO_ANSWER | 19 | Alerting but no answer.| +| CALL_REJECTED | 21 | Call rejected. | +| NUMBER_CHANGED | 22 | Number changed. | +| DESTINATION_OUT_OF_ORDER | 27 | Destination fault. | +| INVALID_NUMBER_FORMAT | 28 | Invalid number format. | +| NETWORK_OUT_OF_ORDER | 38 | Network fault. | +| TEMPORARY_FAILURE | 41 | Temporary fault. | +| INVALID_PARAMETER | 1025 | Invalid parameter. | +| SIM_NOT_EXIT | 1026 | SIM card not exit. | +| SIM_PIN_NEED | 1027 | SIM card PIN required. | +| CALL_NOT_ALLOW | 1029 | Call not allowed. | +| SIM_INVALID | 1045 | Invalid SIM card. | +| UNKNOWN | 1279 | Unknown reason. | + +## MmiCodeResults9+ + +Defines the MMI code result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ------- | -------------------------------- | ---- | --------------- | +| result | [MmiCodeResult](#mmicoderesult9) | Yes | MMI code result.| +| message | string | Yes | MMI code message.| + +## MmiCodeResult9+ + +Enumerates MMI code results. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Value | Description | +| ---------------- | ---- | ------------- | +| MMI_CODE_SUCCESS | 0 | Success.| +| MMI_CODE_FAILED | 1 | Failure.| + +## AudioDeviceOptions9+ + +Defines audio device options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ---------------- | ------ | ---- | -------- | +| bluetoothAddress | string | No | Bluetooth address.| diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 50c4228a23727b230a2ffab82dcf077be5f6682b..d0702995d7955ccf0b7a9907ab09b79efd6268ec 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,161 +1,10 @@ # CommonEvent -> **NOTE** -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **CommonEvent** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. -## Required Permissions - -| Common Event Macro | Common Event Name | Subscriber Permissions | -| ------------ | ------------------ | ---------------------- | -| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | -| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | -| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | -| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | -| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | -| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | -| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | -| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | -| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | -| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | -| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | - | -| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | -| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | -| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | -| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | -| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | -| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | -| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | -| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | -| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | -| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | -| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | -| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | -| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | -| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | -| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | -| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | -| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | -| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | -| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | -| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | -| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | -| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | -| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | -| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | -| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | -| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | -| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | -| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | -| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | -| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | -| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | -| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | -| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | -| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_USERS | -| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_USERS | -| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | -| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_USERS | -| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | -| COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | - | -| COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | - | -| COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | - | -| COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | - | -| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | -| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | -| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | -| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | -| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | -| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | -| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | -| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | -| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | -| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | -| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | -| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | -| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | -| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | -| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | -| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | -| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | -| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_USERS | -| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_USERS | -| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | -| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | -| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | -| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | -| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | -| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | -| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | -| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | -| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | -| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | -| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | -| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | -| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | -| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | -| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | -| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | -| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | -| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | -| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | -| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_VOLUME_REMOVED | usual.event.data.VOLUME_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_VOLUME_UNMOUNTED | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_VOLUME_MOUNTED | usual.event.data.VOLUME_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_VOLUME_BAD_REMOVAL | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_VOLUME_EJECT | usual.event.data.VOLUME_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| -| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | -| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | -| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | -| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | -| COMMON_EVENT_SPLIT_SCREEN | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | +> **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 @@ -163,6 +12,170 @@ import CommonEvent from '@ohos.commonEvent'; ``` +## Support + +Provides the event types supported by the **CommonEvent** module. The name and value indicate the macro and name of a common event, respectively. + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Value | Subscriber Permissions | Description | +| ------------ | ------------------ | ---------------------- | -------------------- | +| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | +| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | +| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | Indicates the common event that the device is being shut down and the final shutdown will proceed. | +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | Indicates the common event that the charging state, level, and other information about the battery have changed. | +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | Indicates the common event that the battery level is low. | +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | Indicates the common event that the battery exits the low state. | +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | Indicates the common event that the device is connected to an external power supply. | +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | Indicates the common event that the device is disconnected from the external power supply. | +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | Indicates the common event that the device screen is off and the device is sleeping. | +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | Indicates the common event that the device screen is on and the device is in interactive state. | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED8+ | usual.event.THERMAL_LEVEL_CHANGED | - | Indicates the common event that the device's thermal level has changed. | +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | Indicates the common event that the user unlocks the device. | +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | Indicates the common event that the system time has changed. | +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | Indicates the common event that the system time is set. | +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | Indicates the common event that the system time has changed. | +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | Indicates the common event that the system time zone has changed. | +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | Indicates the common event that a user closes a temporary system dialog box. | +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | Indicates the common event that a new application package has been installed on the device. | +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | Indicates the common event that a later version of an installed application package has replaced the previous one on the device. | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | Indicates the common event that a later version of your application package has replaced the previous one. | +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | Indicates the common event that an installed application has been uninstalled from the device with the application data retained. | +| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | Indicates the common event that an installed bundle has been uninstalled from the device with the application data retained. | +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | Indicates the common event that an installed application, including both the application data and code, has been completely uninstalled from the device. | +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | Indicates the common event that an application package has been changed (for example, a component in the package has been enabled or disabled). | +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | Indicates the common event that the user has restarted the application package and killed all its processes. | +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | Indicates the common event that the user has cleared the application package data. | +| COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ | usual.event.PACKAGE_CACHE_CLEARED | - | Indicates the common event that the user clears the application package cache. | +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | Indicates the common event that application packages have been suspended. | +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | Indicates the common event that application packages have not been suspended. | +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | Indicates the common event that an application package has been suspended. | +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | Indicates the common event that a user ID has been removed from the system. | +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | Indicates the common event that an installed application is started for the first time. | +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | Indicates the common event that an application requires system verification. | +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | Indicates the common event that an application has been verified by the system. | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | Indicates the common event that applications installed on the external storage become available for the system. | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | Indicates the common event that applications installed on the external storage become unavailable for the system. | +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | Indicates the common event that the device state (for example, orientation and locale) has changed. | +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | Indicates the common event that the device locale has changed. | +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | Indicates the common event that the device storage is insufficient. | +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | Indicates the common event that the system is in driving mode. | +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | Indicates the common event that the system is in home mode. | +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | Indicates the common event that the system is in office mode. | +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. | +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. | +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. | +| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_USERS | Indicates the common event that user switching is happening. | +| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_USERS | Indicates the common event that the user is going to be started. | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | +| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_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. | +| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | Indicates the common event that the Wi-Fi connection state has changed. | +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | Indicates the common event about the Wi-Fi hotspot state, such as enabled or disabled. | +| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | Indicates the common event that a client has joined the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |Indicates the common event that a client has disconnected from the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | Indicates the common event that the state of MPLINK (an enhanced Wi-Fi feature) has changed. | +| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Indicates the common event that the Wi-Fi P2P connection state has changed. | +| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P state, such as enabled and disabled. | +| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of Wi-Fi P2P peer devices. | +| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P discovery status change. | +| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of the Wi-Fi P2P local device. | +| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi P2P group information has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth handsfree communication. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected to the Bluetooth handsfree is active. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth A2DP. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected using Bluetooth A2DP is active. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the AVRCP connection state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio codec state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | Indicates the common event that a remote Bluetooth device is discovered. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth class of a remote Bluetooth device has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been established with a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been disconnected from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the friendly name of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of a remote Bluetooth device has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the battery level of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | Indicates the common event about the SDP state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the UUID connection state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the pairing request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | Indicates the common event that Bluetooth pairing is canceled. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | Indicates the common event about the connection request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | Indicates the common event about the response to the connection request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | Indicates the common event that the connection to a remote Bluetooth device has been canceled. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | Indicates the common event that the connection state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | Indicates the common event that the audio state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | Indicates the common event that the audio gateway state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | Indicates the common event that the calling state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the state of a Bluetooth adapter has been changed, for example, Bluetooth has been enabled or disabled. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | Indicates the common event about the request for the user to allow Bluetooth device scanning. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to enable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to disable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning mode of a device has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning has been started on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning is finished on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth adapter name of the device has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | Indicates the common event that the state of the device's NFC adapter has changed. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the enabled state. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the disabled state. | +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | Indicates the common event that the system stops charging the battery. | +| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. | +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. | +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. | +| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_USERS | Indicates the common event that a user has been added to the system. | +| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_USERS | Indicates the common event that a user has been removed from the system. | +| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | +| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | +| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | +| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | Indicates the common event that the location mode of the system has changed. | +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | Indicates the common event that the in-vehicle infotainment (IVI) system of a vehicle is sleeping. | +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | Indicates the common event that the IVI system of a vehicle has entered sleep mode and the playing application is instructed to stop playback. | +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | Indicates the common event that a third-party application is instructed to pause the current work. | +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | Indicates the common event that a third-party application is instructed to save its last mode. | +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | Indicates the common event that the voltage of the vehicle's power system is abnormal. | +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is high. | +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is extremely high. | +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | Indicates the common event that the IVI system has an extreme temperature. | +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | Indicates the common event that the voltage of the vehicle's power system is restored to normal. | +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | Indicates the common event that the temperature of the IVI system is restored to normal. | +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | Indicates the common event that the battery service is active. | +|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | - | Indicates the common event that the USB device status has changed. | +|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | - | Indicates the common event that the USB port status of the user device has changed. | +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | Indicates the common event that a USB device has been attached when the user device functions as a USB host. | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device becomes unmountable. | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.WRITE_USER_STORAGE or ohos.permission.READ_USER_STORAGE| Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | +| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | +| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | +| COMMON_EVENT_SPLIT_SCREEN8+ | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has changed. | +| COMMON_EVENT_SPN_INFO_CHANGED9+ | usual.event.SPN_INFO_CHANGED | - | Indicates the common event that the SPN displayed has been updated. | + + ## CommonEvent.publish publish(event: string, callback: AsyncCallback\): void @@ -181,7 +194,7 @@ Publishes a common event. This API uses a callback to return the result. **Example** ```js -// Callback for common event publication. +// Callback for common event publication function PublishCallBack(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); @@ -218,8 +231,8 @@ Publishes a common event with given attributes. This API uses a callback to retu ```js // Attributes of a common event. var options = { - code: 0, // Result code of the common event - data: "initial data",// Result data of the common event + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event. isOrdered: true // The common event is an ordered one. } @@ -246,6 +259,8 @@ Publishes a common event to a specific user. This API uses a callback to return **System capability**: SystemCapability.Notification.CommonEvent +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable/Writable| Type | Mandatory| Description | @@ -257,7 +272,7 @@ Publishes a common event to a specific user. This API uses a callback to return **Example** ```js -// Callback for common event publication. +// Callback for common event publication function PublishAsUserCallBack(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); @@ -283,6 +298,8 @@ Publishes a common event with given attributes to a specific user. This API uses **System capability**: SystemCapability.Notification.CommonEvent +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable/Writable| Type | Mandatory| Description | @@ -298,8 +315,8 @@ Publishes a common event with given attributes to a specific user. This API uses ```js // Attributes of a common event. var options = { - code: 0, // Result code of the common event - data: "initial data",// Result data of the common event + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event } // Callback for common event publication @@ -560,7 +577,7 @@ Obtains the result code of this common event. This API uses a promise to return | Type | Description | | ---------------- | -------------------- | -| Promise\ | Promise used to return the result code.| +| Promise\ | Promise used to return the result.| **Example** @@ -623,7 +640,7 @@ Sets the result code for this common event. This API uses a promise to return th | Type | Description | | ---------------- | -------------------- | -| Promise\ | Promise used to return the result code.| +| Promise\ | Promise used to return the result.| **Example** @@ -742,7 +759,7 @@ Sets the result data for this common event. This API uses a promise to return th | Type | Description | | ---------------- | -------------------- | -| Promise\ | Promise used to return the result data.| +| Promise\ | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index 6adaa00f48cfb7f2e685841e013e3d719bc58548..f6702d14d391a025bf9a16f2d8bf79a97772ed0a 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -1,10 +1,12 @@ # Data Share Result Set -The **DataShareResultSet** module provides methods for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. +The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. ->**NOTE** +> **NOTE** > ->The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The 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 @@ -13,7 +15,7 @@ The **DataShareResultSet** module provides methods for accessing the result set import DataShareResultSet from '@ohos.data.DataShareResultSet'; ``` -## How to Use +## Usage You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShareResultSet** object. @@ -44,7 +46,10 @@ dataShareHelper.query(uri, da, columns).then((data) => { }); ``` -## Attributes +## DataShareResultSet +Provides methods for accessing the result sets generated by querying the database. + +### Attributes **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -55,7 +60,7 @@ dataShareHelper.query(uri, da, columns).then((data) => { | rowCount | number | Yes | Number of rows in the result set. | | isClosed | boolean | Yes | Whether the result set is closed.| -## goToFirstRow +### goToFirstRow goToFirstRow(): boolean @@ -76,7 +81,7 @@ let isGoTOFirstRow = resultSet.goToFirstRow(); console.info('resultSet.goToFirstRow: ' + isGoTOFirstRow); ``` -## goToLastRow +### goToLastRow goToLastRow(): boolean @@ -97,7 +102,7 @@ let isGoToLastRow = resultSet.goToLastRow(); console.info('resultSet.goToLastRow: ' + isGoToLastRow); ``` -## goToNextRow +### goToNextRow goToNextRow(): boolean @@ -118,7 +123,7 @@ let isGoToNextRow = resultSet.goToNextRow(); console.info('resultSet.goToNextRow: ' + isGoToNextRow); ``` -## goToPreviousRow +### goToPreviousRow goToPreviousRow(): boolean @@ -139,7 +144,7 @@ let isGoToPreviousRow = resultSet.goToPreviousRow(); console.info('resultSet.goToPreviousRow: ' + isGoToPreviousRow); ``` -## goTo +### goTo goTo(offset:number): boolean @@ -167,7 +172,7 @@ let isGoTo = resultSet.goTo(goToNum); console.info('resultSet.goTo: ' + isGoTo); ``` -## goToRow +### goToRow goToRow(position: number): boolean @@ -179,7 +184,7 @@ Moves to the specified row in the result set. | **Name**| **Type**| **Mandatory**| Description | | ---------- | -------- | -------- | ------------------------ | -| position | number | Yes | Destination position to move.| +| position | number | Yes | Destination position to move to.| **Return value** @@ -195,11 +200,11 @@ let isGoToRow = resultSet.goToRow(goToRowNum); console.info('resultSet.goToRow: ' + isGoToRow); ``` -## getBlob +### getBlob getBlob(columnIndex: number): Uint8Array -Obtains the value in the specified column in the current row as a byte array. +Obtains the value in the form of a byte array based on the specified column and the current row. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -224,11 +229,11 @@ let getBlob = resultSet.getBlob(columnIndex); console.info('resultSet.getBlob: ' + getBlob); ``` -## getString +### getString getString(columnIndex: number): *string* -Obtains the value in the specified column in the current row as a string. +Obtains the value in the form of a string based on the specified column and the current row. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -253,11 +258,11 @@ let getString = resultSet.getString(columnIndex); console.info('resultSet.getString: ' + getString); ``` -## getLong +### getLong getLong(columnIndex: number): number -Obtains the value in the specified column in the current row as a long integer. +Obtains the value in the form of a long integer based on the specified column and the current row. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -282,11 +287,11 @@ let getLong = resultSet.getLong(columnIndex); console.info('resultSet.getLong: ' + getLong); ``` -## getDouble +### getDouble getDouble(columnIndex: number): number -Obtains the value in the specified column in the current row as a double-precision floating-point number. +Obtains the value in the form of a double-precision floating-point number based on the specified column and the current row. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -311,7 +316,7 @@ let getDouble = resultSet.getDouble(columnIndex); console.info('resultSet.getDouble: ' + getDouble); ``` -## close +### close close(): void @@ -325,7 +330,7 @@ Closes this result set. resultSet.close(); ``` -## getColumnIndex +### getColumnIndex getColumnIndex(columnName: string): number @@ -353,7 +358,7 @@ let getColumnIndex = resultSet.getColumnIndex(ColumnName) console.info('resultSet.getColumnIndex: ' + getColumnIndex); ``` -## getColumnName +### getColumnName getColumnName(columnIndex: number): *string* @@ -381,7 +386,7 @@ let getColumnName = resultSet.getColumnName(columnIndex) console.info('resultSet.getColumnName: ' + getColumnName); ``` -## getDataType +### getDataType getDataType(columnIndex: number): DataType diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 16c1c1c7b622782a577719bae992d10b1f4634a0..2f54d7d7c47b10403fbc96edf92ce1d55cdcb41b 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -1,10 +1,12 @@ # Data Share Predicates -You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data with **DataShare**. +You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. ->**NOTE** +> **NOTE** > ->The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The 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 @@ -13,11 +15,14 @@ You can use **DataSharePredicates** to specify conditions for [updating](js-apis import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` -## equalTo +## DataSharePredicates +Provides methods for setting different **DataSharePredicates** objects. + +### equalTo equalTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is equal to the specified value. Currently, only the relational database (RDB) and key-value database (KVDB, schema) support this **DataSharePredicates** object. @@ -34,7 +39,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -43,11 +48,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose") ``` -## notEqualTo +### notEqualTo notEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value not equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is not equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -64,7 +69,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -73,11 +78,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notEqualTo("NAME", "Rose") ``` -## beginWrap +### beginWrap beginWrap(): DataSharePredicates -Adds a left parenthesis to this **DataSharePredicates**. Currently, only the RDB supports this **DataSharePredicates** object. +Adds a left parenthesis to this **DataSharePredicates**. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -99,11 +106,13 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -## endWrap +### endWrap endWrap(): DataSharePredicates -Adds a right parenthesis to this **DataSharePredicates** object. Currently, only the RDB supports this **DataSharePredicates** object. +Adds a right parenthesis to this **DataSharePredicates** object. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -125,7 +134,7 @@ predicates.equalTo("NAME", "lisi") .endWrap() ``` -## or +### or or(): DataSharePredicates @@ -150,7 +159,7 @@ predicates.equalTo("NAME", "lisi") .equalTo("NAME", "Rose") ``` -## and +### and and(): DataSharePredicates @@ -175,11 +184,13 @@ predicates.equalTo("NAME", "lisi") .equalTo("SALARY", 200.5) ``` -## contains +### contains contains(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the string that contains the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that contains the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -188,13 +199,13 @@ Sets a **DataSharePredicates** object to match the string that contains the spec | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value contained in the string.| +| value | string | Yes | Value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -203,11 +214,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.contains("NAME", "os") ``` -## beginsWith +### beginsWith beginsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that starts with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that begins with the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -216,13 +229,13 @@ Sets a **DataSharePredicates** object to match a string that starts with the spe | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Start value of the string.| +| value | string | Yes | Start value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -231,11 +244,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.beginsWith("NAME", "os") ``` -## endsWith +### endsWith endsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that ends with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that ends with the specified value. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -244,13 +259,13 @@ Sets a **DataSharePredicates** object to match a string that ends with the speci | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | End value of the string.| +| value | string | Yes | End value to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -259,11 +274,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.endsWith("NAME", "os") ``` -## isNull +### isNull isNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the field whose value is null. +Sets a **DataSharePredicates** object to match the data whose value is null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -279,7 +294,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -288,11 +303,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.isNull("NAME") ``` -## isNotNull +### isNotNull isNotNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the field whose value is not null. +Sets a **DataSharePredicates** object to match the data whose value is not null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -308,7 +323,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -317,11 +332,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.isNotNull("NAME") ``` -## like +### like like(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that is similar to the specified value. +Sets a **DataSharePredicates** object to match the data that is similar to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -338,7 +353,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -347,11 +362,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.like("NAME", "%os%") ``` -## unlike +### unlike unlike(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a string that is not similar to the specified value. +Sets a **DataSharePredicates** object to match the data that is not not similar to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -368,7 +383,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -377,11 +392,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.unlike("NAME", "%os%") ``` -## glob +### glob glob(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the specified string. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the specified string. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -396,7 +413,7 @@ Sets a **DataSharePredicates** object to match the specified string. Currently, | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified string.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -405,11 +422,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.glob("NAME", "?h*g") ``` -## between +### between between(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value within the specified range. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that is within the specified range. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -425,7 +444,7 @@ Sets a **DataSharePredicates** object to match the field with data type **ValueT | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -434,11 +453,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.between("AGE", 10, 50) ``` -## notBetween +### notBetween notBetween(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value out of the specified range. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data that is out of the specified range. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -454,7 +475,7 @@ Sets a **DataSharePredicates** object to match the field with data type **ValueT | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -463,11 +484,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notBetween("AGE", 10, 50) ``` -## greaterThan +### greaterThan greaterThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value greater than the specified value. +Sets a **DataSharePredicates** object to match the data that is greater than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -484,7 +505,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -493,11 +514,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.greaterThan("AGE", 10) ``` -## lessThan +### lessThan lessThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value less than the specified value. +Sets a **DataSharePredicates** object to match the data that is less than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -514,7 +535,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -523,11 +544,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.lessThan("AGE", 50) ``` -## greaterThanOrEqualTo +### greaterThanOrEqualTo greaterThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value greater than or equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is greater than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -544,7 +565,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -553,11 +574,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.greaterThanOrEqualTo("AGE", 10) ``` -## lessThanOrEqualTo +### lessThanOrEqualTo lessThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **ValueType** and value less than or equal to the specified value. +Sets a **DataSharePredicates** object to match the data that is less than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -574,7 +595,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -583,11 +604,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.lessThanOrEqualTo("AGE", 50) ``` -## orderByAsc +### orderByAsc orderByAsc(field: string): DataSharePredicates -Sets a **DataSharePredicates** object that sorts the values in a column in ascending order. +Sets a **DataSharePredicates** object that sorts data in ascending order. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -603,7 +624,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -612,11 +633,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.orderByAsc("AGE") ``` -## orderByDesc +### orderByDesc orderByDesc(field: string): DataSharePredicates -Sets a **DataSharePredicates** object that sorts the values in a column in descending order. +Sets a **DataSharePredicates** object that sorts data in descending order. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -632,7 +653,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -641,11 +662,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.orderByDesc("AGE") ``` -## distinct +### distinct distinct(): DataSharePredicates -Sets a **DataSharePredicates** object to filter out duplicate records. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to filter out duplicate data records. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -653,7 +676,7 @@ Sets a **DataSharePredicates** object to filter out duplicate records. Currently | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -662,7 +685,7 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose").distinct() ``` -## limit +### limit limit(total: number, offset: number): DataSharePredicates @@ -683,7 +706,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -692,11 +715,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.equalTo("NAME", "Rose").limit(10, 3) ``` -## groupBy +### groupBy groupBy(fields: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to group the records according to the specified parameters. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object group the records according to the specified fields. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -704,13 +729,13 @@ Sets a **DataSharePredicates** object to group the records according to the spec | Name| Type | Mandatory| Description | | ------ | ------------- | ---- | -------------------- | -| fields | Array<string> | Yes | Names of the columns to group.| +| fields | Array<string> | Yes | Names of the columns by which the records are grouped.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -719,11 +744,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.groupBy(["AGE", "NAME"]) ``` -## indexedBy +### indexedBy indexedBy(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to specify the index column. Currently, only the RDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to list data by the specified index. + +Currently, only the RDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -737,7 +764,7 @@ Sets a **DataSharePredicates** object to specify the index column. Currently, on | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -746,11 +773,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.indexedBy("SALARY_INDEX") ``` -## in +### in in(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **Array** and value within the specified range. +Sets a **DataSharePredicates** object to match the data that is within the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -761,13 +788,13 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes| Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of **ValueType**s to match.| +| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -776,11 +803,11 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.in("AGE", [18, 20]) ``` -## notIn +### notIn notIn(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the field with data type **Array** and value out of the specified range. +Sets a **DataSharePredicates** object to match the data that is not in the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -791,13 +818,13 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of **ValueType**s to match.| +| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -806,11 +833,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.notIn("NAME", ["Lisa", "Rose"]) ``` -## prefixKey +### prefixKey prefixKey(prefix: string): DataSharePredicates -Sets a **DataSharePredicates** object to match a field with the specified key prefix. Currently, only the KVDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data with the specified key prefix. + +Currently, only the KVDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -824,7 +853,7 @@ Sets a **DataSharePredicates** object to match a field with the specified key pr | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** @@ -833,11 +862,13 @@ let predicates = new dataSharePredicates.DataSharePredicates() predicates.prefixKey("NAME") ``` -## inKeys +### inKeys inKeys(keys: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to match the fields whose keys are within the given range. Currently, only the KVDB supports this **DataSharePredicates** object. +Sets a **DataSharePredicates** object to match the data whose keys are within the given range. + +Currently, only the KVDB supports this **DataSharePredicates** object. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -851,7 +882,7 @@ Sets a **DataSharePredicates** object to match the fields whose keys are within | Type | Description | | ------------------------------------------- | -------------------------- | -| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object that matches the specified field.| +| [DataSharePredicates](#datasharepredicates) | **DataSharePredicates** object created.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index 83875a6edb8aa2395b8750e70fb86b7fa596b03d..6f24aa3255f0340e0ad8ef248ae25d62092e0774 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,6 +1,6 @@ # Distributed Data Object -The distributedDataObject module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. +The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. > **NOTE**
> @@ -307,7 +307,7 @@ g_object.save("local").then((result)=>{ ### revokeSave9+ -revokeSave(callback: AsyncCallback<SaveSuccessResponse>): void +revokeSave(callback: AsyncCallback<RevokeSaveSuccessResponse>): void Revokes the saving operation of a distributed data object. This API uses an asynchronous callback to return the result. @@ -334,7 +334,7 @@ g_object.revokeSave((result, data) =>{ ### revokeSave9+ -revokeSave(): Promise<SaveSuccessResponse> +revokeSave(): Promise<RevokeSaveSuccessResponse> Revokes the saving operation of a distributed data object. This API uses a promise to return the result. 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 38c07d6247487e037e9158a00e5c2f752621b44e..296b8a58c2e89677eed23ee377c7568603429646 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -4,7 +4,7 @@ The relational database (RDB) manages data based on relational models. With the This module provides the following RDB-related functions: -- [RdbPredicates](#rdbpredicates): predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. +- [RdbPredicates](#rdbpredicates): provides predicates indicating the nature, feature, or relationship of a data entity in an RDB store. It is used to define the operation conditions for an RDB store. - [RdbStore](#rdbstore): provides APIs for managing an RDB store. > **NOTE**
@@ -85,7 +85,7 @@ promise.then(async (rdbStore) => { deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void -Deletes an RDB store. This API uses an asynchronous callback to return the result. +Deletes an RDB store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -166,14 +166,14 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates -Specifies a remote device on the network during distributed database synchronization. +Connects to the specified remote devices on the network during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| devices | Array<string> | Yes| ID of the remote device to specify.| +| devices | Array<string> | Yes| IDs of the remote devices in the same network.| **Return value** | Type| Description| @@ -211,7 +211,7 @@ predicates.inAllDevices() equalTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -238,7 +238,7 @@ predicates.equalTo("NAME", "lisi") notEqualTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -362,7 +362,7 @@ predicates.equalTo("NAME", "Lisa") contains(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string containing the specified value. +Sets an **RdbPredicates** to match a string containing the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -389,7 +389,7 @@ predicates.contains("NAME", "os") beginsWith(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that starts with the specified value. +Sets an **RdbPredicates** to match a string that starts with the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -416,7 +416,7 @@ predicates.beginsWith("NAME", "os") endsWith(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that ends with the specified value. +Sets an **RdbPredicates** to match a string that ends with the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -443,7 +443,7 @@ predicates.endsWith("NAME", "se") isNull(field: string): RdbPredicates -Sets the **RdbPredicates** to match the field whose value is null. +Sets an **RdbPredicates** to match the field whose value is null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -469,7 +469,7 @@ predicates.isNull("NAME") isNotNull(field: string): RdbPredicates -Sets the **RdbPredicates** to match the field whose value is not null. +Sets an **RdbPredicates** to match the field whose value is not null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -495,7 +495,7 @@ predicates.isNotNull("NAME") like(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match a string that is similar to the specified value. +Sets an **RdbPredicates** to match a string that is similar to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -522,7 +522,7 @@ predicates.like("NAME", "%os%") glob(field: string, value: string): RdbPredicates -Sets the **RdbPredicates** to match the specified string. +Sets an **RdbPredicates** to match the specified string. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -549,7 +549,7 @@ predicates.glob("NAME", "?h*g") between(field: string, low: ValueType, high: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -577,7 +577,7 @@ predicates.between("AGE", 10, 50) notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -604,7 +604,7 @@ predicates.notBetween("AGE", 10, 50) greaterThan(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -631,7 +631,7 @@ predicates.greaterThan("AGE", 18) lessThan(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. +Sets an **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -659,7 +659,7 @@ predicates.lessThan("AGE", 20) greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. +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 @@ -687,7 +687,7 @@ predicates.greaterThanOrEqualTo("AGE", 18) lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. +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 @@ -715,7 +715,7 @@ predicates.lessThanOrEqualTo("AGE", 20) orderByAsc(field: string): RdbPredicates -Sets the **RdbPredicates** to match the column with values sorted in ascending order. +Sets an **RdbPredicates** to match the column with values sorted in ascending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -742,7 +742,7 @@ predicates.orderByAsc("NAME") orderByDesc(field: string): RdbPredicates -Sets the **RdbPredicates** to match the column with values sorted in descending order. +Sets an **RdbPredicates** to match the column with values sorted in descending order. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -768,7 +768,7 @@ predicates.orderByDesc("AGE") distinct(): RdbPredicates -Sets the **RdbPredicates** to filter out duplicate records. +Sets an **RdbPredicates** to filter out duplicate records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -789,7 +789,7 @@ predicates.equalTo("NAME", "Rose").distinct("NAME") limitAs(value: number): RdbPredicates -Sets the **RdbPredicates** to specify the maximum number of records. +Sets an **RdbPredicates** to specify the maximum number of records. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -815,7 +815,7 @@ predicates.equalTo("NAME", "Rose").limitAs(3) offsetAs(rowOffset: number): RdbPredicates -Sets the **RdbPredicates** to specify the start position of the returned result. +Sets an **RdbPredicates** to specify the start position of the returned result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -841,7 +841,7 @@ predicates.equalTo("NAME", "Rose").offsetAs(3) groupBy(fields: Array<string>): RdbPredicates -Sets the **RdbPredicates** to group rows that have the same value into summary rows. +Sets an **RdbPredicates** to group rows that have the same value into summary rows. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -866,7 +866,7 @@ predicates.groupBy(["AGE", "NAME"]) indexedBy(field: string): RdbPredicates -Sets the **RdbPredicates** object to specify the index column. +Sets an **RdbPredicates** object to specify the index column. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -893,7 +893,7 @@ predicates.indexedBy("SALARY_INDEX") in(field: string, value: Array<ValueType>): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. +Sets an **RdbPredicates** to match the field with data type **Array<ValueType>** and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -921,7 +921,7 @@ predicates.in("AGE", [18, 20]) notIn(field: string, value: Array<ValueType>): RdbPredicates -Sets the **RdbPredicates** to match the field with data type **Array<ValueType>** and value out of the specified range. +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 @@ -948,6 +948,8 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) Provides methods to manage an RDB store. +Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). + ### insert @@ -972,12 +974,12 @@ const valueBucket = { "SALARY": 100.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } -rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { - if (err) { - console.info("Failed to insert data, err: " + err) - return +rdbStore.insert("EMPLOYEE", valueBucket, function (status, rowId) { + if (status) { + console.log("Failed to insert data"); + return; } - console.log("Inserted first row: " + ret) + console.log("Inserted data successfully, rowId = " + rowId); }) ``` @@ -1010,13 +1012,107 @@ const valueBucket = { "CODES": new Uint8Array([1, 2, 3, 4, 5]), } let promise = rdbStore.insert("EMPLOYEE", valueBucket) -promise.then(async (ret) => { - console.log("Inserted first row: " + ret) -}).catch((err) => { - console.log("Failed to insert data, err: " + err) +promise.then((rowId) => { + console.log("Inserted data successfully, rowId = " + rowId); +}).catch((status) => { + console.log("Failed to insert data"); }) ``` +### batchInsert9+ + +batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void + +Batch inserts data into a table. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| values | Array<[ValuesBucket](#valuesbucket)> | Yes| An array of data to insert.| +| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { + if (status) { + console.log("Failed to batch insert data, status = " + status); + return; + } + console.log("Batch inserted data successfully. The number of values that were inserted = " + insertNum); +}) +``` + +### batchInsert9+ + +batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> + +Batch inserts data into a table. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| table | string | Yes| Name of the target table.| +| values | Array<[ValuesBucket](#valuesbucket)> | Yes| An array of data to insert.| + +**Return value** +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result. If the operation is successful, the number of inserted data records is returned. Otherwise, **-1** is returned.| + +**Example** +```js +const valueBucket1 = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]) +} +const valueBucket2 = { + "NAME": "Jack", + "AGE": 19, + "SALARY": 101.5, + "CODES": new Uint8Array([6, 7, 8, 9, 10]) +} +const valueBucket3 = { + "NAME": "Tom", + "AGE": 20, + "SALARY": 102.5, + "CODES": new Uint8Array([11, 12, 13, 14, 15]) +} + +var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); +promise.then((insertNum) => { + console.log("Batch inserted data successfully. The number of values that were inserted = " + insertNum); +}).catch((status) => { + console.log("Failed to batch insert data, status = " + status); +}) +``` ### update @@ -1029,7 +1125,7 @@ Updates data in the RDB store based on the specified **RdbPredicates** object. T **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. 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.| @@ -1057,14 +1153,14 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { update(values: ValuesBucket, predicates: RdbPredicates):Promise<number> -Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result. +Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| +| values | [ValuesBucket](#valuesbucket) | Yes| Data to update. 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** @@ -1287,7 +1383,7 @@ promise.then((rows) => { query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1317,7 +1413,7 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e query(predicates: RdbPredicates, columns?: Array<string>):Promise<ResultSet> -Queries data in the RDB store based on specified conditions. This API uses a promise to return the result. +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1330,7 +1426,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro **Return value** | Type| Description| | -------- | -------- | -| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +| 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 @@ -1349,7 +1445,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void -Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. +Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1362,6 +1458,7 @@ Queries data in the RDB store based on specified conditions. This API uses an as | callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| **Example** + ```js import dataSharePredicates from '@ohos.data.dataSharePredicates' let predicates = new dataSharePredicates.DataSharePredicates() @@ -1380,7 +1477,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> -Queries data in the RDB store based on specified conditions. This API uses a promise to return the result. +Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1392,6 +1489,7 @@ Queries data in the RDB store based on specified conditions. This API uses a pro | 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.| @@ -1410,6 +1508,76 @@ promise.then((resultSet) => { }) ``` +### remoteQuery9+ + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void + +Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| device | string | Yes| Network ID of the remote device.| +| table | string | Yes| Name of the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| +| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new rdb.RdbPredicates('EPLOYEE') +predicates.greaterThan("id", 0) +rdbStore.remoteQuery("deviceId", "EPLOYEE", predicates, function(err, resultSet){ + if (err) { + console.info("Failed to remoteQuery, err: " + err) + return + } + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}) +``` + +### remoteQuery9+ + +remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> + +Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| device | string | Yes| Network ID of the remote device.| +| table | string | Yes| Name of the target table.| +| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| +| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | -------------------------------------------------------- | +| Promise<[ResultSet](js-apis-data-resultset.md#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| + +**Example** + +```js +let predicates = new rdb.RdbPredicates('EPLOYEE') +predicates.greaterThan("id", 0) +let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates) +promise.then((resultSet) => { + console.info("ResultSet column names: " + resultSet.columnNames) + console.info("ResultSet column count: " + resultSet.columnCount) +}).catch((err) => { + console.info("Failed to remoteQuery , err: " + err) +}) +``` + ### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void @@ -1422,7 +1590,7 @@ Queries data in the RDB store using the specified SQL statement. This API uses a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement.| | 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** @@ -1450,12 +1618,12 @@ Queries data in the RDB store using the specified SQL statement. This API uses a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| **Return value** | Type| Description| | -------- | -------- | -| Promise<[ResultSet](../apis/js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| +| 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 @@ -1473,7 +1641,7 @@ promise.then((resultSet) => { executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void -Runs the SQL statement that contains the specified parameters but does not return a value. This API uses an asynchronous callback to return the result. +Executes an SQL statement that contains specified arguments but returns no value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1481,7 +1649,7 @@ Runs the SQL statement that contains the specified parameters but does not retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | Yes| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | Yes| Arguments in the SQL statement.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| **Example** @@ -1492,7 +1660,7 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { console.info("Failed to execute SQL, err: " + err) return } - console.info('Create table done.') + console.info('Created table successfully.') }) ``` @@ -1501,7 +1669,7 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> -Runs the SQL statement that contains the specified parameters but does not return a value. This API uses a promise to return the execution result. +Executes an SQL statement that contains specified arguments but returns no value. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1509,7 +1677,7 @@ Runs the SQL statement that contains the specified parameters but does not retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | sql | string | Yes| SQL statement to run.| -| bindArgs | Array<[ValueType](#valuetype)> | No| Values of the parameters in the SQL statement.| +| bindArgs | Array<[ValueType](#valuetype)> | No| Arguments in the SQL statement.| **Return value** | Type| Description| @@ -1521,7 +1689,7 @@ Runs the SQL statement that contains the specified parameters but does not retur const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" let promise = rdbStore.executeSql(SQL_CREATE_TABLE) promise.then(() => { - console.info('Create table done.') + console.info('Created table successfully.') }).catch((err) => { console.info("Failed to execute SQL, err: " + err) }) @@ -1544,13 +1712,7 @@ const valueBucket = { "salary": 100.5, "blobType": new Uint8Array([1, 2, 3]), } -rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Failed to insert data, err: " + err) - return - } - console.log("Inserted data successfully: " + ret) -}) +await rdbStore.insert("test", valueBucket) rdbStore.commit() ``` @@ -1573,13 +1735,7 @@ const valueBucket = { "blobType": new Uint8Array([1, 2, 3]), } -rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Failed to insert data, err: " + err) - return - } - console.log("Inserted data successfully: " + ret) -}) +await rdbStore.insert("test", valueBucket) rdbStore.commit() ``` @@ -1603,13 +1759,7 @@ try { "salary": 100.5, "blobType": new Uint8Array([1, 2, 3]), } - rdbStore.insert("test", valueBucket, function (err, ret) { - if (err) { - console.info("Failed to insert data, err: " + err) - return - } - console.log("Inserted data successfully: " + ret) - }) + await rdbStore.insert("test", valueBucket) rdbStore.commit() } catch (e) { rdbStore.rollBack() @@ -1637,7 +1787,7 @@ rdbStore.backup("dbBackup.db", function(err) { console.info('Failed to back up data, err: ' + err) return } - console.info('Backup successful.') + console.info('Backed up data successfully.') }) ``` @@ -1663,7 +1813,7 @@ Backs up an RDB store. This API uses a promise to return the result. ```js let promiseBackup = rdbStore.backup("dbBackup.db") promiseBackup.then(()=>{ - console.info('Backup successful.') + console.info('Backed up data successfully.') }).catch((err)=>{ console.info('Failed to back up data, err: ' + err) }) @@ -1673,7 +1823,7 @@ promiseBackup.then(()=>{ restore(srcName:string, callback: AsyncCallback<void>):void -Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result. +Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1690,7 +1840,7 @@ rdbStore.restore("dbBackup.db", function(err) { console.info('Failed to restore data, err: ' + err) return } - console.info('Restore successful.') + console.info('Restored data successfully.') }) ``` @@ -1698,7 +1848,7 @@ rdbStore.restore("dbBackup.db", function(err) { restore(srcName:string): Promise<void> -Restores an RDB store using a backup file. This API uses a promise to return the result. +Restores an RDB store from a backup file. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1716,7 +1866,7 @@ Restores an RDB store using a backup file. This API uses a promise to return the ```js let promiseRestore = rdbStore.restore("dbBackup.db") promiseRestore.then(()=>{ - console.info('Restore successful.') + console.info('Restored data successfully.') }).catch((err)=>{ console.info('Failed to restore data, err: ' + err) }) @@ -1726,7 +1876,7 @@ promiseRestore.then(()=>{ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void -Sets a list of distributed tables. This API uses an asynchronous callback to return the result. +Sets distributed tables. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1747,14 +1897,14 @@ rdbStore.setDistributedTables(["EMPLOYEE"], function (err) { } console.info('Set distributed tables successfully.') }) - ``` +``` ### setDistributedTables8+ setDistributedTables(tables: Array<string>): Promise<void> -Sets a list of distributed tables. This API uses a promise to return the result. +Sets distributed tables. This API uses a promise to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1776,7 +1926,7 @@ 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) }) ``` @@ -1784,7 +1934,7 @@ promise.then(() => { obtainDistributedTableName(device: string, table: string, callback: AsyncCallback<string>): void -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses an asynchronous callback to return the result. +Obtains the distributed table name for a remote device based on the local table name. This API uses an asynchronous callback to return the result. The distributed table name is required when the RDB store of a remote device is queried. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1813,7 +1963,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, obtainDistributedTableName(device: string, table: string): Promise<string> -Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the database of a remote device is queried. This API uses a promise to return the result. +Obtains the distributed table name for a remote device based on the local table name. This API uses a promise to return the result. The distributed table name is required when the RDB store of a remote device is queried. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -1855,7 +2005,7 @@ Synchronizes data between devices. This API uses an asynchronous callback to ret | -------- | -------- | -------- | -------- | | mode | [SyncMode](#syncmode8) | Yes| Data synchronization mode. The value can be **push** or **pull**.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| **RdbPredicates** object that specifies the data and devices to synchronize.| -| callback | AsyncCallback<Array<[string, number]>> | Yes| Callback invoked to send the synchronization result to the caller.
**string** indicates the device ID.
**number** indicates the synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +| 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 @@ -1894,7 +2044,7 @@ Synchronizes data between devices. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| 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 each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure. | +| 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 @@ -1947,7 +2097,7 @@ try { off(event:'dataChange', type: SubscribeType, observer: Callback<Array<string>>): void -Deletes the specified observer of the RDB store. This API uses a callback to return the result. +Unregisters the observer of the specified type from the RDB store. This API uses a callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC 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 45465710a587c51fea60e7c59f2b804c80888043..cd1535b43bfe4e5d13a6460b066a082e31db8020 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -3,7 +3,7 @@ Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type. -> **NOTE**
+> **NOTE** > > - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > @@ -20,10 +20,10 @@ import data_storage from '@ohos.data.storage'; **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.| -| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| +| Name | Type | Readable | Writable | Description | +| ---------------- | ------ | -------- | -------- | ----------------------------------------------------------- | +| MAX_KEY_LENGTH | string | Yes | No | Maximum length of a key. It must be less than 80 bytes. | +| MAX_VALUE_LENGTH | string | Yes | No | Maximum length of a value. It must be less than 8192 bytes. | ## data_storage.getStorageSync @@ -35,25 +35,33 @@ Reads the specified file and loads its data to the **Storage** instance for data **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Return value** - | Type| Description| - | -------- | -------- | - | [Storage](#storage) | **Storage** instance used for data storage operations.| + +| Type | Description | +| ------------------- | ------------------------------------------------------ | +| [Storage](#storage) | **Storage** instance used for data storage operations. | **Example** - ```js - import data_storage from '@ohos.data.storage' - - let path = '/data/storage/el2/database' - let storage = data_storage.getStorageSync(path + '/mystore') - storage.putSync('startup', 'auto') - storage.flushSync() - - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +let storage = data_storage.getStorageSync(path + '/mystore'); +storage.putSync('startup', 'auto'); +storage.flushSync(); +``` ## data_storage.getStorage @@ -65,25 +73,33 @@ Reads the specified file and loads its data to the **Storage** instance for data **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| - | callback | AsyncCallback<[Storage](#storage)> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | --------------------------------------------- | +| path | string | Yes | Path of the target file. | +| callback | AsyncCallback<[Storage](#storage)> | Yes | Callback used to return the execution result. | **Example** - ```js - import data_storage from '@ohos.data.storage' - - let path = '/data/storage/el2/database' - data_storage.getStorage(path + '/mystore', function (err, storage) { - if (err) { - console.info("Failed to get the storage. Path: " + path + '/mystore') - return; - } - storage.putSync('startup', 'auto') - storage.flushSync() - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +data_storage.getStorage(path + '/mystore', function (err, storage) { + if (err) { + console.info("Failed to get the storage. path: " + path + '/mystore'); + return; + } + storage.putSync('startup', 'auto'); + storage.flushSync(); +}) +``` ## data_storage.getStorage @@ -95,29 +111,37 @@ Reads the specified file and loads its data to the **Storage** instance for data **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[Storage](#storage)> | Promise used to return the result.| + +| Type | Description | +| ---------------------------------- | ---------------------------------- | +| Promise<[Storage](#storage)> | Promise used to return the result. | **Example** - ```js - import data_storage from '@ohos.data.storage' - - let path = '/data/storage/el2/database' - - let getPromise = data_storage.getStorage(path + '/mystore') - getPromise.then((storage) => { - storage.putSync('startup', 'auto') - storage.flushSync() - }).catch((err) => { - console.info("Failed to get the storage. Path: " + path + '/mystore') - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +let getPromise = data_storage.getStorage(path + '/mystore'); +getPromise.then((storage) => { + storage.putSync('startup', 'auto'); + storage.flushSync(); +}).catch((err) => { + console.info("Failed to get the storage. path: " + path + '/mystore'); +}) +``` ## data_storage.deleteStorageSync @@ -129,15 +153,25 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Example** - ```js - let path = '/data/storage/el2/database' - data_storage.deleteStorageSync(path + '/mystore') - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +data_storage.deleteStorageSync(path + '/mystore'); +``` ## data_storage.deleteStorage @@ -149,22 +183,32 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------- | +| path | string | Yes | Path of the target file. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - let path = '/data/storage/el2/database' - data_storage.deleteStorage(path + '/mystore', function (err) { - if (err) { - console.info("Deleted failed with err: " + err) - return - } - console.info("Deleted successfully.") - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +data_storage.deleteStorage(path + '/mystore', function (err) { + if (err) { + console.info("Failed to delete the storage with err: " + err); + return; + } + console.info("Succeeded in deleting the storage."); +}) +``` ## data_storage.deleteStorage @@ -176,25 +220,35 @@ Deletes the singleton **Storage** instance of a file from the memory, and delete **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let path = '/data/storage/el2/database' - let promisedelSt = data_storage.deleteStorage(path + '/mystore') - promisedelSt.then(() => { - console.info("Deleted successfully.") - }).catch((err) => { - console.info("Deleted failed with err: " + err) - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +let promisedelSt = data_storage.deleteStorage(path + '/mystore'); +promisedelSt.then(() => { + console.info("Succeeded in deleting the storage."); +}).catch((err) => { + console.info("Failed to delete the storage with err: " + err); +}) +``` ## data_storage.removeStorageFromCacheSync @@ -206,15 +260,25 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Example** - ```js - let path = '/data/storage/el2/database' - data_storage.removeStorageFromCacheSync(path + '/mystore') - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +data_storage.removeStorageFromCacheSync(path + '/mystore'); +``` ## data_storage.removeStorageFromCache @@ -226,22 +290,32 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------- | +| path | string | Yes | Path of the target file. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - let path = '/data/storage/el2/database' - data_storage.removeStorageFromCache(path + '/mystore', function (err) { - if (err) { - console.info("Removed storage from cache failed with err: " + err) - return - } - console.info("Removed storage from cache successfully.") - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +data_storage.removeStorageFromCache(path + '/mystore', function (err) { + if (err) { + console.info("Failed to remove storage from cache with err: " + err); + return; + } + console.info("Succeeded in removing storage from cache."); +}) +``` ## data_storage.removeStorageFromCache @@ -253,25 +327,36 @@ Removes the singleton **Storage** instance of a file from the cache. The removed **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | path | string | Yes| Path of the target file.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------ | +| path | string | Yes | Path of the target file. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let path = '/data/storage/el2/database' - let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') - promiserevSt.then(() => { - console.info("Removed storage from cache successfully.") - }).catch((err) => { - console.info("Removed storage from cache failed with err: " + err) - }) - ``` + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +var path; +var context = featureAbility.getContext(); +context.getFilesDir().then((filePath) => { + path = filePath; + console.info("======================>getFilesDirPromsie====================>"); +}); + +let promiserevSt = data_storage.removeStorageFromCache(path + '/mystore') +promiserevSt.then(() => { + console.info("Succeeded in removing storage from cache."); +}).catch((err) => { + console.info("Failed to remove storage from cache with err: " + err); +}) +``` ## Storage @@ -288,21 +373,24 @@ Obtains the value corresponding to a key. If the value is null or not in the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value.| + +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned if the value of the specified key does not exist. It can be a number, string, or Boolean value. | **Return value** - | Type| Description| - | -------- | -------- | - | ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned.| + +| Type | Description | +| --------- | ------------------------------------------------------------ | +| ValueType | Value corresponding to the specified key. If the value is null or not in the default value format, the default value is returned. | **Example** - ```js - let value = storage.getSync('startup', 'default') - console.info("The value of startup is " + value) - ``` + +```js +let value = storage.getSync('startup', 'default'); +console.info("The value of startup is " + value); +``` ### get @@ -314,22 +402,24 @@ Obtains the value corresponding to a key. If the value is null or not in the def **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<ValueType> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------ | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value. | +| callback | AsyncCallback<ValueType> | Yes | Callback used to return the execution result. | **Example** - ```js - storage.get('startup', 'default', function(err, value) { - if (err) { - console.info("Get the value of startup failed with err: " + err) - return + +```js +storage.get('startup', 'default', function(err, value) { + if (err) { + console.info("Failed to get the value of startup with err: " + err); + return; } - console.info("The value of startup is " + value) - }) - ``` + console.info("The value of startup is " + value); +}) +``` ### get @@ -342,25 +432,26 @@ Obtains the value corresponding to a key. If the value is null or not in the def **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data. It cannot be empty.| -| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, string, or Boolean value.| +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. It can be a number, string, or Boolean value. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<ValueType> | Promise used to return the result.| + +| Type | Description | +| ------------------------ | ---------------------------------- | +| Promise<ValueType> | Promise used to return the result. | **Example** - ```js - let promiseget = storage.get('startup', 'default') - promiseget.then((value) => { - console.info("The value of startup is " + value) - }).catch((err) => { - console.info("Get the value of startup failed with err: " + err) - }) - ``` +```js +let promiseget = storage.get('startup', 'default'); +promiseget.then((value) => { + console.info("The value of startup is " + value) +}).catch((err) => { + console.info("Failed to get the value of startup with err: " + err); +}) +``` ### putSync @@ -372,15 +463,17 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **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| New value to store. It can be a number, string, or Boolean value.| + +| Name | Type | Mandatory | Description | +| ----- | ----------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | **Example** - ```js - storage.putSync('startup', 'auto') - ``` + +```js +storage.putSync('startup', 'auto') +``` ### put @@ -392,22 +485,24 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **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| New value to store. It can be a number, string, or Boolean value.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - storage.put('startup', 'auto', function (err) { - if (err) { - console.info("Put the value of startup failed with err: " + err) - return - } - console.info("Put the value of startup successfully.") - }) - ``` + +```js +storage.put('startup', 'auto', function (err) { + if (err) { + console.info("Failed to put the value of startup with err: " + err); + return; + } + console.info("Succeeded in putting the value of startup."); +}) +``` ### put @@ -419,25 +514,27 @@ Obtains the **Storage** instance corresponding to the specified file, writes dat **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| New value to store. It can be a number, string, or Boolean value.| + +| Name | Type | Mandatory | Description | +| ----- | ----------------------- | --------- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | New value to store. It can be a number, string, or Boolean value. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promiseput = storage.put('startup', 'auto') - promiseput.then(() => { - console.info("Put the value of startup successfully.") - }).catch((err) => { - console.info("Put the value of startup failed with err: " + err) - }) - ``` +```js +let promiseput = storage.put('startup', 'auto'); +promiseput.then(() => { + console.info("Succeeded in putting the value of startup."); +}).catch((err) => { + console.info("Failed to put the value of startup with err: " + err); +}) +``` ### hasSync @@ -449,22 +546,25 @@ Checks whether the storage object contains data with a given key. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.| + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise. | **Example** - ```js - let isExist = storage.hasSync('startup') - if (isExist) { - console.info("The key of startup is contained.") - } - ``` + +```js +let isExist = storage.hasSync('startup'); +if (isExist) { + console.info("The key of startup is contained."); +} +``` ### has @@ -476,28 +576,31 @@ Checks whether the storage object contains data with a given key. This API uses **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the execution result.| + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | --------- | --------------------------------------------- | +| key | string | Yes | Key of the data. It cannot be empty. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the execution result. | **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise.| + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the storage object contains data with the specified key; returns **false** otherwise. | **Example** - ```js - storage.has('startup', function (err, isExist) { - if (err) { - console.info("Check the key of startup failed with err: " + err) - return - } - if (isExist) { - console.info("The key of startup is contained.") - } - }) - ``` + +```js +storage.has('startup', function (err, isExist) { + if (err) { + console.info("Failed to check the key of startup with err: " + err); + return; + } + if (isExist) { + console.info("The key of startup is contained."); + } +}) +``` ### has @@ -509,26 +612,29 @@ Checks whether the storage object contains data with a given key. This API uses **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result.| + +| Type | Description | +| ---------------------- | ---------------------------------- | +| Promise<boolean> | Promise used to return the result. | **Example** - ```js - let promisehas = storage.has('startup') - promisehas.then((isExist) => { - if (isExist) { - console.info("The key of startup is contained.") - } - }).catch((err) => { - console.info("Check the key of startup failed with err: " + err) - }) - ``` + +```js +let promisehas = storage.has('startup') +promisehas.then((isExist) => { + if (isExist) { + console.info("The key of startup is contained."); + } +}).catch((err) => { + console.info("Failed to check the key of startup with err: " + err); +}) +``` ### deleteSync @@ -540,14 +646,16 @@ Deletes data with the specified key from this storage object. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | **Example** - ```js - storage.deleteSync('startup') - ``` + +```js +storage.deleteSync('startup') +``` ### delete @@ -559,21 +667,23 @@ Deletes data with the specified key from this storage object. This API uses an a **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - storage.delete('startup', function (err) { - if (err) { - console.info("Delete startup key failed with err: " + err) - return - } - console.info("Deleted startup key successfully.") - }) - ``` + +```js +storage.delete('startup', function (err) { + if (err) { + console.info("Failed to delete startup key failed err: " + err); + return; + } + console.info("Succeeded in deleting startup key."); +}) +``` ### delete @@ -585,24 +695,27 @@ Deletes data with the specified key from this storage object. This API uses a pr **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data.| + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ---------------- | +| key | string | Yes | Key of the data. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promisedel = storage.delete('startup') - promisedel.then(() => { - console.info("Deleted startup key successfully.") - }).catch((err) => { - console.info("Delete startup key failed with err: " + err) - }) - ``` + +```js +let promisedel = storage.delete('startup') +promisedel.then(() => { + console.info("Succeeded in deleting startup key."); +}).catch((err) => { + console.info("Failed to delete startup key failed err: " + err); +}) +``` ### flushSync @@ -614,9 +727,10 @@ Saves the modification of this object to the **Storage** instance and synchroniz **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Example** - ```js - storage.flushSync() - ``` + +```js +storage.flushSync() +``` ### flush @@ -628,20 +742,22 @@ Saves the modification of this object to the **Storage** instance and synchroniz **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - storage.flush(function (err) { - if (err) { - console.info("Flush to file failed with err: " + err) - return - } - console.info("Flushed to file successfully.") - }) - ``` + +```js +storage.flush(function (err) { + if (err) { + console.info("Failed to flush to file with err: " + err); + return; + } + console.info("Succeeded in flushing to file."); +}) +``` ### flush @@ -653,19 +769,21 @@ Saves the modification of this object to the **Storage** instance and synchroniz **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promiseflush = storage.flush() - promiseflush.then(() => { - console.info("Flushed to file successfully.") - }).catch((err) => { - console.info("Flush to file failed with err: " + err) - }) - ``` + +```js +let promiseflush = storage.flush(); +promiseflush.then(() => { + console.info("Succeeded in flushing to file."); +}).catch((err) => { + console.info("Failed to flush to file with err: " + err); +}) +``` ### clearSync @@ -677,9 +795,10 @@ Clears this **Storage** object. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Example** - ```js - storage.clearSync() - ``` + +```js +storage.clearSync() +``` ### clear @@ -691,20 +810,22 @@ Clears this **Storage** object. This API uses an asynchronous callback to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** - ```js - storage.clear(function (err) { - if (err) { - console.info("Clear to file failed with err: " + err) - return - } - console.info("Cleared to file successfully.") - }) - ``` + +```js +storage.clear(function (err) { + if (err) { + console.info("Failed to clear the storage with err: " + err); + return; + } + console.info("Succeeded in clearing the storage."); +}) +``` ### clear @@ -716,19 +837,21 @@ Clears this **Storage** object. 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.| + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** - ```js - let promiseclear = storage.clear() - promiseclear.then(() => { - console.info("Cleared to file successfully.") - }).catch((err) => { - console.info("Clear to file failed with err: " + err) - }) - ``` + +```js +let promiseclear = storage.clear(); +promiseclear.then(() => { + console.info("Succeeded in clearing the storage."); +}).catch((err) => { + console.info("Failed to clear the storage with err: " + err); +}) +``` ### on('change') @@ -740,20 +863,22 @@ Subscribes to data changes. The **StorageObserver** needs to be implemented. Whe **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Description| - | -------- | -------- | -------- | - | type | string | Event type. The value **change** indicates data change events.| - | callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes.| + +| Name | Type | Description | +| -------- | --------------------------------------------------- | ------------------------------------------------------------ | +| type | string | Event type. The value **change** indicates data change events. | +| callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes. | **Example** - ```js - var observer = function (key) { - console.info("The key of " + key + " changed.") - } - storage.on('change', observer) - storage.putSync('startup', 'auto') - storage.flushSync() // observer will be called. - ``` + +```js +var observer = function (key) { + console.info("The key of " + key + " changed."); +} +storage.on('change', observer); +storage.putSync('startup', 'auto'); +storage.flushSync(); // observer will be called. +``` ### off('change') @@ -765,27 +890,29 @@ Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Description| - | -------- | -------- | -------- | - | type | string | Event type. The value **change** indicates data change events.| - | callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes.| + +| Name | Type | Description | +| -------- | --------------------------------------------------- | ------------------------------------------------------------ | +| type | string | Event type. The value **change** indicates data change events. | +| callback | Callback<[StorageObserver](#storageobserver)> | Callback used to return data changes. | **Example** - ```js - var observer = function (key) { - console.info("The key of " + key + " changed.") - } - storage.off('change', observer) - ``` + +```js +var observer = function (key) { + console.info("The key of " + key + " changed."); +} +storage.off('change', observer); +``` ## StorageObserver **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | No| Data changed.| +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------- | +| key | string | No | Data changed. | ## ValueType @@ -793,8 +920,8 @@ Enumerates the value types. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Type | Description | -| ------- | -------------------- | -| number | The value is a number. | -| string | The value is a string. | -| boolean | The value is of Boolean type.| +| Type | Description | +| ------- | ----------------------------- | +| number | The value is a number. | +| string | The value is a string. | +| boolean | The value is of Boolean type. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md index 52af89ae7faa9fd20a28a62f959f4a3f39340ced..1d10f56aeb69e13d2f329bfc18f56127667ef930 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -119,7 +119,7 @@ helper.on( off(type: 'dataChange', uri: string, callback?: AsyncCallback\): void -Unregisters the observer used to observe data specified by a given URI. This API uses an asynchronous callback to return the result. +Deregisters the observer used to observe data specified by a given URI. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -647,7 +647,7 @@ Deletes one or more data records from the database. This API uses an asynchronou ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -662,7 +662,7 @@ DAHelper.delete( ## DataAbilityHelper.delete -delete(uri: string, predicates: dataAbility.DataAbilityPredicates): Promise\ +delete(uri: string, predicates?: dataAbility.DataAbilityPredicates): Promise\; Deletes one or more data records from the database. This API uses a promise to return the result. @@ -685,7 +685,7 @@ Deletes one or more data records from the database. This API uses a promise to r ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -719,7 +719,7 @@ Updates data records in the database. This API uses an asynchronous callback to ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -741,7 +741,7 @@ DAHelper.update( ## DataAbilityHelper.update -update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates): Promise\ +update(uri: string, valuesBucket: rdb.ValuesBucket, predicates?: dataAbility.DataAbilityPredicates): Promise\; Updates data records in the database. This API uses a promise to return the result. @@ -765,7 +765,7 @@ Updates data records in the database. This API uses a promise to return the resu ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -806,7 +806,7 @@ Queries data in the database. This API uses an asynchronous callback to return t ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -825,7 +825,7 @@ DAHelper.query( ## DataAbilityHelper.query -query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates): Promise\ +query(uri: string, columns?: Array\, predicates?: dataAbility.DataAbilityPredicates): Promise\; Queries data in the database. This API uses a promise to return the result. @@ -849,7 +849,7 @@ Queries data in the database. This API uses a promise to return the result. ```js import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_ability from '@ohos.data.dataAbility' var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -876,7 +876,7 @@ Calls the extended API of the Data ability. This API uses a promise to return th | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx" | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | | method | string | Yes | Name of the API to call. | | arg | string | Yes |Parameter to pass. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | @@ -912,7 +912,7 @@ Calls the extended API of the Data ability. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx" | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | | method | string | Yes | Name of the API to call. | | arg | string | Yes |Parameter to pass. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | @@ -932,8 +932,107 @@ dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", " console.info('Operation succeeded: ' + data); }); ``` + +## DataAbilityHelper.executeBatch + +executeBatch(uri: string, operations: Array\, callback: AsyncCallback\>): void; + +Operates data in the database. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------------------------------- | ---- | ------------------------------------------------ | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| +| operations | Array\<[DataAbilityOperation](#dataabilityoperation)> | Yes | A list of data operations on the database. | +| callback | AsyncCallback\> | Yes |Callback used to return the result of each operation in the **DataAbilityResult** array. | + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +// Select the operations to be performed on the database according to the DataAbilityOperation array. +let op=new Array(); +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); +dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + err); + return; + } + console.info('Operation succeeded: ' + data); +}); +``` + +## DataAbilityHelper.executeBatch + +executeBatch(uri: string, operations: Array\): Promise\>; + +Operates data in the database. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | -------------------------------| ---- | ------------------------------------------------ | +| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| +| operations | Array\<[DataAbilityOperation](#dataabilityoperation)> | Yes | A list of data operations on the database. | + +**Return value** + +| Type| Description| +|------ | ------- | +|Promise\> | Promise used to return the result of each operation in the **DataAbilityResult** array.| + +**Example** + +```js +import featureAbility from '@ohos.ability.featureAbility'; + +// Select the operations to be performed on the database according to the DataAbilityOperation array. +let op=new Array(); +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); +dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility",op ).then((data) => { + console.info('Operation succeeded: ' + data); +}).catch((error) => { + console.error('Operation failed. Cause: ' + error); +}); + +``` + ## PacMap +[key: string]: number | string | boolean | Array\ | null; + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + | Name| Type| Mandatory| Description| | ------ | ------ | ------ | ------ | | [key: string] | number \| string \| boolean \| Array\ \| null | Yes| Data stored in key-value pairs.| + +## DataAbilityOperation + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Type | Readable | Writable | Mandatory| Description | +| -------- | -------- | -------- | -------- | --------| -------- | +| uri | string | Yes | No | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| type | featureAbility.DataAbilityOperationType | Yes | No | Yes | Operation type. | +| valuesBucket? | rdb.ValuesBucket | Yes | No | No | Data value to set. | +| valueBackReferences? | rdb.ValuesBucket | Yes | No | No | **ValuesBucket** object that contains a set of key-value pairs. | +| predicates? | dataAbility.DataAbilityPredicates | Yes | No | No | Predicates to set. If no predicate is set, all data records are displayed. | +| predicatesBackReferences? | Map\ | Yes | No | No | Back references of the predicates. | +| interrupted? | boolean | Yes | No | No | Whether batch operations can be interrupted. | +| expectedCount? | number | Yes | No | No | Expected number of rows to be updated or deleted. | + +## DataAbilityResult + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Type | Readable | Writable | Mandatory | Description | +| -------- | -------- | -------- | -------- | -------- | -------- | +| uri? | string | Yes | No | No | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| count? | number | Yes | No | No | Number of rows affected by the operation. | diff --git a/en/application-dev/reference/apis/js-apis-dispatchInfo.md b/en/application-dev/reference/apis/js-apis-dispatchInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..5f476f34bd9ed8c08fc0e033243c1f4fb55ca23c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-dispatchInfo.md @@ -0,0 +1,16 @@ +# DispatchInfo + +The **DispatchInfo** module provides dispatch information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## DispatchInfo + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | ------------------------ | +| verison | 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-display.md b/en/application-dev/reference/apis/js-apis-display.md index 25cf9ed242f66a0983303065dcea527989444223..372e6feb7c832d873bd98ed238d5cf474df10a5d 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -174,6 +174,42 @@ Obtains all display objects. This API uses a promise to return the result. }); ``` +## display.hasPrivateWindow9+ + +hasPrivateWindow(displayId: number): boolean + +Checks whether there is a visible privacy window on a display. The privacy window can be set by calling **[setPrivacyMode](js-apis-window.md#setprivacymode7)**. The content in the privacy window cannot be captured or recorded. + +This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- |----------| +| id | number | Yes | ID of the display.| + +**Return value** + +| Type | Description | +| -------------------------------- |-----------------------------------------------------------------------| +|boolean | Whether there is a visible privacy window on the display.
The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.
| + +**Example** + + ```js + var ret = display.hasPrivateWindow(displayClass.id); + if (ret == undefined) { + console.log("HasPrivateWindow undefined."); + } + if (ret) { + console.log("HasPrivateWindow."); + } else if (!ret) { + console.log("Don't HasPrivateWindow."); + } + ``` + ## display.on('add'|'remove'|'change') on(type: 'add'|'remove'|'change', callback: Callback<number>): void 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 7d094be2e3b6a425e1c8b0eea194cb1085fd3505..46b962bb7e0dfbb16ea2ef4ba6a0bf2ac37ec5e0 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -19,8 +19,6 @@ getDistributedAccountAbility(): DistributedAccountAbility Obtains a **DistributedAccountAbility** instance. -**System capability**: SystemCapability.Account.OsAccount - - Return value | Type| Description| | -------- | -------- | @@ -43,7 +41,7 @@ Obtains distributed account information. This API uses an asynchronous callback **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC - Parameters | Name| Type| Mandatory| Description| @@ -68,7 +66,7 @@ Obtains distributed account information. This API uses a promise to return the r **System capability**: SystemCapability.Account.OsAccount -**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC - 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 deleted file mode 100644 index 5682921badad9367817fd3e421b1afb823970425..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-distributed-data .md +++ /dev/null @@ -1,5671 +0,0 @@ -# Distributed Data Management - -The distributed data management module implements collaboration between databases of different devices for applications. The APIs provided by distributed data management can be used to save data to distributed databases and perform operations such as adding, deleting, modifying, querying, and synchronizing data in distributed databases. - -This module provides the following functions: - -- [KVManager](#kvmanager): provides a **KVManager** instance to manage key-value (KV) stores. -- [KvStoreResultSet8+](#kvstoreresultset8): provides methods to obtain the KV store result set and query or move the data read position. -- [Query8+](#query8): provides methods to query data from the database through a **Query** instance by using predicates. -- [KVStore](#kvstore): provides methods to add data, delete data, and observe data changes and data synchronization through a **KVStore** instance. -- [SingleKVStore](#singlekvstore): provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore), and data is not distinguished by device. -- [DeviceKVStore8+ ](#devicekvstore8): provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore), and data is distinguished by device. - ->**NOTE**
-> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - - -## Modules to Import - -```js -import distributedData from '@ohos.data.distributedData'; -``` - - -## distributedData.createKVManager - -createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void - -Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| config | [KVManagerConfig](#kvmanagerconfig) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| -| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| - -**Example** - -Stage model: -```ts -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -FA model: -```js -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context.getApplicationContext(), - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -## distributedData.createKVManager - -createKVManager(config: KVManagerConfig): Promise<KVManager> - -Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| config |[KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| - -**Example** - -Stage model: -```ts -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -FA model: -```js -import AbilityStage from '@ohos.application.Ability' -let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context.getApplicationContext(), - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } - } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager"); - kvManager = manager; - }); - } -} -``` - -## KVManagerConfig - -Provides configuration of the **KVManager** object, including the bundle name and user information of the caller. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| context9+ | 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).| -| userInfo | [UserInfo](#userinfo) | Yes | User information.| -| bundleName | string | Yes | Bundle name.| - -## UserInfo - -Defines user information. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| userId | string | Yes | User ID.| -| userType | [UserType](#usertype) | Yes | User type.| - - -## UserType - -Enumerates the user types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name| Value| Description| -| ----- | ------ | ------ | -| SAME_USER_ID | 0 | User who logs in to different devices using the same account.| - - -## KVManager - -Creates a **KVManager** object to obtain KV store information. Before calling any method in **KVManager**, you must use [createKVManager](#distributeddatacreatekvmanager) to create a **KVManager** object. - -### getKVStore - -getKVStore<T extends KVStore>(storeId: string, options: Options, callback: AsyncCallback<T>): void - -Creates and obtains a KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| options | [Options](#options) | Yes | Configuration of the KV store.| -| callback | AsyncCallback<T> , <T extends [KVStore](#kvstore)>| Yes | Callback invoked to return the KV store created.| - -**Example** - -```js -let kvStore; -let kvManager; -try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - 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); -} -``` - - -### getKVStore - -getKVStore<T extends KVStore>(storeId: string, options: Options): Promise<T> - -Creates and obtains a KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ------- | ---------------------- | ---- | -------------------- | -| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| options | [Options](#options) | Yes | Configuration of the KV store.| - - -**Return value** - -| Type | Description | -| -------------------------------------- | ------------------------ | -| Promise<T>, <T extends [KVStore](#kvstore)> | Promise used to return the KV store created.| - -**Example** - -```js -let kvStore; -let kvManager; -try { - const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - securityLevel : distributedData.SecurityLevel.S2, - }; - kvManager.getKVStore('storeId', options).then((store) => { - console.log("getKVStore success"); - kvStore = store; - }).catch((err) => { - console.log("getKVStore err: " + JSON.stringify(err)); - }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### closeKVStore8+ ### - -closeKVStore(appId: string, storeId: string, kvStore: KVStore, callback: AsyncCallback<void>): void - -Closes a KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - - -| Name | Type | Mandatory| Description | -| ------- | ----------------- | ---- | --------------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```js -let kvStore; -let kvManager; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, - } - try { - kvManager.getKVStore('storeId', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - kvManager.closeKVStore('appId', 'storeId', kvStore, function (err, data) { - console.log('closeKVStore success'); - }); - }); -} catch (e) { - console.log('closeKVStore e ' + e); -} -``` - - -### closeKVStore8+ ### - -closeKVStore(appId: string, storeId: string, kvStore: KVStore): Promise<void> - -Closes a KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| kvStore | [KVStore](#kvstore) | Yes | KV store to close. | - -**Return value** - -| Type | Description | -| ------------- | -------------- | -| Promise\ | Promise that returns no value.| - -**Example** - -```js -let kvManager; -let kvStore; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} - try { - kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - kvManager.closeKVStore('appId', 'storeId', kvStore).then(() => { - console.log('closeKVStore success'); - }).catch((err) => { - console.log('closeKVStore err ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('CloseKVStore getKVStore err ' + JSON.stringify(err)); - }); - } catch (e) { - console.log('closeKVStore e ' + e); -} -``` - - -### deleteKVStore8+ ### - -deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void - -Deletes a KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```js -let kvManager; -let kvStore; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} -try { - kvManager.getKVStore('store', options, async function (err, store) { - console.log('getKVStore success'); - kvStore = store; - kvManager.deleteKVStore('appId', 'storeId', function (err, data) { - console.log('deleteKVStore success'); - }); - }); -} catch (e) { - console.log('DeleteKVStore e ' + e); -} -``` - -### deleteKVStore8+ ### - -deleteKVStore(appId: string, storeId: string): Promise<void> - -Deletes a KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| - - -**Return value** - -| Type | Description | -| ------------- | -------------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -let kvManager; -let kvStore; -const options = { - createIfMissing : true, - encrypt : false, - backup : false, - autoSync : true, - kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, - schema : '', - securityLevel : distributedData.SecurityLevel.S2, -} -try { - kvManager.getKVStore('storeId', options).then(async (store) => { - console.log('getKVStore success'); - kvStore = store; - kvManager.deleteKVStore('appId', 'storeId').then(() => { - console.log('deleteKVStore success'); - }).catch((err) => { - console.log('deleteKVStore err ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('getKVStore err ' + JSON.stringify(err)); - }); -} catch (e) { - console.log('deleteKVStore e ' + e); -} -``` - - -### getAllKVStoreId8+ ### - -getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void - -Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | -| callback | AsyncCallback<string[]> | Yes |Callback used to return the KV store IDs obtained. | - -**Example** - -```js -let kvManager; -try { - kvManager.getAllKVStoreId('appId', function (err, data) { - console.log('GetAllKVStoreId success'); - console.log('GetAllKVStoreId size = ' + data.length); - }); -} catch (e) { - console.log('GetAllKVStoreId e ' + e); -} -``` - - -### getAllKVStoreId8+ ### - -getAllKVStoreId(appId: string): Promise<string[]> - -Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) and have not been deleted by [deleteKVStore()](#deletekvstore8). This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| appId | string | Yes | Bundle name of the app that invokes the KV store. | - - -**Return value** - -| Type | Description | -| ------------- | -------------- | -| Promise<string[]>| Promise used to return the KV store IDs obtained.| - -**Example** - -```js -let kvManager; -try { - console.log('GetAllKVStoreId'); - kvManager.getAllKVStoreId('appId').then((data) => { - console.log('getAllKVStoreId success'); - console.log('size = ' + data.length); - }).catch((err) => { - console.log('getAllKVStoreId err ' + JSON.stringify(err)); - }); -} catch(e) { - console.log('getAllKVStoreId e ' + e); -} -``` - - -### on('distributedDataServiceDie')8+ ### - -on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void - -Subscribes to service status changes. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| 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.| - -**Example** - -```js -let kvManager; -try { - - console.log('KVManagerOn'); - const deathCallback = function () { - console.log('death callback call'); - } - kvManager.on('distributedDataServiceDie', deathCallback); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - - -### off('distributedDataServiceDie')8+ ### - -off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void - -Unsubscribes from the service status changes. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| 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.| - - -**Example** - -```js -let kvManager; -try { - console.log('KVManagerOff'); - const deathCallback = function () { - console.log('death callback call'); - } - kvManager.off('distributedDataServiceDie', deathCallback); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} - -``` - -## Options - -Provides KV store configuration. - - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| autoSync | boolean | No|Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | -| kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| -| securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| schema8+ | [Schema](#schema8) | No| Schema used to define the values stored in a KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| - - -## KVStoreType - -Enumerates the KV store types. - - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | -| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| -| MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| - - -## SecurityLevel - -Enumerates the KV store security levels. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| NO_LEVEL | 0 | No security level is set for the KV store. | -| S0 | 1 | The KV store security level is public.| -| S1 | 2 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| -| S2 | 3 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| -| S3 | 5 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| -| S4 | 6 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| - - -## Constants - -Defines the KV store constants. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value| Description | -| --- | ---- | ----------------------- | -| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the KV store, in bytes. | -| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the KV store, in bytes. | -| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes.| -| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | -| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes.| -| MAX_BATCH_SIZE | 128 | Maximum number of batch operations.| - -## Schema8+ ## - -Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -| Name | Type| Description | -| --- | ---- | ----------------------- | -| root8+ | [FieldNode](#fieldnode8) | JSON root object.| -| indexes8+ | Array\ | String array in JSON format. | -| mode8+ | number | Schema mode. | -| skip8+ | number | Size of a skip of the schema. | - -### constructor8+ ### - -constructor() - -A constructor used to create a **Schema** instance. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -## FieldNode8+ ## - -Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -| Name | Type| Description | -| --- | ---- | ----------------------- | -| nullable8+ | boolean | Whether the database field can be null. | -| default8+ | string | Default value of a **FieldNode**.| -| type8+ | number | Value of the data type corresponding to the specified node.| - -### constructor8+ ### - -constructor(name: string) - -A constructor used to create a **FieldNode** instance with a string field. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name| Type| Mandatory| Description | -| ------ | -------- | ---- | --------------- | -| name | string | Yes | Value of **FieldNode**.| - -### appendChild8+ ### - -appendChild(child: FieldNode): boolean - -Appends a child node to this **FieldNode**. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| child | [FieldNode](#fieldnode8) | Yes | Child node to append. | - -**Return value** - -| Type | Description | -| ------------- | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise.| - -**Example** - -```js -import ddm from '@ohos.data.distributedData'; -try { - let node = new ddm.FieldNode("root"); - let child1 = new ddm.FieldNode("child1"); - let child2 = new ddm.FieldNode("child2"); - let child3 = new ddm.FieldNode("child3"); - node.appendChild(child1); - node.appendChild(child2); - node.appendChild(child3); - console.log("appendNode " + JSON.stringify(node)); - child1 = null; - child2 = null; - child3 = null; - node = null; -} catch (e) { - console.log("AppendChild " + e); -} -``` - - -## KvStoreResultSet8+ ## - -Provides methods to obtain the KV store result sets, and query and move the data read position. - -Before calling any method in **KvStoreResultSet**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. - - -### getCount8+ ### - -getCount(): number - -Obtains the total number of rows in the result set. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| number |Total number of rows obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const count = resultSet.getCount(); - console.log("getCount succeed:" + count); -} catch (e) { - console.log("getCount failed: " + e); -} -``` - -### getPosition8+ ### - -getPosition(): number - -Obtains the current data read position (position from which data is read) in the result set. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| number |Current data read position obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeeded.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const position = resultSet.getPosition(); - console.log("getPosition succeed:" + position); -} catch (e) { - console.log("getPosition failed: " + e); -} -``` - - -### moveToFirst8+ ### - -moveToFirst(): boolean - -Moves the data read position to the first row. If the result set is empty, **false** will be returned. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved1 = resultSet.moveToFirst(); - console.log("moveToFirst succeed: " + moved1); -} catch (e) { - console.log("moveToFirst failed " + e); -} -``` - - -### moveToLast8+ ### - -moveToLast(): boolean - -Moves the data read position to the last row. If the result set is empty, **false** will be returned. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved2 = resultSet.moveToLast(); - console.log("moveToLast succeed:" + moved2); -} catch (e) { - console.log("moveToLast failed: " + e); -} -``` - - -### moveToNext8+ ### - -moveToNext(): boolean - -Moves the data read position to the next row. If the result set is empty, **false** will be returned. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved3 = resultSet.moveToNext(); - console.log("moveToNext succeed: " + moved3); -} catch (e) { - console.log("moveToNext failed: " + e); -} -``` - - -### moveToPrevious8+ ### - -moveToPrevious(): boolean - -Moves the data read position to the previous row. If the result set is empty, **false** will be returned. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved4 = resultSet.moveToPrevious(); - console.log("moveToPrevious succeed:" + moved4); -} catch (e) { - console.log("moveToPrevious failed: " + e); -} -``` - - -### move8+ ### - -move(offset: number): boolean - -Moves the data read position with the specified offset from the current position. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward. | - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved5 = resultSet.move(); - console.log("move succeed:" + moved5); -} catch (e) { - console.log("move failed: " + e); -} -``` - - -### moveToPosition8+ ### - -moveToPosition(position: number): boolean - -Moves the data read position from 0 to an absolute position. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| position | number | Yes |Absolute position to move to. | - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the operation is successful; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const moved6 = resultSet.moveToPosition(); - console.log("moveToPosition succeed: " + moved6); -} catch (e) { - console.log("moveToPosition failed: " + e); -} -``` - - -### isFirst8+ ### - -isFirst(): boolean - -Checks whether the data read position is the first row. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the first row is being read; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const isfirst = resultSet.isFirst(); - console.log("Check isFirst succeed:" + isfirst); -} catch (e) { - console.log("Check isFirst failed: " + e); -} -``` - - -### isLast8+ ### - -isLast(): boolean - -Checks whether the data read position is the last row. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the last row is being read; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const islast = resultSet.isLast(); - console.log("Check isLast succeed: " + islast); -} catch (e) { - console.log("Check isLast failed: " + e); -} -``` - -### isBeforeFirst8+ ### - -isBeforeFirst(): boolean - -Checks whether the data read position is before the first row. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the data read position is before the first row; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const isbeforefirst = resultSet.isBeforeFirst(); - console.log("Check isBeforeFirst succeed: " + isbeforefirst); -} catch (e) { - console.log("Check isBeforeFirst failed: " + e); -} -``` - - -### isAfterLast8+ ### - -isAfterLast(): boolean - -Checks whether the data read position is after the last row. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | -------------- | -| boolean |Returns **true** if the data read position is after the last row; returns **false** otherwise. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const isafterlast = resultSet.isAfterLast(); - console.log("Check isAfterLast succeed:" + isafterlast); -} catch (e) { - console.log("Check isAfterLast failed: " + e); -} -``` - - -### getEntry8+ ### - -getEntry(): Entry - -Obtains the KV pair from the current position. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Entry](#entry) |KV pair obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + err); - }); - const entry = resultSet.getEntry(); - console.log("getEntry succeed:" + JSON.stringify(entry)); -} catch (e) { - console.log("getEntry failed: " + e); -} -``` - - -## Query8+ ## - -Provides methods to create a **Query** object, which defines different data query criteria. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -### constructor8+ ### - -constructor() - -A constructor used to create a **Schema** instance. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - - -### reset8+ ### - -reset(): Query - -Resets the **Query** object. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object reset.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.equalTo("key", "value"); - console.log("query is " + query.getSqlLike()); - query.reset(); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("simply calls should be ok :" + e); -} -``` - - -### equalTo8+ ### - -equalTo(field: string, value: number|string|boolean): Query - -Creates a **Query** object to match the specified field whose value is equal to the given value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.equalTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notEqualTo8+ ### - -notEqualTo(field: string, value: number|string|boolean): Query - -Creates a **Query** object to match the specified field whose value is not equal to the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### greaterThan8+ ### - -greaterThan(field: string, value: number|string|boolean): Query - -Creates a **Query** object to match the specified field whose value is greater than the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.greaterThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### lessThan8+ ### - -lessThan(field: string, value: number|string): Query - -Creates a **Query** object to match the specified field whose value is less than the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.lessThan("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### greaterThanOrEqualTo8+ ### - -greaterThanOrEqualTo(field: string, value: number|string): Query - -Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.greaterThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### lessThanOrEqualTo8+ ### - -lessThanOrEqualTo(field: string, value: number|string): Query - -Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.lessThanOrEqualTo("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### isNull8+ ### - -isNull(field: string): Query - -Creates a **Query** object to match the specified field whose value is **null**. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.isNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### inNumber8+ ### - -inNumber(field: string, valueList: number[]): Query - -Creates a **Query** object to match the specified field whose value is within the specified list of numbers. - - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| valueList | number[] | Yes | List of numbers.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.inNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### inString8+ ### - -inString(field: string, valueList: string[]): Query - -Creates a **Query** object to match the specified field whose value is within the specified list of strings. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| valueList | string[] | Yes | List of strings.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.inString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notInNumber8+ ### - -notInNumber(field: string, valueList: number[]): Query - -Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| valueList | number[] | Yes | List of numbers.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notInNumber("field", [0, 1]); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### notInString8+ ### - -notInString(field: string, valueList: string[]): Query - -Creates a **Query** object to match the specified field whose value is not within the specified list of strings. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| valueList | string[] | Yes | List of strings.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notInString("field", ['test1', 'test2']); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### like8+ ### - -like(field: string, value: string): Query - -Creates a **Query** object to match the specified field whose value is similar to the specified string. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | string | Yes | String specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.like("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### unlike8+ ### - -unlike(field: string, value: string): Query - -Creates a **Query** object to match the specified field whose value is not similar to the specified string. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | string | Yes | String specified.| - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.unlike("field", "value"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### and8+ ### - -and(): Query - -Creates a **Query** object with the AND condition. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object Created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value1"); - query.and(); - query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### or8+ ### - -or(): Query - -Creates a **Query** object with the OR condition. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object Created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value1"); - query.or(); - query.notEqualTo("field", "value2"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### orderByAsc8+ ### - -orderByAsc(field: string): Query - -Creates a **Query** object to sort the query results in ascending order. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByAsc("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### orderByDesc8+ ### - -orderByDesc(field: string): Query - -Creates a **Query** object to sort the query results in descending order. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.orderByDesc("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### limit8+ ### - -limit(total: number, offset: number): Query - -Creates a **Query** object to specify the number of results and where to start. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| total | number | Yes |Number of results to query. | -| offset | number | Yes |Start position for query. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -let total = 10; -let offset = 1; -try { - let query = new distributedData.Query(); - query.notEqualTo("field", "value"); - query.limit(total, offset); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### isNotNull8+ ### - -isNotNull(field: string): Query - -Creates a **Query** object to match the specified field whose value is not **null**. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| fieId | string | Yes |Field to match. It cannot contain '^'. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.isNotNull("field"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### beginGroup8+ ### - -beginGroup(): Query - -Creates a **Query** object for a query condition group with a left parenthesis. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.beginGroup(); - query.isNotNull("field"); - query.endGroup(); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### endGroup8+ ### - -endGroup(): Query - -Creates a **Query** object for a query condition group with a right parenthesis. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.beginGroup(); - query.isNotNull("field"); - query.endGroup(); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### prefixKey8+ ### - -prefixKey(prefix: string): Query - -Creates a **Query** object with a specified key prefix. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| prefix | string | Yes |Key prefix. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.prefixKey("$.name"); - query.prefixKey("0"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### setSuggestIndex8+ ### - -setSuggestIndex(index: string): Query - -Creates a **Query** object with an index preferentially used for query. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| index | string | Yes |Index preferentially used for query. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.setSuggestIndex("$.name"); - query.setSuggestIndex("0"); - console.log("query is " + query.getSqlLike()); - query = null; -} catch (e) { - console.log("duplicated calls should be ok :" + e); -} -``` - - -### deviceId8+ ### - -deviceId(deviceId:string):Query - -Creates a **Query** object with the device ID as the key prefix. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId | string | Yes |Device ID. | - - -**Return value** - -| Type | Description | -| ------ | ------- | -| [Query](#query8) |**Query** object created.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - query.deviceId("deviceId"); - console.log("query is " + query.getSqlLike()); -} catch (e) { - console.log("should be ok on Method Chaining : " + e); -} -``` - - -### getSqlLike8+ ### - -getSqlLike():string - -Obtains the query statement of the **Query** object. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| string |Returns the query statement obtained.| - -**Example** - -```js -try { - let query = new distributedData.Query(); - let sql1 = query.getSqlLike(); - console.log("GetSqlLike sql=" + sql1); -} catch (e) { - console.log("duplicated calls should be ok : " + e); -} -``` - - -## KVStore - -Provides methods to manage data in a KV store, for example, adding or deleting data and subscribing to data changes or completion of data synchronization. - -Before calling any method in **KVStore**, you must use [getKVStore](#getkvstore) to obtain a **KVStore** object. - -### put - -put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void - -Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -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) { - 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); -} -``` - - -### put - -put(key: string, value: Uint8Array | string | number | boolean): Promise<void> - -Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -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).then((data) => { - console.log("put success: " + JSON.stringify(data)); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### delete - -delete(key: string, callback: AsyncCallback<void>): void - -Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -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) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err,data) { - if (err != undefined) { - console.log("delete err: " + JSON.stringify(err)); - return; - } - console.log("delete success"); - }); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### delete - -delete(key: string): Promise<void> - -Deletes a KV pair from this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key | string | Yes |Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -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).then((data) => { - console.log("put success: " + JSON.stringify(data)); - kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("delete success"); - }).catch((err) => { - console.log("delete err: " + JSON.stringify(err)); - }); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### delete9+ - -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. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| -| callback | AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let predicates = new dataSharePredicates.DataSharePredicates(); - kvStore.delete(predicates, function (err, data) { - if (err == undefined) { - console.log('delete success'); - } else { - console.log('delete fail' + err); - } - }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` - -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> - -Deletes KV pairs that meet the specified predicates. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| - - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise used to return the result.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let predicates = new dataSharePredicates.DataSharePredicates(); - let arr = ["name"]; - predicates.inKeys(arr); - kvStore.put("name", "bob").then((data) => { - console.log('put success' + JSON.stringify(data)); - kvStore.delete(predicates).then((data) => { - console.log('delete success'); - }).catch((err) => { - console.log('delete fail' + JSON.stringify(err)); - }); - }) .catch((err) => { - console.log(' put fail' + 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. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); -``` - - -### on('syncComplete') - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to data synchronization complete events. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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. | - -**Example** - -```js -let kvStore; -kvStore.on('syncComplete', function (data) { - console.log("callback call data: " + data); -}); -``` - -### off('dataChange')8+ - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from data change notifications. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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.| - -**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); -}); -``` - -### 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. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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. | - -**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); -} -``` - - -### putBatch8+ - -putBatch(entries: Entry[], callback: AsyncCallback<void>): void - -Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | -| callback |Asyncallback<void> |Yes |Callback used to return the result.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} -``` - - -### putBatch8+ - -putBatch(entries: Entry[]): Promise<void> - -Inserts KV pairs in batches to this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('PutBatch ' + JSON.stringify(entries)); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} -``` - -### putBatch9+ - -putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void - -Writes data to this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | -| callback |Asyncallback<void> |Yes |Callback used to return the result.| - -**Example** - -```js -let kvStore; -try { - let v8Arr = []; - let arr = new Uint8Array([4,5,6,7]); - let vb1 = {key : "name_1", value : 32} - let vb2 = {key : "name_2", value : arr}; - let vb3 = {key : "name_3", value : "lisi"}; - - v8Arr.push(vb1); - v8Arr.push(vb2); - v8Arr.push(vb3); - kvStore.putBatch(v8Arr, async function (err,data) { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('putBatch e ' + JSON.stringify(e)); -} -``` - -### putBatch9+ - -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. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise used to return the result.| - -**Example** - -```js -let kvStore; -try { - let v8Arr = []; - let arr = new Uint8Array([4,5,6,7]); - let vb1 = {key : "name_1", value : 32} - let vb2 = {key : "name_2", value : arr}; - let vb3 = {key : "name_3", value : "lisi"}; - - v8Arr.push(vb1); - v8Arr.push(vb2); - v8Arr.push(vb3); - kvStore.putBatch(v8Arr).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} - -``` - -### deleteBatch8+ - -deleteBatch(keys: string[], callback: AsyncCallback<void>): void - -Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keys |string[] | Yes |KV pairs to delete in batches. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - let keys = []; - for (var i = 0; i < 5; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - keys.push(key + i); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.deleteBatch(keys, async function (err,data) { - console.log('deleteBatch success'); - }); - }); -}catch(e) { - console.log('DeleteBatch e ' + e); -} -``` - - -### deleteBatch8+ ### - -deleteBatch(keys: string[]): Promise<void> - -Deletes KV pairs in batches from this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keys |string[] | Yes |KV pairs to delete in batches. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - let keys = []; - for (var i = 0; i < 5; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - keys.push(key + i); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.deleteBatch(keys).then((err) => { - console.log('deleteBatch success'); - }).catch((err) => { - console.log('deleteBatch fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('DeleteBatch e ' + e); -} -``` - - -### startTransaction8+ ### - -startTransaction(callback: AsyncCallback<void>): void - -Starts the transaction in this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -function putBatchString(len, prefix) { - let entries = []; - for (var i = 0; i < len; i++) { - var entry = { - key : prefix + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - return entries; -} -try { - var count = 0; - kvStore.on('dataChange', 0, function (data) { - console.log('startTransaction 0' + data) - count++; - }); - kvStore.startTransaction(async function (err,data) { - console.log('startTransaction success'); - let entries = putBatchString(10, 'batch_test_string_key'); - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - }); - }); -}catch(e) { - console.log('startTransaction e ' + e); -} -``` - - -### startTransaction8+ ### - -startTransaction(): Promise<void> - -Starts the transaction in this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - var count = 0; - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { - console.log('startTransaction ' + JSON.stringify(data)); - count++; - }); - kvStore.startTransaction().then(async (err) => { - console.log('startTransaction success'); - }).catch((err) => { - console.log('startTransaction fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('startTransaction e ' + e); -} -``` - - -### commit8+ ### - -commit(callback: AsyncCallback<void>): void - -Commits the transaction in this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.commit(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); -}catch(e) { - console.log('Commit e ' + e); -} -``` - - -### commit8+ ### - -commit(): Promise<void> - -Commits the transaction in this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - kvStore.commit().then(async (err) => { - console.log('commit success'); - }).catch((err) => { - console.log('commit fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('Commit e ' + e); -} -``` - - -### rollback8+ ### - -rollback(callback: AsyncCallback<void>): void - -Rolls back the transaction in this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.rollback(function (err,data) { - if (err == undefined) { - console.log('commit success'); - } else { - console.log('commit fail'); - } - }); -}catch(e) { - console.log('Rollback e ' + e); -} -``` - - -### rollback8+ ### - -rollback(): Promise<void> - -Rolls back the transaction in this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - kvStore.rollback().then(async (err) => { - console.log('rollback success'); - }).catch((err) => { - console.log('rollback fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('Rollback e ' + e); -} -``` - - -### enableSync8+ ### - -enableSync(enabled: boolean, callback: AsyncCallback<void>): void - -Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - kvStore.enableSync(true, function (err,data) { - if (err == undefined) { - console.log('enableSync success'); - } else { - console.log('enableSync fail'); - } - }); -}catch(e) { - console.log('EnableSync e ' + e); -} -``` - - -### enableSync8+ ### - -enableSync(enabled: boolean): Promise<void> - -Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| enabled |boolean | Yes |Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - kvStore.enableSync(true).then((err) => { - console.log('enableSync success'); - }).catch((err) => { - console.log('enableSync fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('EnableSync e ' + e); -} -``` - - -### setSyncRange8+ ### - -setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void - -Sets the data synchronization range. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| localLabels |string[] | Yes |Synchronization labels set for the local device. | -| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err,data) { - console.log('SetSyncRange put success'); - }); -}catch(e) { - console.log('SetSyncRange e ' + e); -} -``` - - -### setSyncRange8+ ### - -setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> - -Sets the data synchronization range. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| localLabels |string[] | Yes |Synchronization labels set for the local device. | -| remoteSupportLabels |string[] | Yes |Synchronization labels set for remote devices. | - - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - const localLabels = ['A', 'B']; - const remoteSupportLabels = ['C', 'D']; - kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { - console.log('setSyncRange success'); - }).catch((err) => { - console.log('delete fail ' + err); - }); -}catch(e) { - console.log('SetSyncRange e ' + e); -} -``` - - -## SubscribeType - -Enumerates the subscription types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| SUBSCRIBE_TYPE_LOCAL |0 |Local data changes. | -| SUBSCRIBE_TYPE_REMOTE |1 |Remote data changes. | -| SUBSCRIBE_TYPE_ALL |2 |Local and remote data changes. | - -## ChangeNotification - -Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. | -| updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. | -| deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. | -| deviceId | string | Yes | Yes|UUID of the device. | - -## Entry - -Defines the KV pairs stored in the KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| key | string | Yes | Yes|Key of the KV pair stored in the KV store. | -| value | [Value](#value) | Yes | Yes|Value of the KV pair stored in the KV store. | - - -## Value - -Defines the **value** object in a KV store. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | - -## ValueType - -Enumerates the data types. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| STRING |0 |String. | -| INTEGER |1 |Integer. | -| FLOAT |2 |Float (single-precision floating point). | -| BYTE_ARRAY |3 |Byte array. | -| BOOLEAN |4 |Boolean. | -| DOUBLE |5 |Double (double-precision floating point). | - -## SingleKVStore - -Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). - -Data is not distinguished by device in a single KV store. The data written to different devices using the same key will be overwritten. For example, a single KV store can be used to synchronize a user's calendar and contact data between different devices. - -Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. - -### get - -get(key: string, callback: AsyncCallback<Uint8Array | string | boolean | number>): void - -Obtains the value of the specified key. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback invoked to return the value obtained. | - -**Example** - -```js -let kvStore; -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) { - if (err != undefined) { - console.log("put err: " + JSON.stringify(err)); - return; - } - console.log("put success"); - 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); -} -``` - - -### get - -get(key: string): Promise<Uint8Array | string | boolean | number> - -Obtains the value of the specified key. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | - - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| - -**Example** - -```js -let kvStore; -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).then((data) => { - console.log("put success: " + JSON.stringify(data)); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log("get success data: " + data); - }).catch((err) => { - console.log("get err: " + JSON.stringify(err)); - }); - }).catch((err) => { - console.log("put err: " + JSON.stringify(err)); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} -``` - -### getEntries8+ ### - -getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void - -Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_number_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.INTEGER, - value : 222 - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('batch_test_number_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(keyPrefix: string): Promise<Entry[]> - -Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keyPrefix |string | Yes |Key prefix to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); - console.log('entries[0].value.value: ' + entries[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(query: Query, callback: AsyncCallback<Entry[]>): void - -Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(query: Query): Promise<Entry[]> - -Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains the result set with the specified prefix. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keyPrefix |string | Yes |Key prefix to match.| -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the result set obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('GetResultSet putBatch success'); - kvStore.getResultSet('batch_test_string_key', async function (err, result) { - console.log('GetResultSet getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('GetResultSet closeResultSet success'); - }) - }); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(keyPrefix: string): Promise<KvStoreResultSet> - -Obtains the result set with the specified prefix. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keyPrefix |string | Yes |Key prefix to match.| - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the result set obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - kvStore.getResultSet('batch_test_string_key').then((result) => { - console.log('GetResult getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResult closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResult e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |Query | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(query: Query): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet(query).then((result) => { - console.log(' getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - -### 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 capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let resultSet; - let predicates = new dataSharePredicates.DataSharePredicates(); - predicates.prefixKey("batch_test_string_key"); - kvStore.getResultSet(predicates, async function (err, result) { - console.log(' GetResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` -### 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 capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let resultSet; - let predicates = new dataSharePredicates.DataSharePredicates(); - predicates.prefixKey("batch_test_string_key"); - kvStore.getResultSet(predicates) .then((result) => { - console.log(' GetResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void - -Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet): Promise<void> - -Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#kvstoreresultset8) | Yes |**KvStoreResultSet** object to close. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(query: Query, callback: AsyncCallback<number>): void - -Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(query: Query): Promise<number> - -Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void - -Deletes data of a device. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('put success'); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string): Promise<void> - -Deletes data of a device. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('removeDeviceData put success'); - }).catch((err) => { - console.log('put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### on('syncComplete')8+ ### - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to the data synchronization complete events. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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. | - -**Example** - -```js -let kvStore; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const VALUE_TEST_FLOAT_ELEMENT = 321.12; -try { - kvStore.on('syncComplete', function (data) { - console.log('syncComplete ' + data) - }); - kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); -}catch(e) { - console.log('syncComplete put e ' + e); -} -``` - - -### off('syncComplete')8+ ### - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void - -Unsubscribes from the data synchronization complete events. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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. | - -**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); -} -``` - -### on('dataChange')9+ ### - -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data changes of the specified type. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); - -``` - -### off('dataChange')9+ ### - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from the data change events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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.| - -**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); -}); -``` -### sync7+ - - -sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); -``` - -### sync9+ -sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(devices, query, mode , 1000); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### setSyncParam8+ ### - -setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void - -Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs, function (err,data) { - console.log('SetSyncParam put success'); - }); -}catch(e) { - console.log('testSingleKvStoreSetSyncParam e ' + e); -} -``` - - -### setSyncParam8+ ### - -setSyncParam(defaultAllowedDelayMs: number): Promise<void> - -Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| defaultAllowedDelayMs |number | Yes |Default delay allowed for database synchronization, in ms. | - - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - const defaultAllowedDelayMs = 500; - kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { - console.log('SetSyncParam put success'); - }).catch((err) => { - console.log('SetSyncParam put fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('SetSyncParam e ' + e); -} -``` - - -### getSecurityLevel8+ ### - -getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void - -Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| callback |AsyncCallback<[SecurityLevel](#securitylevel)> | Yes |Callback invoked to return the security level obtained. | - -**Example** - -```js -let kvStore; -try { - kvStore.getSecurityLevel(function (err,data) { - console.log('getSecurityLevel success'); - }); -}catch(e) { - console.log('GetSecurityLevel e ' + e); -} -``` - - -### getSecurityLevel8+ ### - -getSecurityLevel(): Promise<SecurityLevel> - -Obtains the security level of this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[SecurityLevel](#securitylevel)> |Promise used to return the security level obtained.| - -**Example** - -```js -let kvStore; -try { - kvStore.getSecurityLevel().then((data) => { - console.log(' getSecurityLevel success'); - }).catch((err) => { - console.log('getSecurityLevel fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetSecurityLevel e ' + e); -} -``` - - -## DeviceKVStore8+ ## - -Provides methods to query and synchronize data in a device KV store. This class inherits from [KVStore](#kvstore). - -Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. - -For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted. - -Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. - -### get8+ ### - -get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void - -Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| key |string | Yes |Key to match. | -| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback used to return the value obtained. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; -try{ - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('put success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err,data) { - console.log('get success'); - }); - }) -}catch(e) { - console.log('get e' + e); -} -``` - - -### get8+ ### - -get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> - -Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| key |string | Yes |Key to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { - console.log(' put success'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('get success'); - }).catch((err) => { - console.log('get fail ' + JSON.stringify(err)); - }); - }).catch((error) => { - console.log('put error' + error); - }); -} catch (e) { - console.log('Get e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void - -Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> - -Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| keyPrefix |string | Yes |Key prefix to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - console.log('entries: ' + entries); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - console.log('entries[0].value: ' + JSON.stringify(entries[0].value)); - console.log('entries[0].value.value: ' + entries[0].value.value); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(query: Query, callback: AsyncCallback<Entry[]>): void - -Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback used to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getEntries(query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(query: Query): Promise<Entry[]> - -Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getEntries(query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('GetEntries putBatch fail ' + JSON.stringify(err)) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void - -Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[Entry](#entry)[]> | Yes |Callback invoked to return the KV pairs obtained. | - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries, async function (err,data) { - console.log('putBatch success'); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - kvStore.getEntries('localDeviceId', query, function (err,entries) { - console.log('getEntries success'); - console.log('entries.length: ' + entries.length); - console.log('entries[0]: ' + JSON.stringify(entries[0])); - }) - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getEntries8+ ### - -getEntries(deviceId: string, query: Query): Promise<Entry[]> - -Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[Entry](#entry)[]> |Promise used to return the KV pairs obtained.| - -**Example** - -```js -let kvStore; -try { - var arr = new Uint8Array([21,31]); - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_bool_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.BYTE_ARRAY, - value : arr - } - } - entries.push(entry); - } - console.log('entries: ' + JSON.stringify(entries)); - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - var query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - kvStore.getEntries('localDeviceId', query).then((entries) => { - console.log('getEntries success'); - }).catch((err) => { - console.log('getEntries fail ' + JSON.stringify(err)); - }); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - console.log('GetEntries success'); -}catch(e) { - console.log('GetEntries e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(deviceId: string, keyPrefix: string): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| keyPrefix |string | Yes |Key prefix to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(query: Query, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSet(query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(query: Query): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + err); - }); - const query = new distributedData.Query(); - query.deviceId('localDeviceId'); - query.prefixKey("batch_test"); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.getResultSet(query).then((result) => { - console.log('getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query, async function (err, result) { - console.log('getResultSet succeed.'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log('closeResultSet success'); - }) - }); - }); -} catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### getResultSet8+ ### - -getResultSet(deviceId: string, query: Query): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -let kvStore; -try { - let resultSet; - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('GetResultSet putBatch success'); - }).catch((err) => { - console.log('PutBatch putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSet('localDeviceId', query).then((result) => { - console.log('GetResultSet getResultSet succeed.'); - resultSet = result; - }).catch((err) => { - console.log('GetResultSet getResultSet failed: ' + JSON.stringify(err)); - }); - query.deviceId('localDeviceId'); - console.log("GetResultSet " + query.getSqlLike()); - kvStore.closeResultSet(resultSet).then((err) => { - console.log('GetResultSet closeResultSet success'); - }).catch((err) => { - console.log('GetResultSet closeResultSet fail ' + JSON.stringify(err)); - }); - -}catch(e) { - console.log('GetResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void - -Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet, function (err, data) { - if (err == undefined) { - console.log('closeResultSet success'); - } else { - console.log('closeResultSet fail'); - } - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### closeResultSet8+ ### - -closeResultSet(resultSet: KvStoreResultSet): Promise<void> - -Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| resultSet |[KvStoreResultSet](#getresultset8) | Yes |**KvStoreResultSet** object to close. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - console.log('CloseResultSet success'); - let resultSet = null; - kvStore.closeResultSet(resultSet).then(() => { - console.log('closeResultSet success'); - }).catch((err) => { - console.log('closeResultSet fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('CloseResultSet e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(query: Query, callback: AsyncCallback<number>): void - -Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSize(query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(query: Query): Promise<number> - -Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.getResultSize(query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; - -Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<number> | Yes |Callback invoked to return the number of results obtained. | - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries, async function (err, data) { - console.log('putBatch success'); - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { - console.log('getResultSet succeed.'); - }); - }); -} catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### getResultSize8+ ### - -getResultSize(deviceId: string, query: Query): Promise<number> - -Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| query |[Query](#query8) | Yes |**Query** object to match. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<number> |Promise used to return the number of results obtained.| - -**Example** - -```js -let kvStore; -try { - let entries = []; - for (var i = 0; i < 10; i++) { - var key = 'batch_test_string_key'; - var entry = { - key : key + i, - value : { - type : distributedData.ValueType.STRING, - value : 'batch_test_string_value' - } - } - entries.push(entry); - } - kvStore.putBatch(entries).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); - var query = new distributedData.Query(); - query.prefixKey("batch_test"); - kvStore.getResultSize('localDeviceId', query).then((resultSize) => { - console.log('getResultSet succeed.'); - }).catch((err) => { - console.log('getResultSet failed: ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('GetResultSize e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void - -Deletes data of the specified device from this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | -| callback |AsyncCallback<void> | Yes |Callback used to return the result. | - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData put success'); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid, async function (err,data) { - if (err == undefined) { - console.log('removeDeviceData success'); - } else { - console.log('removeDeviceData fail'); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, async function (err,data) { - console.log('RemoveDeviceData get success'); - }); - } - }); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### removeDeviceData8+ ### - -removeDeviceData(deviceId: string): Promise<void> - -Deletes data of the specified device from this KV store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceId |string | Yes |ID of the target device. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -const KEY_TEST_STRING_ELEMENT = 'key_test_string'; -const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; -try { - kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { - console.log('RemoveDeviceData put success'); - }).catch((err) => { - console.log('RemoveDeviceData put fail ' + JSON.stringify(err)); - }); - const deviceid = 'no_exist_device_id'; - kvStore.removeDeviceData(deviceid).then((err) => { - console.log('removeDeviceData success'); - }).catch((err) => { - console.log('removeDeviceData fail ' + JSON.stringify(err)); - }); - kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { - console.log('RemoveDeviceData get success data:' + data); - }).catch((err) => { - console.log('RemoveDeviceData get fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('RemoveDeviceData e ' + e); -} -``` - - -### sync8+ ### - -sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - kvStore.sync(devices, mode); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### sync9+ ### - -sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| -| query |[Query](#query8) | Yes | **Query** object to match.| -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(devices, query, 1000); - }); -}catch(e) { - console.log('Sync e' + e); -} -``` - -### on('syncComplete')8+ ### - -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void - -Subscribes to the data synchronization complete events. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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. | - -**Example** - -```js -let kvStore; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const VALUE_TEST_FLOAT_ELEMENT = 321.12; -try { - kvStore.on('syncComplete', function (data) { - console.log('syncComplete ' + data) - }); - kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); -}catch(e) { - console.log('syncComplete put e ' + e); -} -``` - - -### off('syncComplete')8+ ### - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void - -Unsubscribes from the synchronization complete events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data changes of the specified type. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); -``` - - -### off('dataChange')9+ ### - -off(event:'dataChange', listener?: Callback<ChangeNotification>): void - -Unsubscribes from the data change events. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| 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.| - -**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); -}); -``` - -## SyncMode - -Enumerates the synchronization modes. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -| Name | Value | Description | -| ----- | ------ | ----------------------- | -| 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-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index bad85aee529e6f5b2bff68cd79fd4172c53e7969..5682921badad9367817fd3e421b1afb823970425 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -39,26 +39,60 @@ Creates a **KVManager** instance to manage KV stores. This API uses an asynchron | callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| **Example** + +Stage model: +```ts +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; + }); + } +} +``` + +FA model: ```js +import AbilityStage from '@ohos.application.Ability' let kvManager; -try { +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } + context: context.getApplicationContext(), + 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; + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } } ``` @@ -84,24 +118,59 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to **Example** +Stage model: +```ts +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; + }); + } +} +``` + +FA model: ```js +import AbilityStage from '@ohos.application.Ability' let kvManager; -try { +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context const kvManagerConfig = { - bundleName : 'com.example.datamanagertest', - userInfo : { - userId : '0', - userType : distributedData.UserType.SAME_USER_ID - } + context: context.getApplicationContext(), + bundleName: 'com.example.datamanagertest', + userInfo: { + userId: '0', + userType: distributedData.UserType.SAME_USER_ID + } } - distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("createKVManager success"); - kvManager = manager; - }).catch((err) => { - console.log("createKVManager err: " + JSON.stringify(err)); + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager"); + kvManager = manager; }); -} catch (e) { - console.log("An unexpected error occurred. Error:" + e); + } } ``` @@ -113,7 +182,7 @@ Provides configuration of the **KVManager** object, including the bundle name an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| context | Context | Yes| Context of the application or function.
See [Context](js-apis-Context.md) for versions earlier than API version 9.
See [Context](js-apis-ability-context.md) for API version 9 or later.| +| context9+ | 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).| | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| @@ -572,9 +641,9 @@ Provides KV store configuration. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | -| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | +| backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | autoSync | boolean | No|Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC | | kvStoreType | [KVStoreType](#kvstoretype) | No|Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | securityLevel | [SecurityLevel](#securitylevel) | No|Security level of the KV store. By default, the security level is not set.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | @@ -1238,7 +1307,7 @@ Creates a **Query** object to match the specified field whose value is equal to | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1273,7 +1342,7 @@ Creates a **Query** object to match the specified field whose value is not equal | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1308,7 +1377,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1343,7 +1412,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1378,7 +1447,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1413,7 +1482,7 @@ Creates a **Query** object to match the specified field whose value is less than | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1447,7 +1516,7 @@ Creates a **Query** object to match the specified field whose value is **null**. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1483,7 +1552,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1518,7 +1587,7 @@ Creates a **Query** object to match the specified field whose value is within th | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1553,7 +1622,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1588,7 +1657,7 @@ Creates a **Query** object to match the specified field whose value is not withi | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1623,7 +1692,7 @@ Creates a **Query** object to match the specified field whose value is similar t | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1658,7 +1727,7 @@ Creates a **Query** object to match the specified field whose value is not simil | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1752,7 +1821,7 @@ Creates a **Query** object to sort the query results in ascending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1787,7 +1856,7 @@ Creates a **Query** object to sort the query results in descending order. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1823,7 +1892,7 @@ Creates a **Query** object to specify the number of results and where to start. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1860,7 +1929,7 @@ Creates a **Query** object to match the specified field whose value is not **nul | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1888,7 +1957,7 @@ Creates a **Query** object for a query condition group with a left parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1918,7 +1987,7 @@ Creates a **Query** object for a query condition group with a right parenthesis. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1954,7 +2023,7 @@ Creates a **Query** object with a specified key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -1989,7 +2058,7 @@ Creates a **Query** object with an index preferentially used for query. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -2025,7 +2094,7 @@ Creates a **Query** object with the device ID as the key prefix. | Type | Description | | ------ | ------- | -| [Query](#query8) |**Query** object.| +| [Query](#query8) |**Query** object created.| **Example** @@ -2232,7 +2301,7 @@ try { ### delete9+ -delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>): void +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. @@ -2242,13 +2311,13 @@ Deletes KV pairs that meet the specified predicates. This API uses an asynchrono | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| | callback | AsyncCallback<void> | Yes |Callback used to return the result. | **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let predicates = new dataSharePredicates.DataSharePredicates(); @@ -2276,7 +2345,7 @@ Deletes KV pairs that meet the specified predicates. This API uses a promise to | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| **Return value** @@ -2288,7 +2357,7 @@ Deletes KV pairs that meet the specified predicates. This API uses a promise to **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let predicates = new dataSharePredicates.DataSharePredicates(); @@ -2312,7 +2381,7 @@ try { ### on('dataChange') -on(event: 'dataChange', type: SubscribeType, observer: Callback<ChangeNotification>): void +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void Subscribes to data change notifications of the specified type. @@ -2324,7 +2393,7 @@ Subscribes to data change notifications of the specified type. | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates data changes. | | type |[SubscribeType](#subscribetype) | Yes |Type of data changes. | -| observer |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| +| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback used to return the data changes.| **Example** @@ -2362,7 +2431,7 @@ kvStore.on('syncComplete', function (data) { ### off('dataChange')8+ -off(event:'dataChange', observer?: Callback<ChangeNotification>): void +off(event:'dataChange', listener?: Callback<ChangeNotification>): void Unsubscribes from data change notifications. @@ -2373,7 +2442,7 @@ Unsubscribes from data change notifications. | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates data changes. | -| observer |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| +| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback used to return the data changes.| **Example** @@ -2422,7 +2491,7 @@ try { putBatch(entries: Entry[], callback: AsyncCallback<void>): void -Inserts KV pairs to this KV store in batches. This API uses an asynchronous callback to return the result. +Inserts KV pairs in batches to this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2469,7 +2538,7 @@ try { putBatch(entries: Entry[]): Promise<void> -Inserts KV pairs to this KV store in batches. This API uses a promise to return the result. +Inserts KV pairs in batches to this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2523,7 +2592,7 @@ try { putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void -Writes values 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 capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2531,7 +2600,7 @@ Writes values to this KV store. This API uses an asynchronous callback to return | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| value |Array[<ValuesBucket>]()[] | Yes |Values to write. | +| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | | callback |Asyncallback<void> |Yes |Callback used to return the result.| **Example** @@ -2562,7 +2631,7 @@ try { putBatch(value: Array<ValuesBucket>): Promise<void> -Writes values of the **valuesbucket** type to this KV store. This API uses a promise to return the result. +Writes data of the **valuesbucket** type to this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2570,7 +2639,7 @@ Writes values of the **valuesbucket** type to this KV store. This API uses a pro | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket>](#)[] | Yes |Values to write. | +| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | **Return value** @@ -2607,7 +2676,7 @@ try { deleteBatch(keys: string[], callback: AsyncCallback<void>): void -Deletes KV pairs from this KV store in batches. This API uses an asynchronous callback to return the result. +Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2654,7 +2723,7 @@ try { deleteBatch(keys: string[]): Promise<void> -Deletes KV pairs from this KV store in batches. This API uses a promise to return the result. +Deletes KV pairs in batches from this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2797,7 +2866,7 @@ try { commit(callback: AsyncCallback<void>): void -Submits the transaction in this KV store. This API uses an asynchronous callback to return the result. +Commits the transaction in this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2829,7 +2898,7 @@ try { commit(): Promise<void> -Submits the transaction in this KV store. This API uses a promise to return the result. +Commits the transaction in this KV store. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3104,7 +3173,7 @@ Defines the **value** object in a KV store. | Name | Type |Readable |Writable | Description | | ----- | ------- | -----| ------|------------------------ | | type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value. | +| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | ## ValueType @@ -3121,7 +3190,6 @@ Enumerates the data types. | BOOLEAN |4 |Boolean. | | DOUBLE |5 |Double (double-precision floating point). | - ## SingleKVStore Provides methods to query and synchronize data in a single KV store. This class inherits from [KVStore](#kvstore). @@ -3641,7 +3709,7 @@ try { getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void -Obtains a **KvStoreResultSet** object that matches the specified **Predicates** object. This API uses an asynchronous callback to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3649,13 +3717,13 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates | Predicates | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | +| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | | callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let resultSet; @@ -3676,7 +3744,7 @@ try { getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> -Obtains a **KvStoreResultSet** object that matches the specified **Predicates** object. This API uses a promise to return the result. +Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3684,7 +3752,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| predicates |[Predicates](#) | Yes |**Predicates** object to match. If this parameter is **null**, define the processing logic. | +| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | **Return value** @@ -3695,7 +3763,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Predicates** **Example** ```js -import dataSharePredicates from './@ohos.data.dataSharePredicates'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let kvStore; try { let resultSet; @@ -3704,7 +3772,7 @@ try { kvStore.getResultSet(predicates) .then((result) => { console.log(' GetResultSet success'); resultSet = result; - kvStore.closeResultSet(resultSet, fun ction (err, data) { + kvStore.closeResultSet(resultSet, function (err, data) { console.log(' closeResultSet success'); }) }); @@ -3716,7 +3784,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object returned by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3750,7 +3818,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object returned by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. +Closes the **KvStoreResultSet** object obtained by [SingleKvStore.getResultSet](#singlekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -3988,7 +4056,7 @@ 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 invoked to return the synchronization result. | +| syncCallback |Callback<Array<[string, number]>> | Yes |Callback called to return the synchronization result. | **Example** @@ -4045,7 +4113,7 @@ try { on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. +Subscribes to data changes of the specified type. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4071,7 +4139,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API uses a synchronous callback to return the result. +Unsubscribes from the data change events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -4096,7 +4164,7 @@ kvStore.off('dataChange', function (data) { ### sync7+ -sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void +sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). @@ -4108,9 +4176,9 @@ Synchronizes the KV store manually. For details about the synchronization modes | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIdList |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | +| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | +| delayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -4122,7 +4190,7 @@ kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); ### sync9+ sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. This API uses a synchronous mode. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -4140,7 +4208,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail **Example** ```js -let kvstore; +let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; try { @@ -4154,7 +4222,7 @@ try { const query = new distributedData.Query(); query.prefixKey("batch_test"); query.deviceId('localDeviceId'); - kvStore.sync(devices, query, PULL_ONLY , 1000); + kvStore.sync(devices, query, mode , 1000); }); }catch(e) { console.log('Sync e' + e); @@ -5023,7 +5091,7 @@ try { closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void -Closes the **KvStoreResultSet** object returned by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. +Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5058,7 +5126,7 @@ try { closeResultSet(resultSet: KvStoreResultSet): Promise<void> -Closes the **KvStoreResultSet** object returned by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. +Closes the **KvStoreResultSet** object obtained by [DeviceKVStore.getResultSet](#devicekvstore_getresultset). This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -5391,7 +5459,7 @@ try { ### sync8+ ### -sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void +sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). @@ -5403,9 +5471,9 @@ Synchronizes the KV store manually. For details about the synchronization modes | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| deviceIdList |string[] | Yes |IDs of the devices to be synchronized.| +| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| | mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| allowedDelayMs |number | No |Allowed synchronization delay time, in ms. | +| delayMs |number | No |Allowed synchronization delay time, in ms. | **Example** @@ -5432,7 +5500,7 @@ try { sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void -Synchronizes the KV store manually. This API uses a synchronous mode. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). +Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview] (../../database/database-mdds-overview.md). **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -5449,7 +5517,7 @@ Synchronizes the KV store manually. This API uses a synchronous mode. For detail **Example** ```js -let kvstore; +let kvStore; const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; try { @@ -5510,7 +5578,7 @@ try { off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization complete events. This API uses a synchronous callback to return the result. +Unsubscribes from the synchronization complete events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5540,7 +5608,7 @@ try { on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API uses a synchronous callback to return the result. +Subscribes to data changes of the specified type. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5566,7 +5634,7 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from the data change events. This API uses a synchronous callback to return the result. +Unsubscribes from the data change events. This API returns the result synchronously. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -5600,3 +5668,4 @@ 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-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index fa54f6739279745a1f7538fd32abf0fca6402711..6398b87f685e5f91c59dacb1da97b4ad993e5afa 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -1,6 +1,9 @@ # Emitter -> **NOTE**
+The **Emitter** module provides APIs for sending and processing in-process events, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue. + +> **NOTE** +> > The initial APIs of this module are supported since API version 7. ## Modules to Import @@ -17,12 +20,14 @@ None Enumerates the event emit priority levels. - | Name | Value | Description | - | --------- | ---- | ------------------------------------------------- | - | IMMEDIATE | 0 | The event will be emitted immediately.
**System capability**: SystemCapability.Notification.Emitter | - | HIGH | 1 | The event will be emitted before low-priority events.
**System capability**: SystemCapability.Notification.Emitter | - | LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority.
**System capability**: SystemCapability.Notification.Emitter | - | IDLE | 3 | The event will be emitted after all the other events.
**System capability**: SystemCapability.Notification.Emitter | +**System capability**: SystemCapability.Notification.Emitter + +| Name | Value | Description | +| --------- | ---- | ------------------------------------------------- | +| IMMEDIATE | 0 | The event will be emitted immediately. | +| HIGH | 1 | The event will be emitted before low-priority events. | +| LOW | 2 | The event will be emitted before idle-priority events. By default, an event is in LOW priority. | +| IDLE | 3 | The event will be emitted after all the other events. | ## emitter.on @@ -34,10 +39,10 @@ Subscribes to an event in persistent manner. This API uses a callback to return **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ----------------------------------- | ---- | ------------------------ | - | event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. | - | callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------ | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in persistent manner. | +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| **Example** @@ -61,10 +66,10 @@ Subscribes to an event in one-shot manner and unsubscribes from it after the eve **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ----------------------------------- | ---- | ------------------------ | - | event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. | - | callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------ | +| event | [InnerEvent](#innerevent) | Yes | Event to subscribe to in one-shot manner. | +| callback | Callback\<[EventData](#eventdata)\> | Yes | Callback used to return the event.| **Example** @@ -88,9 +93,9 @@ Unsubscribes from an event. **Parameters** - | Name | Type | Mandatory | Description | - | ------- | ------ | ---- | ------ | - | eventId | number | Yes | Event ID. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------ | +| eventId | number | Yes | Event ID.| **Example** @@ -108,10 +113,10 @@ Emits an event to the event queue. **Parameters** - | Name | Type | Mandatory | Description | - | ------ | ------------------------- | ---- | -------------- | - | event | [InnerEvent](#innerevent) | Yes | Event to emit. | - | data | [EventData](#eventdata) | No | Data carried by the event. | +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- | -------------- | +| event | [InnerEvent](#innerevent) | Yes | Event to emit. | +| data | [EventData](#eventdata) | No | Data carried by the event.| **Example** @@ -130,17 +135,21 @@ emitter.emit(innerEvent, eventData); ## InnerEvent -Describes an intra-process event. +Describes an in-process event. - | Name | Type | Readable | Writable | Description | - | -------- | ------------------------------- | ---- | ---- | ---------------------------------- | - | eventId | number | Yes | Yes | Event ID, which is used to identify an event.
**System capability**: SystemCapability.Notification.Emitter | - | priority | [EventPriority](#eventpriority) | Yes | Yes | Emit priority of the event.
**System capability**: SystemCapability.Notification.Emitter | +**System capability**: SystemCapability.Notification.Emitter + +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------- | ---- | ---- | ---------------------------------- | +| eventId | number | Yes | Yes | Event ID, which is used to identify an event.| +| priority | [EventPriority](#eventpriority) | Yes | Yes | Emit priority of the event. | ## EventData Describes the data passed in the event. - | Name | Type | Readable | Writable | Description | - | ---- | ------------------ | ---- | ---- | -------------- | - | data | [key: string]: any | Yes | Yes | Data carried by the event. The data type can be String, Integer, or Boolean.
**System capability**: SystemCapability.Notification.Emitter | +**System capability**: SystemCapability.Notification.Emitter + +| Name| Type | Readable| Writable| Description | +| ---- | ------------------ | ---- | ---- | -------------- | +| data | [key: string]: any | Yes | Yes | Data carried by the event. The data type can be String, Integer, or Boolean.| diff --git a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md index 25c0dbf964cc82eaddc85ff1114c440afbd00d2d..1849150107a5922136403a0c01cb24eb1152d675 100644 --- a/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-enterprise-device-manager.md @@ -1,57 +1,93 @@ # Enterprise Device Management -> **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 **enterpriseDeviceManager** module provides enterprise device management capabilities so that devices have the customization capabilities required in enterprise scenarios. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import enterpriseDeviceManager from '@ohos.enterpriseDeviceManager'; ``` - ## enterpriseDeviceManager.enableAdmin -enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number, callback: AsyncCallback\): void +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\): void Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", +}; +let enterpriseInfo = { + name: "enterprise name", + description: "enterprise description" +} +enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## enterpriseDeviceManager.enableAdmin + +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId: number, callback: AsyncCallback\): void -ohos.permission.MANAGE_ADMIN +Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.MANAGE_ADMIN -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` @@ -61,126 +97,145 @@ enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId Enables a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. -**Required permissions** - -ohos.permission.MANAGE_ADMIN +**Required permissions**: ohos.permission.MANAGE_ADMIN -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ---------------------------------------------- | ---- | ------------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | -| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#AdminType) | Yes | Type of the device administrator to enable. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.enableAdmin(wantTemp, enterpriseInfo, enterpriseDeviceManager.AdminType.ADMIN_TYPE_NORMAL, 100) .then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` ## enterpriseDeviceManager.disableAdmin -disableAdmin(admin: Want, userId?: number, callback: AsyncCallback\): void +disableAdmin(admin: Want, callback: AsyncCallback\): void Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +enterpriseDeviceManager.disableAdmin(wantTemp, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## enterpriseDeviceManager.disableAdmin + +disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void -ohos.permission.MANAGE_ADMIN +Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** +**Required permissions**: ohos.permission.MANAGE_ADMIN -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | ---- | ------------------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -``` +```js let wantTemp = { - bundleName: elementName.bundleName, - abilityName: elementName.abilityName, + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.disableAdmin(wantTemp, 100, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` - - ## enterpriseDeviceManager.disableAdmin disableAdmin(admin: Want, userId?: number): Promise\ Disables a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. -**Required permissions** +**Required permissions**: ohos.permission.MANAGE_ADMIN -ohos.permission.MANAGE_ADMIN - -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ---------------------------------------------- | ---- | ------------------ | -| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ------ | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device common administrator application. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.disableAdmin(wantTemp, 100).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -190,27 +245,25 @@ disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void Disables a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ----------------------- | ---- | ------------------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | ------------------- | +| bundleName | String | Yes | Bundle name of the device super administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.disableSuperAdmin(bundleName, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` @@ -220,68 +273,93 @@ disableSuperAdmin(bundleName: String): Promise\ Disables a device super administrator application based on the specified bundle name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ------ | ---- | ------------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------ | +| bundleName | String | Yes | Bundle name of the device super administrator application.| **Return value** - | Type | Description | - | ----------------- | --------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.disableSuperAdmin(bundleName).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` ## enterpriseDeviceManager.isAdminEnabled -isAdminEnabled(admin: Want, userId?: number, callback: AsyncCallback\): void +isAdminEnabled(admin: Want, callback: AsyncCallback\): void Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------- | ---- | -------------------------------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | -------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: elementName.bundleName, - abilityName: elementName.abilityName, + bundleName: "bundleName", + abilityName: "abilityName", }; -enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => { +enterpriseDeviceManager.isAdminEnabled(wantTemp, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` +## enterpriseDeviceManager.isAdminEnabled + +isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\): void + +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| userId | number | Yes | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +enterpriseDeviceManager.isAdminEnabled(wantTemp, 100, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` ## enterpriseDeviceManager.isAdminEnabled @@ -289,34 +367,32 @@ isAdminEnabled(admin: Want, userId?: number): Promise\ Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ---------------------------------------------- | ---- | -------------- | -| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | -| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| Name | Type | Mandatory | Description | +| ------ | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| userId | number | No | User ID The default value is the user ID of the caller. The value must be greater than or equal to 0.| **Return value** - | Type | Description | - | ----------------- | ------------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; enterpriseDeviceManager.isAdminEnabled(wantTemp, 100).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -326,62 +402,56 @@ isSuperAdmin(bundleName: String, callback: AsyncCallback\): void Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ----------------------- | ---- | -------------------------------- | - | bundleName | String | Yes | Bundle name of a device super administrator application. | - | callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | -------------------- | +| bundleName | String | Yes | Device administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.isSuperAdmin(bundleName, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } - console.log(result); + console.log("result is " + result); }); ``` - - ## enterpriseDeviceManager.isSuperAdmin isSuperAdmin(bundleName: String): Promise\ Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ---------- | ------ | ---- | ------------------ | - | bundleName | String | Yes | Bundle name of a device super administrator application. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| bundleName | String | Yes | Device super administrator application.| **Return value** - | Type | Description | - | ----------------- | ------------------------------- | - | Promise\ | Promise used to return the result. | +| Type | Description | +| ----------------- | ------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let bundleName = "com.example.myapplication"; enterpriseDeviceManager.isSuperAdmin(bundleName).then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -391,27 +461,25 @@ getDeviceSettingsManager(callback: AsyncCallback<DeviceSettingsManager>): Obtains a **DeviceSettingsManager** object. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback { if (error != null) { console.log("error occurs" + error); - return; + return; } mgr.setDateTime(wantTemp, 1526003846000, (error, value) => { if (error != null) { @@ -423,31 +491,28 @@ enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { }); ``` - ## enterpriseDeviceManager.getDeviceSettingsManager getDeviceSettingsManager(): Promise<DeviceSettingsManager> Obtains a **DeviceSettingsManager** object. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Return value** - | Type | Description | - | -------- | -------- | - | Promise<DeviceSettingsManager> | Promise used to return the **DeviceSettingsManager** object obtained. | +| Type | Description | +| ------------------------------------ | ---------------------------------- | +| Promise<DeviceSettingsManager> | Promise used to return the **DeviceSettingsManager** object obtained.| **Example** -``` +```js let wantTemp = { - bundleName: "bundleName", - abilityName: "abilityName", + bundleName: "bundleName", + abilityName: "abilityName", }; -mgr.getDeviceSettingsManager().then((mgr) => { +enterpriseDeviceManager.getDeviceSettingsManager().then((mgr) => { mgr.setDateTime(wantTemp, 1526003846000).then((value) => { console.log(value); }).catch((error) => { @@ -464,77 +529,72 @@ setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCa Sets the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | ---------------------------------------------- | ---- | ------------------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | - | callback | AsyncCallback\ { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` - ## enterpriseDeviceManager.setEnterpriseInfo setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise<boolean> Sets the enterprise information of a device administrator application. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------------- | ---------------------------------------------- | ---- | ------------------------ | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application. | +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#EnterpriseInfo) | Yes | Enterprise information of the device administrator application.| **Return value** - | Type | Description | - | ------------------ | ----------------------------------- | - | Promise\; | Callback used to return the result. | +| Type | Description | +| ----------------- | --------------------- | +| Promise\ | Promise used to return the result.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; let enterpriseInfo = { - name: "enterprise name", - description: "enterprise description" + name: "enterprise name", + description: "enterprise description" } enterpriseDeviceManager.setEnterpriseInfo(wantTemp, enterpriseInfo) .then((result) => { - console.log(result); + console.log("result is " + result); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -544,69 +604,64 @@ getEnterpriseInfo(admin: Want, callback: AsyncCallback<EnterpriseInfo>): v Obtains the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | -------- | ------------------------------------------------------ | ---- | ---------------------------------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | - | callback | AsyncCallback<[EnterpriseInfo](#EnterpriseInfo)> | Yes | Callback used to return the enterprise information of the device administrator application. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| callback | AsyncCallback<[EnterpriseInfo](#EnterpriseInfo)> | Yes | Callback used to return the enterprise information of the device administrator application.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; enterpriseDeviceManager.getEnterpriseInfo(wantTemp, (error, result) => { if (error != null) { console.log("error occurs" + error); - return; + return; } console.log(result.name); - console.log(result.description); + console.log(result.description); }); ``` - ## enterpriseDeviceManager.getEnterpriseInfo getEnterpriseInfo(admin: Want): Promise<EnterpriseInfo> Obtains the enterprise information of a device administrator application. This API uses a promise to return the result. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager **Parameters** - | Name | Type | Mandatory | Description | - | ------ | ---------------------------------------------- | ---- | -------------- | - | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application. | +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application.| **Return value** - | Type | Description | - | ------------------------------------------------ | ------------------------------------------- | - | Promise<[EnterpriseInfo](#EnterpriseInfo)> | Promise used to return the enterprise information of the device administrator application. | +| Type | Description | +| ---------------------------------------- | ------------------------- | +| Promise<[EnterpriseInfo](#EnterpriseInfo)> | Promise used to return the enterprise information of the device administrator application.| **Example** -``` +```js let wantTemp = { - bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", }; enterpriseDeviceManager.getEnterpriseInfo(wantTemp).then((result) => { - console.log(result.name); - console.log(result.description); + console.log(result.name); + console.log(result.description); }).catch(error => { - console.log("error occurs" + error); + console.log("error occurs" + error); }); ``` @@ -614,25 +669,20 @@ enterpriseDeviceManager.getEnterpriseInfo(wantTemp).then((result) => { Describes the enterprise information of a device administrator application. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager - - | Name | Readable/Writable | Type | Mandatory | Description | - | ----------- | -------- | ------ | ---- | ---------------------------------- | - | name | Read only | string | Yes | Name of the enterprise to which the device administrator application belongs. | - | description | Read only | string | Yes | Description of the enterprise to which the device administrator application belongs. | +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager +| Name | Readable/Writable| Type | Mandatory | Description | +| ----------- | ---- | ------ | ---- | ----------------- | +| name | Read only | string | Yes | Name of the enterprise to which the device administrator application belongs.| +| description | Read only | string | Yes | Description of the enterprise to which the device administrator application belongs.| ## AdminType Enumerates the administrator types of the device administrator application. -**System capability** - -SystemCapability.Customation.EnterpriseDeviceManager +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager - | Name | Default Value | Description | - | -------- | -------- | -------- | - | ADMIN_TYPE_NORMAL | 0x00 | Common administrator. | - | ADMIN_TYPE_SUPER | 0x01 | Super administrator. | +| Name | Default Value | Description | +| ----------------- | ---- | ----- | +| ADMIN_TYPE_NORMAL | 0x00 | Common administrator.| +| ADMIN_TYPE_SUPER | 0x01 | Super administrator.| diff --git a/en/application-dev/reference/apis/js-apis-errorManager.md b/en/application-dev/reference/apis/js-apis-errorManager.md new file mode 100644 index 0000000000000000000000000000000000000000..a06e1650bd6f3614a33c58dd092b55451d0a0db8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-errorManager.md @@ -0,0 +1,139 @@ +# ErrorManager + +The **ErrorManager** module provides APIs for registering and deregistering error observers. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import +``` +import errorManager from '@ohos.application.errorManager' +``` + +## ErrorManager.registerErrorObserver + +registerErrorObserver(observer: ErrorObserver): number; + +Registers an error observer. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observer | [ErrorObserver](#errorobserver) | No| Numeric code of the observer.| + +**Example** + +```js +var observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + } +} +errorManager.registerErrorObserver(observer) + .then((data) => { + console.log('----------- registerErrorObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- registerErrorObserver fail ----------', err); + }) + +``` + +## ErrorManager.unregisterErrorObserver + +unregisterErrorObserver(observerId: number, callback: AsyncCallback\): void; + +Deregisters an error observer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | No| Numeric code of the observer.| +| callback | AsyncCallback\ | No| Callback used to return the result.| + +**Example** + +```js +var observerId = 100; + +function unregisterErrorObserverCallback(err) { + if (err) { + console.log('------------ unregisterErrorObserverCallback ------------', err); + } +} +errorManager.unregisterErrorObserver(observerId, unregisterErrorObserverCallback); + +``` + +## ErrorManager.unregisterErrorObserver + +unregisterErrorObserver(observerId: number): Promise\; + +Deregisters an error observer. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | No| Numeric code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +var observerId = 100; +errorManager.unregisterErrorObserver(observerId) +.then((data) => { + console.log('----------- unregisterErrorObserver success ----------', data); +}) +.catch((err) => { + console.log('----------- unregisterErrorObserver fail ----------', err); +}) + +``` + +## ErrorObserver + +onUnhandledException(errMsg: string): void; + +Called when an unhandled exception occurs in the JS runtime. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| errMsg | string | No| Message and error stack trace about the exception.| + +**Example** + +```js +var observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + } +} +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-filemanager.md b/en/application-dev/reference/apis/js-apis-filemanager.md index 38d6d982683a111a7ef98acfbd0d6f8f8d61ba4d..9aa6294c56aed0d897ceecc46c4fd4ca6ecd48c6 100644 --- a/en/application-dev/reference/apis/js-apis-filemanager.md +++ b/en/application-dev/reference/apis/js-apis-filemanager.md @@ -1,6 +1,6 @@ # User File Access and Management -The fileManager module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. +The **fileManager** module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files. >**NOTE**
> @@ -35,12 +35,10 @@ Obtains information about the root album or directory in asynchronous mode. This **Example** ```js - filemanager.getRoot().then((fileInfo) => { - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } + filemanager.getRoot().then((fileInfos) => { + for (var i = 0; i < fileInfos.length; i++) { + console.log("files:"+JSON.stringify(fileInfos)); + } }).catch((err) => { console.log(err) }); @@ -69,14 +67,11 @@ Obtains information about the root album or directory in asynchronous mode. This "name":"local" } }; - filemanager.getRoot(options, (err, fileInfo)=>{ - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } + filemanager.getRoot(options, (err, fileInfos)=>{ + for (var i = 0; i < fileInfos.length; i++) { + console.log("files:"+JSON.stringify(fileInfos)); + } }); - ``` ## filemanager.listFile @@ -111,18 +106,17 @@ Obtains information about the second-level album or files in asynchronous mode. **Example** ```js - // Obtain all files in the directory. - // Call listFile() and getRoot() to obtain the file URI. - let media_path = "" - filemanager.listFile(media_path, "file") - .then((fileInfo) => { - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } + // Obtain all files in the directory. You can use getRoot to obtain the directory URI. + filemanager.getRoot().then((fileInfos) => { + let file = fileInfos.find(item => item.name == "file_folder"); + let path = file.path; + filemanager.listFile(path, "file").then((files) => { + console.log("files:" + JSON.stringify(files)); + }).catch((err) => { + console.log("failed to get files" + err); + }); }).catch((err) => { - console.log("Failed to get file"+err); + console.log("failed to get root" + err); }); ``` @@ -153,33 +147,18 @@ Obtains information about the second-level album or files in asynchronous mode. **Example** - ```js - // Call listFile() and getRoot() to obtain the file path. - let fileInfos = filemanager.getRoot(); - let media_path = ""; - for (let i = 0; i < fileInfos.length; i++) { - if (fileInfos[i].name == "image_album") { - media_path = fileInfos[i].path; - } else if (fileInfos[i].name == "audio_album") { - media_path = fileInfos[i].path; - } else if (fileInfos[i].name == "video_album") { - media_path = fileInfos[i].path; - } else if (fileInfos[i].name == "file_folder") { - media_path = fileInfos[i].path; - } - } - - filemanager.listFile(media_path, "file") - .then((fileInfo) => { - if(Array.isArray(fileInfo)) { - for (var i = 0; i < fileInfo.length; i++) { - console.log("file:"+JSON.stringify(fileInfo)); - } - } - }).catch((err) => { - console.log("Failed to get file"+err); - }); - ``` +```js +// Obtain all files in the directory. You can use getRoot to obtain the directory URI. +filemanager.getRoot().then((fileInfos) => { + let file = fileInfos.find(item => item.name == "image_album"); + let path = file.path; + filemanager.listFile(path, "image",function(err, files){ + console.log("files:" + JSON.stringify(files)); + }) +}).catch((err) => { + console.log("failed to get root" + err); +}); +``` ## filemanager.createFile diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md index daea33dbb50edf3aec50c84eee9795339bd9c43a..1540e538e1bcc8f53165a3fd277e60f76e73a7a1 100644 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ b/en/application-dev/reference/apis/js-apis-formextension.md @@ -35,15 +35,15 @@ Called to notify the widget provider that a **Form** instance (widget) has been **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-Want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| + | Name| Type | Mandatory| Description | + | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | + | want | [Want](js-apis-application-Want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| **Return value** -| Type | Description | -| ------------------------------------------------------------ | ----------------------------------------------------------- | -| [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| + | Type | Description | + | ------------------------------------------------------------ | ----------------------------------------------------------- | + | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| **Example** @@ -72,9 +72,9 @@ Called to notify the widget provider that a temporary widget has been converted **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------ | -| formId | string | Yes | ID of the widget that requests to be converted to a normal one.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | formId | string | Yes | ID of the widget that requests to be converted to a normal one.| **Example** @@ -96,9 +96,9 @@ Called to notify the widget provider that a widget has been updated. After obtai **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| formId | string | Yes | ID of the widget that requests to be updated.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | formId | string | Yes | ID of the widget that requests to be updated.| **Example** @@ -127,9 +127,9 @@ Called to notify the widget provider of the change of visibility. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ---------------------------- | -| newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| + | Name | Type | Mandatory| Description | + | --------- | ------------------------- | ---- | ---------------------------- | + | newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| **Example** @@ -162,10 +162,10 @@ Called to instruct the widget provider to receive and process the widget event. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ---------------------- | -| formId | string | Yes | ID of the widget that requests the event.| -| message | string | Yes | Event message. | + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ---------------------- | + | formId | string | Yes | ID of the widget that requests the event.| + | message | string | Yes | Event message. | **Example** @@ -187,9 +187,9 @@ Called to notify the widget provider that a **Form** instance (widget) has been **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------ | -| formId | string | Yes | ID of the widget to be destroyed.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | formId | string | Yes | ID of the widget to be destroyed.| **Example** @@ -211,9 +211,9 @@ Called when the configuration of the environment where the ability is running is **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| **Example** @@ -235,9 +235,9 @@ Called when the widget provider receives the status query result of a widget. By **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | No| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-Want.md) | No| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| **Example** @@ -250,3 +250,40 @@ Called when the widget provider receives the status query result of a widget. By } } ``` + +## FormExtension.onShare + +onShare?(formId: string): {[key: string]: any}; + +Called by the widget provider to receive shared widget data. + +This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | formId | string | Yes | ID of a widget.| + +**Return value** + + | Type | Description | + | ------------------------------------------------------------ | ----------------------------------------------------------- | + | {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| + +**Example** + + ```js + class MyFormExtension extends FormExtension { + onShare(formId) { + console.log('FormExtension onShare, formId:' + formId); + let wantParams = { + "temperature":"20", + "time":"2022-8-8 09:59", + }; + return wantParams; + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-formextensioncontext.md b/en/application-dev/reference/apis/js-apis-formextensioncontext.md index f2e1fe143fbac2991698d2dd4244d88b23b0ebd5..7cd19e0e0f9a5d4ae906abd1a6d469893c1e95e0 100644 --- a/en/application-dev/reference/apis/js-apis-formextensioncontext.md +++ b/en/application-dev/reference/apis/js-apis-formextensioncontext.md @@ -2,13 +2,32 @@ The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for Form Extension abilities. -You can use the APIs of this module to start abilities. +You can use the APIs of this module to start Form Extension abilities. > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module can be used only in the stage model. +## Usage + +Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtension** instance. +```js +import FormExtension from '@ohos.application.FormExtension'; +import formBindingData from '@ohos.application.formBindingData' +export default class MyFormExtension extends FormExtension { + onCreate() { + let dataObj1 = { + temperature:"11c", + "time":"11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +} + +``` + ## FormExtensionContext.startAbility startAbility(want: Want, callback: AsyncCallback<void>): void @@ -64,7 +83,7 @@ Starts an ability. This API uses a promise to return the result. | Type | Description | | ------------ | ---------------------------------- | -| Promise\ | Promise used to return the result.| +| Promise<void< | Promise used to return the result.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-formprovider.md b/en/application-dev/reference/apis/js-apis-formprovider.md index 81855948f4994b85d601763ffe5e817a175d3733..fbe8907aed6b59d005f027af62ec4d0b0ec9a141 100644 --- a/en/application-dev/reference/apis/js-apis-formprovider.md +++ b/en/application-dev/reference/apis/js-apis-formprovider.md @@ -189,6 +189,7 @@ Obtains the application's widget information that meets a filter criterion on th **Example** ```js +import formInfo from '@ohos.application.formInfo'; const filter : formInfo.FormInfoFilter = { moduleName : "entry" }; @@ -224,6 +225,7 @@ Obtains the application's widget information on the device. This API uses a prom **Example** ```js +import formInfo from '@ohos.application.formInfo'; const filter : formInfo.FormInfoFilter = { moduleName : "entry" }; @@ -236,13 +238,13 @@ formProvider.getFormsInfo(filter).then((data) => { ## requestPublishForm9+ -requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback<string>): <void>; +requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void; Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -276,13 +278,13 @@ SystemCapability.Ability.Form ## requestPublishForm9+ -requestPublishForm(want: Want, callback: AsyncCallback<string>): <void>; +requestPublishForm(want: Want, callback: AsyncCallback<string>): void; Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -317,9 +319,9 @@ requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData Requests to publish a widget to the widget host. This API uses a promise to return the result. -**System capability** +**System capability**: SystemCapability.Ability.Form -SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -360,6 +362,8 @@ Checks whether a widget can be published to the widget host. This API uses an as **System capability**: SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type | Mandatory| Description | @@ -402,6 +406,8 @@ Checks whether a widget can be published to the widget host. This API uses a pro **System capability**: SystemCapability.Ability.Form +**System API**: This is a system API and cannot be called by third-party applications. + **Return value** | Type | Description | diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 0abc724302fcf89b86421b90c0bb507f1894b312..9baa14b8fcc490c92a115d026628c9f4a5613436 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,6 +1,7 @@ # Internationalization – I18N -> **NOTE**
+> **NOTE** +> > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > - This module 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). @@ -115,7 +116,7 @@ Obtains the system language. setSystemLanguage(language: string): boolean -Sets the system language. +Sets the system language. Currently, this API does not support real-time updating of the system language. This is a system API. @@ -673,7 +674,7 @@ Formats a phone number. phonenumberfmt.format("15812312312"); ``` -### getLocationName8+ +### getLocationName9+ static getLocationName(number: string, locale: string): string @@ -753,6 +754,29 @@ Converts one measurement unit into another and formats the unit based on the spe i18n.Util.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); ``` +### getDateOrder9+ + +static getDateOrder(locale: string): string + +Obtains the sequence of the year, month, and day in the specified locale. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ---------------------------------------- | +| locale | string | Yes | Locale used for formatting, for example, **zh-Hans-CN**. | + +**Return value** +| Type | Description | +| ------ | ----------------------- | +| string | Sequence of the year, month, and day.| + +**Example** + ``` + i18n.Util.getDateOrder("zh-CN"); + ``` + ## getInstance8+ @@ -1487,10 +1511,10 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. ``` -## TimeZone8+ +## TimeZone -### getID8+ +### getID getID(): string @@ -1510,7 +1534,7 @@ Obtains the ID of the specified **TimeZone** object. ``` -### getDisplayName8+ +### getDisplayName getDisplayName(locale?: string, isDST?: boolean): string @@ -1536,7 +1560,7 @@ Obtains the representation of a **TimeZone** object in the specified locale. ``` -### getRawOffset8+ +### getRawOffset getRawOffset(): number @@ -1556,7 +1580,7 @@ Obtains the offset between the time zone represented by a **TimeZone** object an ``` -### getOffset8+ +### getOffset getOffset(date?: number): number @@ -1706,3 +1730,73 @@ Checks whether the local digit switch is turned on. ``` var status = i18n.getUsingLocalDigit(); ``` + +## Transliterator9+ + + +### getAvailableIDs9+ + +static getAvailableIDs(): string[] + +Obtains a list of IDs supported by the **Transliterator** object. + +**System capability**: SystemCapability.Global.I18n + +**Return value** +| Type | Description | +| ------ | ------------ | +| string[] | List of IDs supported by the **Transliterator** object.| + +**Example** + ``` + i18n.Transliterator.getAvailableIDs(); + ``` + + +### getInstance9+ + +static getInstance(id: string): Transliterator + +Creates a **Transliterator** object. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------- | +| id | string | Yes | ID supported by the **Transliterator** object. | + +**Return value** +| Type | Description | +| ------ | ------------- | +| [Transliterator](#transliterator9) | **Transliterator** object.| + +**Example** + ``` + var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + ``` + + +### transform9+ + +transform(text: string): string + +Converts the input string from the source format to the target format. + +**System capability**: SystemCapability.Global.I18n + +**Parameters** +| Name | Type | Mandatory | Description | +| ------ | ------- | ---- | -------------------- | +| text | string | Yes | Input string. | + +**Return value** +| Type | Description | +| ------ | ------------- | +| string | Target string.| + +**Example** + ``` + var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + transliterator.transform ("China"); + ``` diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 13701cecf67e947c876789d0f1f4acde7f62a601..efd8277b83ac1cbe39a19ebad0fbf49cdf020190 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -16,22 +16,23 @@ import image from '@ohos.multimedia.image'; createPixelMap(colors: ArrayBuffer, options: InitializationOptions): Promise\ -Creates a **PixelMap** object. This API uses a promise to return the result. +Creates a **PixelMap** object with the default BGRA_8888 format and pixel properties specified. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Image.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | +| colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| **Return value** -| Type | Description | -| -------------------------------- | -------------- | -| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.| +| Type | Description | +| -------------------------------- | ----------------------------------------------------------------------- | +| Promise\<[PixelMap](#pixelmap7)> | Promise used to return the **PixelMap** object.
If the size of the created pixel map exceeds that of the original image, the pixel map size of the original image is returned.| + **Example** @@ -48,7 +49,7 @@ image.createPixelMap(color, opts) createPixelMap(colors: ArrayBuffer, options: InitializationOptions, callback: AsyncCallback\): void -Creates a **PixelMap** object. This API uses an asynchronous callback to return the result. +Creates a **PixelMap** object with the default BGRA_8888 format and pixel properties specified. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Image.Core @@ -91,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. +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. **System capability**: SystemCapability.Multimedia.Image.Core @@ -122,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. +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. **System capability**: SystemCapability.Multimedia.Image.Core @@ -1008,7 +1009,7 @@ const imageSourceApi = image.createImageSource(fd); createImageSource(buf: ArrayBuffer): ImageSource -Creates an **ImageSource** instance based on the buffer. +Creates an **ImageSource** instance based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1029,7 +1030,7 @@ const imageSourceApi = image.createImageSource(buf); createImageSource(buf: ArrayBuffer, options: SourceOptions): ImageSource -Creates an **ImageSource** instance based on the buffer. +Creates an **ImageSource** instance based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1057,7 +1058,7 @@ const imageSourceApi = image.createImageSource(data); CreateIncrementalSource(buf: ArrayBuffer): ImageSource -Creates an **ImageSource** instance in incremental mode based on the buffer. +Creates an **ImageSource** instance in incremental mode based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -1084,7 +1085,7 @@ const imageSourceApi = image.CreateIncrementalSource(buf); CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource -Creates an **ImageSource** instance in incremental mode based on the buffer. +Creates an **ImageSource** instance in incremental mode based on the buffers. **System capability**: SystemCapability.Multimedia.Image.ImageSource @@ -2246,7 +2247,7 @@ Describes image properties. ## PropertyKey7+ -Describes the exchangeable image file format (Exif) information of an image. +Describes the exchangeable image file format (EXIF) information of an image. **System capability**: SystemCapability.Multimedia.Image.Core @@ -2322,7 +2323,7 @@ Enumerates the response codes returned upon build errors. | ERR_IMAGE_CROP | 62980109 | An error occurs during image cropping. | | ERR_IMAGE_SOURCE_DATA | 62980110 | The image source data is incorrect. | | ERR_IMAGE_SOURCE_DATA_INCOMPLETE | 62980111 | The image source data is incomplete. | -| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image format does not match. | +| ERR_IMAGE_MISMATCHED_FORMAT | 62980112 | The image formats do not match. | | ERR_IMAGE_UNKNOWN_FORMAT | 62980113 | Unknown image format. | | ERR_IMAGE_SOURCE_UNRESOLVED | 62980114 | The image source is not parsed. | | ERR_IMAGE_INVALID_PARAMETER | 62980115 | Invalid image parameter. | @@ -2338,4 +2339,4 @@ Enumerates the response codes returned upon build errors. | ERR_IMAGE_READ_PIXELMAP_FAILED | 62980246 | Failed to read the pixel map. | | ERR_IMAGE_WRITE_PIXELMAP_FAILED | 62980247 | Failed to write the pixel map. | | ERR_IMAGE_PIXELMAP_NOT_ALLOW_MODIFY | 62980248 | Modification to the pixel map is not allowed. | -| ERR_IMAGE_CONFIG_FAILED | 62980259 | The software parameter setting is incorrect. | +| ERR_IMAGE_CONFIG_FAILED | 62980259 | The configuration is incorrect. | diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index dbb47a0d3ad9ee20ee500bc1d51d61ff380f63a5..c7662424d0b5bbde7888fe9dd696b177f532dcd5 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -2,7 +2,7 @@ The Input Consumer module implements listening for key events. -> **NOTE**
+> **NOTE** > > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index 0b7fc7a4e6e20b0cbd760c85d4ac3ee120b6a6cf..fa10d1c9b41f587ecfa8a86ff60e1abc24473fbc 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,6 +1,8 @@ # Input Method Framework -> **NOTE** +The **inputMethod** module provides an input method framework, which can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. + +> **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. @@ -8,14 +10,14 @@ ## Modules to Import ``` -import inputMethod from '@ohos.inputMethod'; +import inputMethod from '@ohos.inputmethod'; ``` ## inputMethod8+ Provides the constants. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -26,7 +28,7 @@ Provides the constants. Describes the input method application attributes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -37,15 +39,15 @@ Describes the input method application attributes. getInputMethodController(): InputMethodController -Obtains an [InputMethodController](#InputMethodController) instance. +Obtains an **[InputMethodController](#inputmethodcontroller)** instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type| Description| -| -------- | -------- | -| [InputMethodController](#InputMethodController) | Returns the current **InputMethodController** instance.| +| Type | Description | +| ----------------------------------------- | ---------------------------- | +| [InputMethodController](#inputmethodcontroller) | Returns the current **InputMethodController** instance.| **Example** @@ -57,25 +59,74 @@ Obtains an [InputMethodController](#InputMethodController) instance. getInputMethodSetting(): InputMethodSetting -Obtains an [InputMethodSetting](#InputMethodSetting) instance. +Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type | Description | | ----------------------------------------- | ---------------------------- | -| [InputMethodSetting](#InputMethodSetting) | Returns the current **InputMethodSetting** instance.| +| [InputMethodSetting](#inputmethodsetting8) | Returns the current **InputMethodSetting** instance.| + **Example** ```js var InputMethodSetting = inputMethod.getInputMethodSetting(); ``` +## inputMethod.switchInputMethod9+ + +switchInputMethod(target: InputmethodProperty, callback: AsyncCallback<boolean>): void; + +Switches to another input method. This API uses an asynchronous callback to return the result. This API can be used only in the stage model. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|target | [InputmethodProperty](#inputmethodproperty8) | Yes| Input method to switch to.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the execution result. | + + +**Example** + +```js + inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => { + prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200}); + }); +``` +## inputMethod.switchInputMethod9+ +switchInputMethod(target: InputmethodProperty): Promise<boolean> + +Switches to another input method. This API uses a promise to return the result. This API can be used only in the stage model. +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|target | [InputmethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| + +**Return value** +| Type | Description | +| ----------------------------------------- | ---------------------------- | +| Promise\ | Promise used to return the execution result. | + +**Example** + + +```js + inputMethod.switchInputMethod({packageName:"com.ohos.inputApp", methodId:"InputDemoService"}).then(res => { + prompt.showToast({message:"Input method switched." + this.imeList[this.flag].packageName, duration: 200}); + }); +``` ## InputMethodController -In the following API examples, you must first use [getInputMethodController](#getInputMethodController) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[getInputMethodController](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. ### stopInput @@ -83,7 +134,7 @@ stopInput(callback: AsyncCallback<boolean>): void Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -105,13 +156,13 @@ stopInput(): Promise<boolean> Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return whether the keyboard is successfully hidden.| +| Promise<boolean> | Promise used to return whether the keyboard is successfully hidden. | **Example** @@ -123,7 +174,7 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ## InputMethodSetting8+ -In the following API examples, you must first use [getInputMethodSetting](#getInputMethodSetting) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[getInputMethodSetting](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. ### listInputMethod @@ -131,13 +182,12 @@ listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>) Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** - | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | ---------------------- | -| callback | Array<[InputMethodProperty](#InputMethodProperty)> | Yes | Callback used to return the list of installed input methods.| +| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return the list of installed input methods.| **Example** @@ -156,13 +206,12 @@ listInputMethod(): Array<InputMethodProperty> Obtains the list of installed input methods. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** - | Type | Description | | ----------------------------------------------------------- | ---------------------- | -| Promise> | Promise used to return the list of installed input methods.| +| Promise> | Promise used to return the list of installed input methods. | **Example** @@ -180,15 +229,16 @@ displayOptionalInputMethod(callback: AsyncCallback<void>): void Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| **Example** + ```js InputMethodSetting.displayOptionalInputMethod(()=>{ console.info('displayOptionalInputMethod is called'); @@ -197,20 +247,20 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono ### displayOptionalInputMethod - displayOptionalInputMethod(): Promise<void> +displayOptionalInputMethod(): Promise<void> Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise used to return the execution result. | **Example** ```js InputMethodSetting.displayOptionalInputMethod(); -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 60c6c8a4ce2d0caad26c838e6353cdc21bcbc785..55e702cd0501af092bbc7e0420f410ff81ed90c6 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1,19 +1,22 @@ # Input Method Engine -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **inputMethodEngine** module streamlines the interaction between applications and input methods. By calling APIs of this module, applications can accept text input through the input methods, be bound to input method services, request the keyboard to display or hide, listen for the input method status, and much more. + +> **NOTE** > +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ``` -import inputMethodEngine from '@ohos.inputMethodEngine'; +import inputMethodEngine from '@ohos.inputmethodengine'; ``` ## inputMethodEngine -Defines constant values. +Provides the constants. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | @@ -50,7 +53,7 @@ getInputMethodEngine(): InputMethodEngine Obtains an **InputMethodEngine** instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -60,9 +63,9 @@ Obtains an **InputMethodEngine** instance. **Example** -```js -var InputMethodEngine = inputMethodEngine.getInputMethodEngine(); -``` + ```js + var InputMethodEngine = inputMethodEngine.getInputMethodEngine(); + ``` ## inputMethodEngine.createKeyboardDelegate @@ -70,7 +73,7 @@ createKeyboardDelegate(): KeyboardDelegate Obtains a **KeyboardDelegate** instance. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -80,9 +83,9 @@ Obtains a **KeyboardDelegate** instance. **Example** -```js -var KeyboardDelegate = inputMethodEngine.createKeyboardDelegate(); -``` + ```js + var KeyboardDelegate = inputMethodEngine.createKeyboardDelegate(); + ``` ## InputMethodEngine @@ -94,7 +97,7 @@ on(type: 'inputStart', callback: (kbController: KeyboardController, textInputCli Listens for the input method binding event. This API uses a callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -105,12 +108,12 @@ Listens for the input method binding event. This API uses a callback to return t **Example** -```js -InputMethodEngine.on('inputStart', (kbController, textInputClient) => { - KeyboardController = kbController; - TextInputClient = textInputClient; -}); -``` + ```js + InputMethodEngine.on('inputStart', (kbController, textInputClient) => { + KeyboardController = kbController; + TextInputClient = textInputClient; + }); + ``` ### off('inputStart') @@ -118,7 +121,7 @@ off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputC Cancels listening for the input method binding event. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -127,11 +130,13 @@ Cancels listening for the input method binding event. | type | string | Yes | Listening type.
Set it to **'inputStart'**, which indicates listening for the input method binding event.| | callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | No| Callback used to return the result.| + + **Example** -```js -InputMethodEngine.off('inputStart'); -``` + ```js + InputMethodEngine.off('inputStart'); + ``` ### on('keyboardShow'|'keyboardHide') @@ -139,22 +144,22 @@ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void Listens for an input method event. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| +| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| | callback | void | No | Callback used to return the result. | **Example** -```js -InputMethodEngine.on('keyboardShow', (err) => { - console.info('keyboardShow'); -}); -``` + ```js + InputMethodEngine.on('keyboardShow', (err) => { + console.info('keyboardShow'); + }); + ``` ### off('keyboardShow'|'keyboardHide') @@ -162,20 +167,21 @@ off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void Cancels listening for an input method event. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| +| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| | callback | void | No | Callback used to return the result. | **Example** -```js -InputMethodEngine.off('keyboardShow'); -``` + ```js + InputMethodEngine.off('keyboardShow'); + ``` + ## KeyboardDelegate @@ -187,22 +193,24 @@ on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void Listens for a hard keyboard even. This API uses a callback to return the key information. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| +| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| | callback | [KeyEvent](#KeyEvent) | Yes| Callback used to return the key information.| + + **Example** -```js -KeyboardDelegate.on('keyDown', (event) => { - console.info('keyDown'); -}); -``` + ```js + KeyboardDelegate.on('keyDown', (event) => { + console.info('keyDown'); + }); + ``` ### off('keyDown'|'keyUp') @@ -210,20 +218,20 @@ off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void Cancels listening for a hard keyboard even. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| +| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| | callback | [KeyEvent](#KeyEvent) | No | Callback used to return the key information. | **Example** -```js -KeyboardDelegate.off('keyDown'); -``` + ```js + KeyboardDelegate.off('keyDown'); + ``` ### on('cursorContextChange') @@ -231,21 +239,25 @@ on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) = Listens for cursor context changes. This API uses a callback to return the cursor information. -**System capability**: SystemCapability.Miscservices.InputMethodFramework + **System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| | callback | number | Yes | Callback used to return the cursor information. | -**Example** + + + **Example** ```js + KeyboardDelegate.on('cursorContextChange', (x, y, height) => { console.info('cursorContextChange'); }); + ``` ### off('cursorContextChange') @@ -254,42 +266,46 @@ off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) Cancels listening for cursor context changes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| -| callback | number | No| Callback used to return the cursor information.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| +| callback | number | No | Callback used to return the cursor information. | -**Example** + + **Example** ```js + KeyboardDelegate.off('cursorContextChange'); -``` +``` ### on('selectionChange') on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void Listens for text selection changes. This API uses a callback to return the text selection information. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | | type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| | callback | number | Yes | Callback used to return the text selection information. | -**Example** + **Example** ```js + KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { console.info('selectionChange'); }); + ``` ### off('selectionChange') @@ -298,19 +314,21 @@ off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBe Cancels listening for text selection changes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| -| callback | number | No| Callback used to return the text selection information.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| +| callback | number | No | Callback used to return the text selection information. | -**Example** + **Example** ```js + KeyboardDelegate.off('selectionChange'); + ``` @@ -320,21 +338,23 @@ on(type: 'textChange', callback: (text: string) => void): void Listens for text changes. This API uses a callback to return the current text content. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| -| callback | string | Yes| Callback used to return the current text content.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| +| callback | string | Yes | Callback used to return the current text content. | -**Example** + **Example** ```js + KeyboardDelegate.on('textChange', (text) => { console.info('textChange'); }); + ``` ### off('textChange') @@ -343,16 +363,16 @@ off(type: 'textChange', callback?: (text: string) => void): void Cancels listening for text changes. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| -| callback | string | No| Callback used to return the current text content.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| +| callback | string | No | Callback used to return the current text content. | -**Example** + **Example** ```js KeyboardDelegate.off('textChange'); @@ -368,7 +388,7 @@ hideKeyboard(callback: AsyncCallback<void>): void Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -388,19 +408,18 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. hideKeyboard(): Promise<void> -Hides the keyboard. This API uses a promise to return the result. +Hides the keyboard. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description: | +| Type | Description | | ---------------- | -------- | | Promise<void> | Promise used to return the result.| **Example** - ```js KeyboardController.hideKeyboard(); ``` @@ -415,30 +434,30 @@ getForward(length:number, callback: AsyncCallback<string>): void Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | length | number | Yes| Text length.| -| callback | AsyncCallback<string> | Yes| Text returned.| +| callback | AsyncCallback<string> | Yes| Callback used to return the text.| **Example** -```js - TextInputClient.getForward(5,(text) =>{ - console.info("text = " + text); - }); -``` + ```js + TextInputClient.getForward(5,(text) =>{ + console.info("text = " + text); + }); + ``` ### getForward getForward(length:number): Promise<string> -Obtains the specific-length text before the cursor. This API uses a promise to return the result. +Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -450,14 +469,14 @@ Obtains the specific-length text before the cursor. This API uses a promise to r | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<string> | Text returned. | +| Promise<string> | Promise used to return the text. | **Example** -```js - var text = TextInputClient.getForward(5); - console.info("text = " + text); -``` + ```js + var text = TextInputClient.getForward(5); + console.info("text = " + text); + ``` ### getBackward @@ -465,30 +484,30 @@ getBackward(length:number, callback: AsyncCallback<string>): void Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | length | number | Yes| Text length.| -| callback | AsyncCallback<string> | Yes| Text returned.| +| callback | AsyncCallback<string> | Yes| Callback used to return the text.| **Example** -```js - TextInputClient.getBackward(5,(text)=>{ - console.info("text = " + text); -}); -``` + ```js + TextInputClient.getBackward(5,(text)=>{ + console.info("text = " + text); + }); + ``` ### getBackward getBackward(length:number): Promise<string> -Obtains the specific-length text after the cursor. This API uses a promise to return the result. +Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -500,14 +519,14 @@ Obtains the specific-length text after the cursor. This API uses a promise to re | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<string> | Text returned. | +| Promise<string> | Promise used to return the text. | **Example** -```js - var text = TextInputClient.getBackward(5); - console.info("text = " + text); -``` + ```js + var text = TextInputClient.getBackward(5); + console.info("text = " + text); + ``` ### deleteForward @@ -515,47 +534,46 @@ deleteForward(length:number, callback: AsyncCallback<boolean>): void Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | length | number | Yes| Text length.| -| callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** -```js -TextInputClient.deleteForward(5,(isSuccess)=>{ - console.info("isSuccess = " + isSuccess); -}); -``` - + ```js + TextInputClient.deleteForward(5,(isSuccess)=>{ + console.info("isSuccess = " + isSuccess); + }); + ``` ### deleteForward deleteForward(length:number): Promise<boolean> -Deletes the fixed-length text before the cursor. This API uses a promise to return the result. +Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| length | number | Yes| Text length.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| length | number | Yes | Text length.| **Return value** -| Type | Description | -| ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Returns whether the operation is successful. | +| Type | Description | +| ---------------------- | -------------- | +| Promise<boolean> | Promise used to return the result.| **Example** ```js - var isSuccess = TextInputClient.deleteForward(5); +var isSuccess = TextInputClient.deleteForward(5); console.info("isSuccess = " + isSuccess); ``` @@ -565,33 +583,34 @@ deleteBackward(length:number, callback: AsyncCallback<boolean>): void Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| length | number | Yes| Text length.| -| callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | -------------- | +| length | number | Yes | Text length. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| -**Example** + **Example** ```js + TextInputClient.deleteBackward(5, (isSuccess)=>{ console.info("isSuccess = " + isSuccess); }); + ``` ### deleteBackward deleteBackward(length:number): Promise<boolean> -Deletes the fixed-length text after the cursor. This API uses a promise to return the result. +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** - | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | length | number | Yes| Text length.| @@ -600,45 +619,48 @@ Deletes the fixed-length text after the cursor. This API uses a promise to retur | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Returns whether the operation is successful. | +| Promise<boolean> | Promise used to return the result. | **Example** ```js -var isSuccess = TextInputClient.deleteBackward(5); -console.info("isSuccess = " + isSuccess); -``` + var isSuccess = TextInputClient.deleteBackward(5); + console.info("isSuccess = " + isSuccess); + +``` ### sendKeyFunction sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | action | number | Yes| Edit box attribute.| -| callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| -**Example** + **Example** ```js + TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT,(isSuccess)=>{ console.info("isSuccess = " + isSuccess); }); + ``` ### sendKeyFunction sendKeyFunction(action:number): Promise<boolean> -Sets the Enter key to send the text to its target. This API uses a promise to return the result. +Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -650,14 +672,14 @@ Sets the Enter key to send the text to its target. This API uses a promise to re | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Returns whether the operation is successful. | +| Promise<boolean> | Promise used to return the result. | **Example** -```js -var isSuccess = TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT); -console.info("isSuccess = " + isSuccess); -``` + ```js + var isSuccess = TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT); + console.info("isSuccess = " + isSuccess); + ``` ### insertText @@ -665,30 +687,32 @@ insertText(text:string, callback: AsyncCallback<boolean>): void Inserts text. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | text | string | Yes| Text to insert.| -| callback | AsyncCallback<boolean> | Yes| Returns whether the operation is successful.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** ```js + TextInputClient.insertText("test", (isSuccess)=>{ console.info("isSuccess = " + isSuccess); }); + ``` ### insertText insertText(text:string): Promise<boolean> -Inserts text. This API uses a promise to return the result. +Inserts text. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -696,18 +720,18 @@ Inserts text. This API uses a promise to return the result. | -------- | -------- | -------- | -------- | | text | string | Yes| Text to insert.| -**Return value** +**Return value** | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Returns whether the operation is successful. | +| Promise<boolean> | Promise used to return the result. | **Example** -```js -var isSuccess = TextInputClient.insertText("test"); -console.info("isSuccess = " + isSuccess); -``` + ```js + var isSuccess = TextInputClient.insertText("test"); + console.info("isSuccess = " + isSuccess); + ``` ### getEditorAttribute @@ -715,7 +739,7 @@ getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** @@ -725,36 +749,36 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to **Example** -```js - TextInputClient.getEditorAttribute((EditorAttribute)=>{ - }); -``` + ```js + TextInputClient.getEditorAttribute((EditorAttribute)=>{ + }); + ``` ### getEditorAttribute getEditorAttribute(): EditorAttribute -Obtains the attribute of the edit box. This API uses a promise to return the result. +Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<[EditorAttribute](#EditorAttribute)> | Returns the attribute of the edit box. | +| Promise<[EditorAttribute](#EditorAttribute)> | Promise used to return the attribute of the edit box. | **Example** -```js -var EditorAttribute = TextInputClient.getEditorAttribute(); -``` + ```js + var EditorAttribute = TextInputClient.getEditorAttribute(); + ``` ## EditorAttribute Describes the attribute of the edit box. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name | Type| Readable| Writable| Description | | ------------ | -------- | ---- | ---- | ------------------ | @@ -765,7 +789,7 @@ Describes the attribute of the edit box. Describes the attribute of a key. -**System capability**: SystemCapability.Miscservices.InputMethodFramework +**System capability**: SystemCapability.MiscServices.InputMethodFramework | Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------ | diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index 9a1c1712577e7d34c841ba19fc47376166ad231c..3a711c0ea13132547c4fc2bb9cc76066f71ab0ee 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -203,7 +203,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode' | KEYCODE_CLOSE | number | Yes| No| Close key| | KEYCODE_PLAY | number | Yes| No| Play key| | KEYCODE_BASSBOOST | number | Yes| No| Bass Boost key| -| KEYCODE_PRINT | number | Yes| No| Print key| +| KEYCODE_PRINT | number | Yes| No| Print key| | KEYCODE_CHAT | number | Yes| No| Chat key| | KEYCODE_FINANCE | number | Yes| No| Finance key| | KEYCODE_CANCEL | number | Yes| No| Cancel key| @@ -302,7 +302,7 @@ import {KeyCode} from '@ohos.multimodalInput.keyCode' | KEYCODE_SCREENLOCK | number | Yes| No| Screen Lock key| | KEYCODE_DIRECTION_ROTATE_DISPLAY | number | Yes| No| Directional Rotation Display key| | KEYCODE_CYCLEWINDOWS | number | Yes| No| Windows Cycle key| -| KEYCODE_COMPUTER | number | Yes| No| Computer key| +| KEYCODE_COMPUTER | number | Yes| No| Key | | KEYCODE_EJECTCLOSECD | number | Yes| No| Eject CD key| | KEYCODE_ISO | number | Yes| No| ISO key| | KEYCODE_MOVE | number | Yes| No| Move key| diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 77002020139fbdb2aada0cb1141a0f2840a9f250..dff8251fcc345a2e8fb24b4fcafee582357951b0 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -106,6 +106,7 @@ media.createVideoPlayer().then((video) => { createAudioRecorder(): AudioRecorder Creates an **AudioRecorder** instance to control audio recording. +Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder @@ -126,6 +127,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. +Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -155,6 +157,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. +Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -272,14 +275,15 @@ For details about the audio playback demo, see [Audio Playback Development](../. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer -| Name | Type | Readable| Writable| Description | -| ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio media URI. The mainstream audio formats (MPEG-4, AAC, MPEG-3, OGG, and WAV) are supported.
**Example of supported URIs**:
1. FD playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HTTPS network playback: https://xx
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| -| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | -| currentTime | number | Yes | No | Current audio playback position. | -| duration | number | Yes | No | Audio duration. | -| state | [AudioState](#audiostate) | Yes | No | Audio playback state. | - +| 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| +| 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. | +| 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()**.| ### play play(): void @@ -501,7 +505,7 @@ Subscribes to the audio buffering update event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'bufferingUpdate' in this case. | +| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | | callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** @@ -590,7 +594,7 @@ audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' e on(type: 'timeUpdate', callback: Callback\): void -Subscribes to the 'timeUpdate' event. +Subscribes to the **'timeUpdate'** event. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -598,7 +602,7 @@ 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.| +| 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. | **Example** @@ -618,7 +622,7 @@ audioPlayer.seek(30000); // Seek to 30000 ms. on(type: 'error', callback: ErrorCallback): void -Subscribes to the audio playback error event. +Subscribes to audio playback error events. After an error event is reported, you must handle the event and exit the playback. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -626,13 +630,13 @@ Subscribes to the audio playback error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during audio playback.| +| type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during audio playback. | | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** ```js -audioPlayer.on('error', (error) => { // Set the error event callback. +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. @@ -646,13 +650,38 @@ Enumerates the audio playback states. You can obtain the state through the **sta **System capability**: SystemCapability.Multimedia.Media.AudioPlayer -| Name | Type | Description | -| ------------------ | ------ | -------------- | -| idle | string | The audio player is idle.| -| playing | string | Audio playback is in progress.| -| paused | string | Audio playback is paused.| -| stopped | string | Audio playback is stopped.| -| 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. | +| error8+ | 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** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| fd | number | Yes | Resource handle, which is obtained by calling **resourceManager.getRawFileDescriptor**. | +| 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+ @@ -666,13 +695,16 @@ 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 playback: fd://xx
![](figures/en-us_image_url.png)
2. HTTP network playback: http://xx
3. HTTPS network playback: https://xx
3. HLS network playback: http://xx or https://xx
**Note**:
To use media materials, you must declare the read permission. Otherwise, the media materials cannot be played properly.| +| 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| | loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | -| currentTime8+ | number | Yes | No | Current video playback position. | -| duration8+ | number | Yes | No | Video duration. The value **-1** indicates the live streaming mode. | +| videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | +| audioInterruptMode9+ | [InterruptMode](#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. | -| width8+ | number | Yes | No | Video width. | -| height8+ | number | Yes | No | Video height. | +| width8+ | number | Yes | No | Video width, in pixels. | +| height8+ | number | Yes | No | Video height, in pixels. | ### setDisplaySurface8+ @@ -1334,7 +1366,7 @@ videoPlayer.setSpeed(speed).then() => { selectBitrate(bitrate:number, callback: AsyncCallback\): void -Selects a bit rate from available bit rates. This API uses a callback to return the result. The available bit rates can be obtained by calling [availableBitrateCollected](#on('availableBitrateCollected')9+). +Selects a bit rate from available ones, which can be obtained by calling [availableBitratesCollect](#onavailablebitratescollect9). This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1362,7 +1394,7 @@ videoPlayer.selectBitrate(bitrate, (err, result) => { selectBitrate(bitrate:number): Promise\ -Selects a bit rate from available bit rates. This API uses a promise to return the result. The available bit rates can be obtained by calling [availableBitrateCollected](#on('availableBitrateCollected')9+). +Selects a bit rate from available ones, which can be obtained by calling [availableBitratesCollect](#onavailablebitratescollect9). This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1401,7 +1433,7 @@ Subscribes to the video playback completion event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ----------------------------------------------------------- | -| type | string | Yes | Event type, which is 'playbackCompleted' in this case.| +| type | string | Yes | Event type, which is **'playbackCompleted'** in this case. | | callback | function | Yes | Callback invoked when the event is triggered. | **Example** @@ -1424,7 +1456,7 @@ Subscribes to the video buffering update event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'bufferingUpdate' in this case. | +| type | string | Yes | Event type, which is **'bufferingUpdate'** in this case. | | callback | function | Yes | Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** @@ -1448,7 +1480,7 @@ Subscribes to the frame rendering start event. | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'startRenderFrame' in this case.| +| type | string | Yes | Event type, which is **'startRenderFrame'** in this case. | | callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** @@ -1471,7 +1503,7 @@ Subscribes to the video width and height change event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'videoSizeChanged' in this case.| +| type | string | Yes | Event type, which is **'videoSizeChanged'** in this case. | | callback | function | Yes | Callback invoked when the event is triggered. **width** indicates the video width, and **height** indicates the video height. | **Example** @@ -1487,7 +1519,7 @@ videoPlayer.on('videoSizeChanged', (width, height) => { on(type: 'error', callback: ErrorCallback): void -Subscribes to the video playback error event. +Subscribes to video playback error events. After an error event is reported, you must handle the event and exit the playback. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1495,7 +1527,7 @@ Subscribes to the video playback error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during video playback.| +| type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during video playback. | | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** @@ -1506,12 +1538,12 @@ videoPlayer.on('error', (error) => { // Set the 'error' event callback. 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. }); -videoPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. +videoPlayer.url = 'fd://error'; // Set an incorrect URL to trigger the 'error' event. ``` -### on('availableBitrateCollected')9+ +### on('availableBitratesCollect')9+ -on(type: 'availableBitrateCollected', callback: (bitrates: Array) => void): void +on(type: 'availableBitratesCollect', callback: (bitrates: Array\) => void): void Subscribes to the video playback bit rate reporting event. @@ -1521,15 +1553,15 @@ Subscribes to the video playback bit rate reporting event. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'availableBitrateCollected' in this case. This event is reported only once when the playback starts.| -| callback | function | Yes | Callback used to return supported bit rates, in an array. | +| type | string | Yes | Event type, which is **'availableBitratesCollect'** in this case. This event is reported only once when the playback starts.| +| callback | function | Yes | Callback used to return supported bit rates, in an array. | **Example** ```js -videoPlayer.on('availableBitrateCollected', (bitrates) => { +videoPlayer.on('availableBitratesCollect', (bitrates) => { for (let i = 0; i < bitrates.length; i++) { - console.info('case availableBitrateCollected bitrates: ' + bitrates[i]); // Print bit rates. + console.info('case availableBitratesCollect bitrates: ' + bitrates[i]); // Print bit rates. } }); ``` @@ -1574,6 +1606,17 @@ Enumerates the video playback speeds, which can be passed in the **setSpeed** AP | SPEED_FORWARD_1_75_X | 3 | Plays the video at 1.75 times the normal speed.| | SPEED_FORWARD_2_00_X | 4 | Plays the video at 2.00 times the normal speed.| +## VideoScaleType9+ + +Enumerates the video scale modes. + +**System capability**: SystemCapability.Multimedia.Media.VideoPlayer + +| Name | Default Value| Description | +| ---------------------------- | ------ | ---------- | +| VIDEO_SCALE_TYPE_FIT | 0 | The video will be stretched to fit the window.| +| VIDEO_SCALE_TYPE_FIT_CROP| 1 | The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped. | + ## MediaDescription8+ ### [key : string] : Object @@ -1765,7 +1808,7 @@ Subscribes to the audio recording events. | Name | Type | Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The following events are supported: 'prepare'\|'start'\| 'pause' \| 'resume' \|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when the [prepare](#audiorecorder_prepare) API is called and the audio recording parameters are set.
- The 'start' event is triggered when the [start](#audiorecorder_start) API is called and audio recording starts.
- The 'pause' event is triggered when the [pause](#audiorecorder_pause) API is called and audio recording is paused.
- The 'resume' event is triggered when the [resume](#audiorecorder_resume) API is called and audio recording is resumed.
- The 'stop' event is triggered when the [stop](#audiorecorder_stop) API is called and audio recording stops.
- The 'release' event is triggered when the [release](#audiorecorder_release) API is called and the recording resource is released.
- The 'reset' event is 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** @@ -1781,41 +1824,41 @@ let audioRecorderConfig = { 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. +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}`); }); -audioRecorder.on('prepare', () => { // Set the prepare event callback. +audioRecorder.on('prepare', () => { // Set the 'prepare' event callback. console.log('prepare success'); - audioRecorder.start(); // Start recording and trigger the start event callback. + audioRecorder.start(); // Start recording and trigger the 'start' event callback. }); -audioRecorder.on('start', () => { // Set the start event callback. +audioRecorder.on('start', () => { // Set the 'start' event callback. console.log('audio recorder start success'); }); -audioRecorder.on('pause', () => { // Set the pause event callback. +audioRecorder.on('pause', () => { // Set the 'pause' event callback. console.log('audio recorder pause success'); }); -audioRecorder.on('resume', () => { // Set the resume event callback. +audioRecorder.on('resume', () => { // Set the 'resume' event callback. console.log('audio recorder resume success'); }); -audioRecorder.on('stop', () => { // Set the stop event callback. +audioRecorder.on('stop', () => { // Set the 'stop' event callback. console.log('audio recorder stop success'); }); -audioRecorder.on('release', () => { // Set the release event callback. +audioRecorder.on('release', () => { // Set the 'release' event callback. console.log('audio recorder release success'); }); -audioRecorder.on('reset', () => { // Set the reset event callback. +audioRecorder.on('reset', () => { // Set the 'reset' event callback. console.log('audio recorder reset success'); }); -audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the prepare event callback. +audioRecorder.prepare(audioRecorderConfig) // Set recording parameters and trigger the 'prepare' event callback. ``` ### on('error') on(type: 'error', callback: ErrorCallback): void -Subscribes to the audio recording error event. +Subscribes to audio recording error events. After an error event is reported, you must handle the event and exit the recording. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder @@ -1823,18 +1866,18 @@ Subscribes to the audio recording error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during audio recording.| +| type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during audio recording. | | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** ```js -audioRecorder.on('error', (error) => { // Set the error event callback. +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. }); -audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the error event callback. +audioRecorder.prepare(); // Do no set any parameter in prepare and trigger the 'error' event callback. ``` ## AudioRecorderConfig @@ -1978,7 +2021,7 @@ prepare(config: VideoRecorderConfig): Promise\; Sets video recording parameters in asynchronous mode. This API uses a promise to return the result. -**Required permissions:** ohos.permission.MICROPHONE and ohos.permission.CAMERA +**Required permissions:** ohos.permission.MICROPHONE **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2109,7 +2152,7 @@ start(callback: AsyncCallback\): void; Starts video recording in asynchronous mode. This API uses a callback to return the result. -This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. +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. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2138,7 +2181,7 @@ start(): Promise\; Starts video recording in asynchronous mode. This API uses a promise to return the result. -This API can be called only after [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) are called, because the data source must pass data to the surface first. +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. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2273,7 +2316,7 @@ stop(callback: AsyncCallback\): void; Stops video recording in asynchronous mode. This API uses a callback to return the result. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2302,7 +2345,7 @@ stop(): Promise\; Stops video recording in asynchronous mode. This API uses a promise to return the result. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2381,7 +2424,7 @@ reset(callback: AsyncCallback\): void; Resets video recording in asynchronous mode. This API uses a callback to return the result. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2410,7 +2453,7 @@ reset(): Promise\; Resets video recording in asynchronous mode. This API uses a promise to return the result. -To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface8) again. +To start another recording, you must call [prepare()](#videorecorder_prepare1) and [getInputSurface()](#getinputsurface9) again. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2435,7 +2478,7 @@ videoRecorder.reset().then(() => { on(type: 'error', callback: ErrorCallback): void -Subscribes to the video recording error event. +Subscribes to video recording error events. After an error event is reported, you must handle the event and exit the recording. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder @@ -2443,13 +2486,13 @@ Subscribes to the video recording error event. | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type, which is 'error' in this case.
The 'error' event is triggered when an error occurs during video recording.| +| type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during video recording. | | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | **Example** ```js -videoRecorder.on('error', (error) => { // Set the error event callback. +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. @@ -2485,7 +2528,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)
The file must be created by the caller and granted with proper permissions.| +| url | string | Yes | Video output URL. Supported: fd://xx (fd number)
![](figures/en-us_image_url.png)
**Required permissions**: ohos.permission.READ_MEDIA| ## AudioSourceType9+ diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index 5589051694d6aa726df14d2c87b5425f314873da..b59e88a401cebca64a2be96b29de92dd375e893d 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -2278,7 +2278,7 @@ Describes options for fetching media files. | Name | Type | Readable| Writable| Mandatory| Description | | ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | -| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| +| selections | string | Yes | Yes | Yes | Conditions for fetching files. The enumerated values in [FileKey](#filekey8) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR ' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?', | | selectionArgs | Array<string> | Yes | Yes | Yes | Value of the condition, which corresponds to the value of the condition column in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | | order | string | Yes | Yes | No | Sorting mode of the search results, which can be ascending or descending. The enumerated values in [FileKey](#filekey8) are used as the columns for sorting the search results. Example:
Ascending: order: mediaLibrary.FileKey.DATE_ADDED + " AESC"
Descending: order: mediaLibrary.FileKey.DATE_ADDED + " DESC"| | uri8+ | string | Yes | Yes | No | File URI. | diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-missionManager.md index b981d28061d45feb313dbaf7ea0709d6f198e0e8..50057062701f1ddbe0b058dc79e957c1a47e63a3 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-missionManager.md @@ -362,6 +362,88 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r }); ``` +## missionManager.getLowResolutionMissionSnapShot9+ + +getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback\): void; + +Obtains the low-resolution snapshot of a given mission. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + +**Example** + + ```js + import missionManager from '@ohos.application.missionManager' + + missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { + console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code); + console.log("bundleName = " + snapshot.ability.bundleName); + }) + }) + ``` + + +## missionManager.getLowResolutionMissionSnapShot9+ + +getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\; + +Obtains the low-resolution snapshot of a given mission. This API uses a promise to return the result. + +**Required permission**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| + +**Example** + + ```js + import missionManager from '@ohos.application.missionManager' + + var allMissions; + missionManager.getMissionInfos("",10).then(function(res){ + allMissions=res; + }).catch(function(err){console.log(err);}); + console.log("size = " + allMissions.length); + console.log("missions = " + JSON.stringify(allMissions)); + var id = allMissions[0].missionId; + + var snapshot = missionManager.getLowResolutionMissionSnapShot("", id).catch(function (err){ + console.log(err); + }); + ``` + ## missionManager.lockMission diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md new file mode 100644 index 0000000000000000000000000000000000000000..eb7d01dda3b5bcf8c88a45981d661aacf6d4e4f4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -0,0 +1,1820 @@ +# Standard NFC Tag Technologies + +The **nfctech** module provides methods 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** + +```js +import tag from '@ohos.nfc.tag'; +``` + +## NfcATag + +Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. **NfcATag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NfcATag**. + +### NfcATag.getSak + +getSak(): number + +Obtains the SAK value of this NFC-A tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | SAK value obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let sak = tag.getNfcATag(taginfo).getSak(); +console.log("sak:" +sak); +``` + +### NfcATag.getAtqa + +getAtqa(): number[] + +Obtains the ATQA value of this NFC-A tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | ATQA value obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let atqa = tag.getNfcATag(taginfo).getAtqa(); +console.log("atqa:" +atqa); +``` + +## NfcBTag + +Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. **NfcBTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NfcBTag**. + +### NfcBTag.getRespAppData + +getRespAppData(): number[] + +Obtains the application data of this NFC-B tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | Application data obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let appData = tag.getNfcBTag(taginfo).getRespAppData(); +console.log("appData:" +appData); +``` + +### NfcBTag.getRespProtocol + +getRespProtocol(): number[] + +Obtains protocol information of this NFC-B tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | Protocol information obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let protocol = tag.getNfcBTag(taginfo).getRespProtocol(); +console.log("appData:" +protocol); +``` + +## NfcFTag + +Provides access to NFC-F(JIS 6319-4) properties and I/O operations. **NfcFTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NfcFTag**. + +### NfcFTag.getSystemCode + +getSystemCode(): number[] + +Obtains the system code from the tag instance. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | System code obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let systemCode = tag.getNfcFTag(taginfo).getSystemCode(); +console.log("systemCode:" +systemCode); +``` + +### NfcFTag.getPmm + +getPmm(): number[] + +Obtains the PMm (consisting of the IC code and manufacturer parameters) information from the tag instance. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | PMm information obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let pmm = tag.getNfcFTag(taginfo).getPmm(); +console.log("pmm:" +pmm); +``` + +## NfcVTag + +Provides access to NFC-V (ISO 15693) properties and I/O operations. **NfcVTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NfcVTag**. + +### NfcvTag.getResponseFlags + +getResponseFlags(): number + +Obtains the response flags from the tag instance. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Response flags obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let flags = tag.getNfcVTag(taginfo).getResponseFlags(); +console.log("flags:" +flags); +``` + +### NfcvTag.getDsfId + +getDsfId(): number + +Obtains the data storage format identifier (DSFID) from the tag instance. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | DSFID obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let dsfId = tag.getNfcVTag(taginfo).getDsfId(); +console.log("dsfId:" +dsfId); +``` + +## IsoDepTag9+ + +Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. **IsoDepTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **IsoDepTag**. + +### IsoDepTag.getHistoricalBytes9+ + +getHistoricalBytes(): string + +Obtains the historical bytes of this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| string | Historical bytes obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let historicalBytes = tag.getIsoDepTag(taginfo).getHistoricalBytes(); +console.log("historicalBytes:" +historicalBytes); +``` + +### IsoDepTag.getHiLayerResponse9+ + +getHiLayerResponse(): string + +Obtains the HiLayer response of this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| string | HiLayer response obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let hiLayerResponse = tag.getIsoDepTag(taginfo).getHiLayerResponse(); +console.log("hiLayerResponse:" +hiLayerResponse); +``` + +### IsoDepTag.isExtendedApduSupported9+ + +isExtendedApduSupported(): Promise<boolean> + +Checks whether an extended application protocol data unit (APDU) is supported. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise<boolean> | Promise used to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.getIsoDepTag(taginfo).isExtendedApduSupported().then(function (has) { + console.log('has: ' + has) +}) +``` + +### IsoDepTag.isExtendedApduSupported9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.getIsoDepTag(taginfo).isExtendedApduSupported(function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +## NdefTag9+ + +Provides access to the tags in the NFC Data Exchange Format (NDEF). **NdefTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NdefTag**. + +### NdefTag.createNdefMessage9+ + +createNdefMessage(data: string): [NdefMessage](#ndefmessage9) + +Creates an NDEF message using raw bytes. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Raw bytes of the string type.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](#ndefmessage9) | NDEF message created.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NdefMessage = tag.NdefTag(taginfo).createNdefMessage(data); +``` + +## NdefMessage9+ + +### NdefMessage.getNdefRecords9+ + +getNdefRecords(): [NdefRecord](#ndefrecord9)[ ] + +Obtains all NDEF records. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9)[ ] | All records obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NdefRecord = tag.NdefTag(taginfo).getNdefRecords(); +``` + +## NdefRecord9+ + +| **Name**| **Type**| **Description**| +| -------- | -------- | -------- | +| tnf | number | UID of the tag.| +| [rtdType](#rtdtype9) | string | NFC Record Type Definition (RTD) supported by the tag.| +| id | string | Additional information about the tag.| +| payload | string | RF discovery ID of the tag.| + +## RtdType9+ + +| **Name**| **Type**| **Description**| +| -------- | -------- | -------- | +| RTD_TEXT | 'T' | Text information.| +| RTD_URI | 'U' | Network address, email, or phone number.| + +### NdefTag.createNdefMessage9+ + +createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) + +Creates an NDEF message using the NDEF records. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| ndefRecords | [NdefRecord](#ndefrecord9)[] | Yes| A list of NDEF records.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](#ndefmessage9) | NDEF message created.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NdefMessage = tag.NdefTag(taginfo).createNdefMessage(ndefRecords); +``` + +### NdefTag.getNdefTagType9+ + +getNdefTagType(): NfcForumType + +Obtains the type of this NDEF tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NfcForumType](#nfcforumtype9) | NDEF tag type obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NfcForumType = tag.NdefTag(taginfo).getNdefTagType(); +``` + +### NdefTag.getNdefMessage9+ + +getNdefMessage(): NdefMessage + +Obtains the NDEF message from the tag discovered. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](#ndefmessage9) | NDEF message created.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let NdefMessage = tag.NdefTag(taginfo).getNdefMessage(); +``` + +### NdefTag.isNdefWritable9+ + +isNdefWritable(): Promise<boolean> + +Checks whether the NDEF tag is writable. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise<boolean> | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).isNdefWritable().then(function (has) { + console.log(JSON.stringify(has)) +}) +``` + +### NdefTag.isNdefWritable9+ + +isNdefWritable(callback: AsyncCallback<boolean>): void; + +Checks whether the NDEF tag is writable. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).isNdefWritable(function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +### NdefTag.readNdef9+ + +readNdef(): Promise\ + +Reads the NDEF message from this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).readNdef().then(function (ndefMessage) { + console.log(JSON.stringify(ndefMessage)) +}) +``` + +### NdefTag.readNdef9+ + +readNdef(callback: AsyncCallback\<[NdefMessage](#ndefmessage9)>): void + +Reads the NDEF message from this tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).readNdef(function (error, ndefMessage) { + console.log(JSON.stringify(error)) + console.log('ndefMessage: ' + ndefMessage) +}) +``` + +### NdefTag.writeNdef9+ + +writeNdef(msg: NdefMessage): Promise\; + +Write an NDEF message to this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| msg | NdefMessage | Yes | NDEF message to write.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +NdefTag.writeNdef(msg).then(function (netHandle) { + console.log(JSON.stringify(netHandle)) +}) +``` + +### NdefTag.writeNdef9+ + +writeNdef(msg: NdefMessage, callback: AsyncCallback\): void + +Write an NDEF message to this tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| msg | NdefMessage | Yes | NDEF message to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).write(msg, function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +### NdefTag.canSetReadOnly9+ + +canSetReadOnly(): Promise\ + +Checks whether this NDEF tag can be set to read-only. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise<boolean> | Promise used to return the result. If the tag can be set to read-only, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).canSetReadOnly().then(function (has) { + console.log(JSON.stringify(has)) +}) +``` + +### NdefTag.canSetReadOnly9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag can be set to read-only, **true** is returned; otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).canSetReadOnly(function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +### NdefTag.setReadOnly9+ + +setReadOnly(): Promise\ + +Sets this NDEF tag to read-only. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise<number> | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).setReadOnly().then(function (errcode) { + console.log(JSON.stringify(errcode)) +}) +``` + +### NdefTag.setReadOnly9+ + +setReadOnly(callback: AsyncCallback): void + +Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefTag(taginfo).setReadOnly(function (error, errcode) { + console.log(JSON.stringify(error)) + console.log('has: ' + errcode) +}) +``` + +### NdefTag.getNdefTagTypeString9+ + +getNdefTagTypeString(type: [NfcForumType](#nfcforumtype9)): string + +Converts the NFC Forum Type to a byte array defined in the NFC Forum. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| type | [NfcForumType](#nfcforumtype9) | Yes | NFC Forum Type.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| string | Byte array obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let ndefTypeString= tag.NdefTag(taginfo).getNdefTagTypeString(type); +``` + +## NfcForumType9+ + +| **Name**| **Type**| **Description**| +| -------- | -------- | -------- | +| NFC_FORUM_TYPE_1 | 1 | NFC Forum Type 1.| +| NFC_FORUM_TYPE_2 | 2 | NFC Forum Type 2.| +| NFC_FORUM_TYPE_3 | 3 | NFC Forum Type 3.| +| NFC_FORUM_TYPE_4 | 4 | NFC Forum Type 4.| +| MIFARE_CLASSIC | 101 | MIFARE Classic.| + +## MifareClassicTag 9+ + +Provides access to MIFARE Classic properties and I/O operations. **MifareClassicTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **MifareClassicTag**. + +### MifareClassicTag.authenticateSector9+ + +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ + +Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| sectorIndex | number | Yes | Index of the sector to authenticate.| +| key | number[]| Yes | Key (6 bytes) used for authentication.| +| isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If the authentication is successful, **true** is returned. Otherwise, **false** is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key).then(function (isKeyA) { + console.log(JSON.stringify(isKeyA)) + }) +``` + +### MifareClassicTag.authenticateSector9+ + +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback): void + +Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| sectorIndex | number | Yes | Index of the sector to authenticate.| +| key | number[]| Yes | Key (6 bytes) used for authentication.| +| isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key, function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +### MifareClassicTag.readSingleBlock9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to read.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the block data read.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let data = "xxx"; +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex).then(function (data){ + console.log('data: ' + data) + }) +``` + +### MifareClassicTag.readSingleBlock9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let data = "xxx"; +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex, function (error, data) { + console.log(JSON.stringify(error)) + console.log('data: ' + data) +}) +``` + +### MifareClassicTag.writeSingleBlock9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the target block.| +| data | string | Yes | Data to write.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let data = "xxx"; +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.writeSingleBlock9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the target block.| +| data | string | Yes | Data to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let data = "xxx"; +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.incrementBlock9+ + +incrementBlock(blockIndex: number, value: number): Promise\ + +Increments a block with data. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to increment.| +| value | number | Yes | Block data to increment. The value is a non-negative number.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).incrementBlock(blockIndex, value).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.incrementBlock9+ + +incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void + +Increments a block with data. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to increment.| +| value | number | Yes | Block data to increment. The value is a non-negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).incrementBlock(blockIndex, value, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.decrementBlock9+ + +decrementBlock(blockIndex: number, value: number): Promise\ + +Decrements a block with data. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to decrement.| +| value | number | Yes | Block data to decrement. The value is a non-negative number.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).decrementBlock(blockIndex, value).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.decrementBlock9+ + +decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void + +Decrements a block with data. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block to decrement.| +| value | number | Yes | Block data to decrement. The value is a non-negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).decrementBlock(blockIndex, value, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.transferToBlock9+ + +transferToBlock(blockIndex: number): Promise\ + +Copies data from the register to a block. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the destination block.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js + +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).transferToBlock(blockIndex).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.transferToBlock + +transferToBlock(blockIndex: number, callback: AsyncCallback\): void + +Copies data from the register to a block. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the destination block.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).transferToBlock(blockIndex, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.restoreFromBlock9+ + +restoreFromBlock(blockIndex: number): Promise\ + +Copies data from a block to the register. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the source block.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js + +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).restoreFromBlock(blockIndex).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareClassicTag.restoreFromBlock9+ + +restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void + +Copies data from a block to the register. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the source block.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareClassicTag(taginfo).restoreFromBlock(blockIndex, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareClassicTag.getSectorCount9+ + +getSectorCount(): number + +Obtains the number of sectors in this MIFARE Classic tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Number of sectors obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let setorCount = tag.MifareClassicTag(taginfo).getSectorCount(); +``` + +### MifareClassicTag.getBlockCountInSector9+ + +getBlockCountInSector(sectorIndex: number): number + +Obtains the number of blocks in a sector. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| sectorIndex | number | Yes | Index of the sector.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Number of blocks obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let blockNumber = tag.MifareClassicTag(taginfo).getBlockCountInSector(sectorIndex); +``` + +### MifareClassicTag.getType9+ + +getType(): [MifareClassicType](#mifareclassictype9) + +Obtains the type of this MIFARE Classic tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [MifareClassicType](#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let type = tag.MifareClassicTag(taginfo).getType(); +``` + +### MifareClassicTag.getTagSize9+ + +getTagSize(): number + +Obtains the tag size (in bytes). For details, see [MifareTagSize](#mifaretagsize9). + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Tag size obtained, in bytes. For details, see [MifareTagSize](#mifaretagsize9).| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let size = tag.MifareClassicTag(taginfo).getTagSize(); +``` + +## MifareClassicType9+ + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TYPE_UNKNOWN | -1 | Unknown type.| +| TYPE_CLASSIC | 0 | MIFARE Classic.| +| TYPE_PLUS | 1 | MIFARE Plus.| +| TYPE_PRO | 2 | MIFARE Pro.| + +## MifareTagSize9+ + +| **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.| + +### MifareClassicTag.isEmulatedTag9+ + +isEmulatedTag(): boolean + +Checks whether the tag is an emulated tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean |Returns **true** if the tag is an emulated tag; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let isEmulated = tag.MifareClassicTag(taginfo).isEmulatedTag(); +``` + +### MifareClassicTag.getBlockIndex9+ + +getBlockIndex(sectorIndex: number): number + +Obtains the first block of a sector. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| sectorIndex | number | Yes | Index of the sector.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Index of the first block obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let index = tag.MifareClassicTag(taginfo).getBlockIndex(sectorIndex); +``` + +### MifareClassicTag.getSectorIndex9+ + +getSectorIndex(blockIndex: number): number + +Obtains the index of a sector that contains the specified block. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| blockIndex | number | Yes | Index of the block contained in the sector.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Index of the sector obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let index = tag.MifareClassicTag(taginfo).getSectorIndex(blockIndex); +``` + +## MifareUltralightTag9+ + +Provides access to MIFARE Ultralight properties and I/O operations. **MifareUltralightTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **MifareUltralightTag**. + +### MifareUltralightTag.readMultiplePages9+ + +readMultiplePages(pageIndex: number): Promise\ + +Reads multiple pages. The size of each page is 4 bytes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | +| pageIndex | number | Yes | Indexes of the pages to read.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the data read.| + +**Example** + +```js + +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex).then(function (data){ + console.log("data: " + data) + }) +``` + +### MifareUltralightTag.readMultiplePages9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| pageIndex | number | Yes | Indexes of the pages to read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the data read.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex, function (error, data) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +### MifareUltralightTag.writeSinglePages9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| pageIndex | number | Yes | Index of the page.| +| data | string | Yes | Data to write.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### MifareUltralightTag.writeSinglePages9+ + +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. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------ | +| pageIndex | number | Yes | Index of the page.| +| data | string | Yes | Data to write.| +| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### MifareUltralightTag.getType9+ + +getType(): MifareUltralightType + +Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](#mifareultralighttype9). + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| MifareUltralightType | Type of the MIFARE Ultralight tag. For details, see [MifareUltralightType](#mifareultralighttype9).| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let type = tag.MifareUltralightType(taginfo).getType(); +``` + +### MifareUltralightType9+ + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TYPE_UNKOWN | -1 | Unknown type.| +| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| +| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| + +## NdefFormatableTag9+ + +Provides methods for operating NDEF formattable tags. **NdefFormatableTag** inherits from **TagSession**. + +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). + +The following describes the unique interfaces of **NdefFormatableTag**. + +### NdefFormatableTag.format9+ + +format(message: [NdefMessage](#ndefmessage9)): Promise\ + +Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| 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.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefFormatableTag(taginfo).format(message).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### NdefFormatableTag.format9+ + +format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void + +Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| 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.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefFormatableTag(taginfo).format(message, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` + +### NdefFormatableTag.formatReadOnly9+ + +formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ + +Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| 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.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefFormatableTag(taginfo).formatReadOnly(message).then(function (errcode){ + console.log(JSON.stringify(errcode)) + }) +``` + +### NdefFormatableTag.formatReadOnly9+ + +formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void + +Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC + +**Parameters** + +| 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.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +tag.NdefFormatableTag(taginfo).formatReadOnly(message, function (error, errcode) { + console.log(JSON.stringify(error)) + console.log(JSON.stringify(errcode)) +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 7912809087579d64ca726be1b9ada1c8ea0129fb..1e9fa33963ed6eb07302ddfbb9db44973e9be4d4 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,6 +1,11 @@ # Notification +The **Notification** module provides notification management capabilities, covering notifications, notification slots, notification subscription, notification enabled status, and notification badge status. + +Generally, only system applications have the permission to subscribe to and unsubscribe from notifications. + > **NOTE**
+> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -21,7 +26,7 @@ Publishes a notification. This API uses an asynchronous callback to return the r | Name | Readable| Writable| Type | Mandatory| Description | | -------- | ---- | ---- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| | callback | Yes | No |AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -85,13 +90,15 @@ Publishes a notification. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | | -------- | ---- | ---- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| | userId | Yes | No |number | Yes | ID of the user who receives the notification. | | callback | Yes | No |AsyncCallback\ | Yes | Callback used to return the result. | @@ -127,13 +134,15 @@ Publishes a notification. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | | -------- | ---- | ---- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| request | Yes | No |[NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| | userId | Yes | No |number | Yes | ID of the user who receives the notification. | **Example** @@ -291,6 +300,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -324,6 +335,8 @@ Adds a notification slot. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -405,6 +418,8 @@ Adds multiple notification slots. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -442,6 +457,8 @@ Adds multiple notification slots. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -681,6 +698,8 @@ Subscribes to a notification with the subscription information specified. This A **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -720,6 +739,8 @@ Subscribes to a notification with the subscription information specified. This A **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -754,6 +775,8 @@ Subscribes to a notification with the subscription information specified. This A **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -787,6 +810,8 @@ Unsubscribes from a notification. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -821,6 +846,8 @@ Unsubscribes from a notification. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -853,6 +880,8 @@ Sets whether to enable notification for a specified bundle. This API uses an asy **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -885,6 +914,8 @@ Sets whether to enable notification for a specified bundle. This API uses a prom **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -917,6 +948,8 @@ Checks whether notification is enabled for a specified bundle. This API uses an **System API**: This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -946,6 +979,8 @@ Checks whether notification is enabled for a specified bundle. This API uses a p **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -981,6 +1016,8 @@ Checks whether notification is enabled for this application. This API uses an as **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1009,6 +1046,8 @@ Checks whether notification is enabled for this application. This API uses a pro **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1041,6 +1080,8 @@ Sets whether to enable the notification badge for a specified bundle. This API u **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1073,6 +1114,8 @@ Sets the notification slot for a specified bundle. This API uses a promise to re **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1103,6 +1146,8 @@ Checks whether the notification badge is enabled for a specified bundle. This AP **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1134,6 +1179,8 @@ Checks whether the notification badge is enabled for a specified bundle. This AP **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1169,6 +1216,8 @@ Sets the notification slot for a specified bundle. This API uses an asynchronous **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1204,6 +1253,8 @@ Sets the notification slot for a specified bundle. This API uses a promise to re **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1237,6 +1288,8 @@ Obtains the notification slots of a specified bundle. This API uses an asynchron **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1268,6 +1321,8 @@ Obtains the notification slots of a specified bundle. This API uses a promise to **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1303,6 +1358,8 @@ Obtains the number of notification slots of a specified bundle. This API uses an **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1334,6 +1391,8 @@ Obtains the number of notification slots of a specified bundle. This API uses a **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1369,6 +1428,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1405,6 +1466,8 @@ Removes a notification for a specified bundle. This API uses a promise to return **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1439,6 +1502,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1470,6 +1535,8 @@ Removes a notification for a specified bundle. This API uses a promise to return **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1500,6 +1567,8 @@ Removes all notifications for a specified bundle. This API uses an asynchronous **System API**: This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -1529,6 +1598,8 @@ Removes all notifications. This API uses an asynchronous callback to return the **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1557,6 +1628,8 @@ Removes all notifications for a specified user. This API uses a promise to retur **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1581,6 +1654,8 @@ Removes all notifications for a specified user. This API uses an asynchronous ca **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1610,6 +1685,8 @@ Removes all notifications for a specified user. This API uses a promise to retur **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1639,6 +1716,8 @@ Obtains all active notifications. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1667,7 +1746,9 @@ Obtains all active notifications. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification -**System API**: This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications.removeGroupByBundle **Return value** @@ -1847,6 +1928,8 @@ Removes a notification group for a specified bundle. This API uses an asynchrono **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1880,6 +1963,8 @@ Removes a notification group for a specified bundle. This API uses a promise to **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1909,6 +1994,8 @@ Sets the DND time. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1944,6 +2031,8 @@ Sets the DND time. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -1974,6 +2063,8 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2012,6 +2103,8 @@ Sets the DND time for a specified user. This API uses a promise to return the re **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2046,6 +2139,8 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2074,6 +2169,8 @@ Obtains the DND time. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Return value** @@ -2099,6 +2196,10 @@ Obtains the DND time of a specified user. This API uses an asynchronous callback **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -2128,6 +2229,10 @@ Obtains the DND time of a specified user. This API uses a promise to return the **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name | Readable| Writable| Type | Mandatory| Description | @@ -2159,6 +2264,8 @@ Checks whether the DND mode is supported. This API uses an asynchronous callback **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2187,6 +2294,8 @@ Checks whether the DND mode is supported. This API uses a promise to return the **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Return value** @@ -2317,6 +2426,8 @@ Sets whether this device supports distributed notifications. This API uses an as **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2348,6 +2459,8 @@ Sets whether this device supports distributed notifications. This API uses a pro **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2426,6 +2539,8 @@ Sets whether an application supports distributed notifications based on the bund **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2456,12 +2571,14 @@ Notification.enableDistributedByBundle(bundle, enable, enableDistributedByBundle ## Notification.enableDistributedByBundle8+ -bundleenableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise\ +enableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise\ Sets whether an application supports distributed notifications based on the bundle. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2494,6 +2611,8 @@ Obtains whether an application supports distributed notifications based on the b **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2527,6 +2646,8 @@ Obtains whether an application supports distributed notifications based on the b **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2563,6 +2684,8 @@ Obtains the notification reminder type. This API uses an asynchronous callback t **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2591,6 +2714,8 @@ Obtains the notification reminder type. This API uses a promise to return the re **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Return value** @@ -2608,6 +2733,7 @@ Notification.getDeviceRemindType() }); ``` + ## Notification.publishAsBundle9+ publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number, callback: AsyncCallback\): void @@ -2616,14 +2742,15 @@ Publishes an agent-powered notification. This API uses an asynchronous callback **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** - | Name | Type | Mandatory| Description | | -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| | representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | | userId | number | Yes | ID of the user who receives the notification. | | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -2663,6 +2790,8 @@ Publishes a notification through the reminder agent. This API uses a promise to **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + **System API**: This is a system API and cannot be called by third-party applications. **Parameters** @@ -2670,7 +2799,7 @@ Publishes a notification through the reminder agent. This API uses a promise to | Name | Type | Mandatory| Description | | -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | Notification to publish.| +| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| | representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | | userId | number | Yes | ID of the user who receives the notification. | @@ -2707,6 +2836,8 @@ Cancels a notification published by the reminder agent. This API uses an asynchr **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + **Parameters** @@ -2740,6 +2871,8 @@ Publishes a notification through the reminder agent. This API uses a promise to **System capability**: SystemCapability.Notification.Notification +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + **Parameters** @@ -2762,9 +2895,9 @@ Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { }); ``` -## Notification.enableNotificationSlot9+ +## Notification.enableNotificationSlot 9+ -enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback): void +enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback\): void Sets the enabled status for a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -2772,6 +2905,8 @@ Sets the enabled status for a notification slot of a specified type. This API us **System API**: This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **Parameters** | Name | Type | Mandatory| Description | @@ -2791,14 +2926,14 @@ function enableSlotCallback(err) { Notification.enableNotificationSlot( { bundle: "ohos.samples.notification", }, - notify.SlotType.SOCIAL_COMMUNICATION, + Notification.SlotType.SOCIAL_COMMUNICATION, true, enableSlotCallback); ``` -## Notification.enableNotificationSlot9+ +## Notification.enableNotificationSlot 9+ -enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise +enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise\ Sets the enabled status for a notification slot of a specified type. This API uses a promise to return the result. @@ -2806,6 +2941,8 @@ Sets the enabled status for a notification slot of a specified type. This API us **System API**: This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **Parameters** | Name| Type | Mandatory| Description | @@ -2820,29 +2957,31 @@ Sets the enabled status for a notification slot of a specified type. This API us //enableNotificationSlot Notification.enableNotificationSlot( { bundle: "ohos.samples.notification", }, - notify.SlotType.SOCIAL_COMMUNICATION, + Notification.SlotType.SOCIAL_COMMUNICATION, true).then(() => { console.log('====================>enableNotificationSlot====================>'); }); ``` -## Notification.isNotificationSlotEnabled9+ +## Notification.isNotificationSlotEnabled 9+ -isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback): void +isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback\): void -Obtains the enabled status of a notification slot of a specified type. This API uses an asynchronous callback to return the result. +Obtains the enabled status of the notification slot of a specified type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ---------------------- | | bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | | type | [SlotType](#slottype) | Yes | Notification slot type. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -2854,20 +2993,22 @@ function getEnableSlotCallback(err, data) { Notification.isNotificationSlotEnabled( { bundle: "ohos.samples.notification", }, - notify.SlotType.SOCIAL_COMMUNICATION, + Notification.SlotType.SOCIAL_COMMUNICATION, getEnableSlotCallback); ``` -## Notification.isNotificationSlotEnabled9+ +## Notification.isNotificationSlotEnabled 9+ -isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise +isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ -Obtains the enabled status of a notification slot of a specified type. This API uses a promise to return the result. +Obtains the enabled status of the notification slot of a specified type. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + **Parameters** | Name| Type | Mandatory| Description | @@ -2875,30 +3016,180 @@ Obtains the enabled status of a notification slot of a specified type. This API | bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | | type | [SlotType](#slottype) | Yes | Notification slot type.| +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the enabled status of the notification slot of the specified type.| + **Example** ```js //isNotificationSlotEnabled Notification.isNotificationSlotEnabled( { bundle: "ohos.samples.notification", }, - notify.SlotType.SOCIAL_COMMUNICATION, - true).then((data) => { + Notification.SlotType.SOCIAL_COMMUNICATION + ).then((data) => { console.log('====================>isNotificationSlotEnabled====================>'); }); ``` + +## Notification.setSyncNotificationEnabledForUninstallApp9+ + +setSyncNotificationEnabledForUninstallApp(userId: number, enable: boolean, callback: AsyncCallback\): void + +Sets whether to sync notifications to devices where the application is not installed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| userId | number | Yes | User ID. | +| enable | boolean | Yes | Whether to sync notifications to devices where the application is not installed. The value **true** means to sync notifications to devices where the application is not installed, and **false** means the opposite.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let userId = 100; +let enable = true; + +function setSyncNotificationEnabledForUninstallAppCallback(err) { + console.log('setSyncNotificationEnabledForUninstallAppCallback'); +} + +Notification.setSyncNotificationEnabledForUninstallApp(userId, enable, setSyncNotificationEnabledForUninstallAppCallback); +``` + + +## Notification.setSyncNotificationEnabledForUninstallApp9+ + +setSyncNotificationEnabledForUninstallApp(userId: number, enable: boolean): Promise\ + +Sets whether to sync notifications to devices where the application is not installed. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| userId | number | Yes | User ID. | +| enable | boolean | Yes | Whether to sync notifications to devices where the application is not installed. The value **true** means to sync notifications to devices where the application is not installed, and **false** means the opposite.| + +**Example** + +```js +let userId = 100; +let enable = true; + +Notification.setSyncNotificationEnabledForUninstallApp(userId, enable) + .then((data) => { + console.log('setSyncNotificationEnabledForUninstallApp, data:', data); + }) + .catch((err) => { + console.log('setSyncNotificationEnabledForUninstallApp, err:', err); + }); +``` + + +## Notification.getSyncNotificationEnabledForUninstallApp9+ + +getSyncNotificationEnabledForUninstallApp(userId: number, callback: AsyncCallback\): void + +Checks whether notifications are synced to devices where the application is not installed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| userId | number | Yes | User ID. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that notifications are synced to devices where the application is not installed, and **false** means the opposite.| + +**Example** + +```js +let userId = 100; + +function getSyncNotificationEnabledForUninstallAppCallback(err, data) { + console.log('getSyncNotificationEnabledForUninstallAppCallback, data: ', data); +} + +Notification.getSyncNotificationEnabledForUninstallApp(userId, getSyncNotificationEnabledForUninstallAppCallback); +``` + + +## Notification.getSyncNotificationEnabledForUninstallApp9+ + +getSyncNotificationEnabledForUninstallApp(userId: number): Promise\ + +Checks whether notifications are synced to devices where the application is not installed. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| userId | number | Yes | User ID. | + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** means that notifications are synced to devices where the application is not installed, and **false** means the opposite.| + +**Example** + +```js +let userId = 100; + +Notification.getSyncNotificationEnabledForUninstallApp(userId) + .then((data) => { + console.log('getSyncNotificationEnabledForUninstallApp, data: ', data); + }) + .catch((err) => { + console.log('getSyncNotificationEnabledForUninstallApp, err: ', err); + }); +``` + + + ## NotificationSubscriber **System API**: This is a system API and cannot be called by third-party applications. ### onConsume -onConsume?:(data: [SubscribeCallbackData](#subscribecallbackdata)) +onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void Callback for receiving notifications. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -2940,12 +3231,14 @@ Notification.subscribe(subscriber, subscribeCallback); ### onCancel -onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) +onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void Callback for removing notifications. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -2978,12 +3271,14 @@ Notification.subscribe(subscriber, subscribeCallback); ### onUpdate -onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) +onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void Callback for notification sorting updates. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -3014,12 +3309,14 @@ Notification.subscribe(subscriber, subscribeCallback); ### onConnect -onConnect?:void +onConnect?:() => void Callback for subscription. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Example** ```javascript @@ -3044,12 +3341,14 @@ Notification.subscribe(subscriber, subscribeCallback); ### onDisconnect -onDisconnect?:void +onDisconnect?:() => void Callback for unsubscription. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Example** ```javascript @@ -3074,12 +3373,14 @@ Notification.subscribe(subscriber, subscribeCallback); ### onDestroy -onDestroy?:void +onDestroy?:() => void Callback for service disconnection. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Example** ```javascript @@ -3104,17 +3405,19 @@ Notification.subscribe(subscriber, subscribeCallback); ### onDoNotDisturbDateChange8+ -onDoNotDisturbDateChange?:(mode: Notification.[DoNotDisturbDate](#donotdisturbdate8)) +onDoNotDisturbDateChange?:(mode: notification.[DoNotDisturbDate](#donotdisturbdate8)) => void Callback for DND time setting updates. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| mode | Notification.[DoNotDisturbDate](#donotdisturbdate8) | Yes| DND time setting updates.| +| mode | notification.[DoNotDisturbDate](#donotdisturbdate8) | Yes| DND time setting updates.| **Example** ```javascript @@ -3140,12 +3443,14 @@ Notification.subscribe(subscriber, subscribeCallback); ### onEnabledNotificationChanged8+ -onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata8)) +onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata8)) => void Listens for the notification enable status changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| @@ -3201,7 +3506,7 @@ Notification.subscribe(subscriber, subscribeCallback); | ------ | ---- | --- | ------- | ---- | ---------------- | | bundle | Yes | No | string | Yes | Bundle name of the application. | | uid | Yes | No | number | Yes | UID of the application. | -| enable | Yes | No | boolean | Yes | Notification enable status of the application.| +| enable | Yes | No | boolean | Yes | Notification enabled status of the application.| ## DoNotDisturbDate8+ @@ -3300,7 +3605,7 @@ Notification.subscribe(subscriber, subscribeCallback); | title | Yes | Yes | string | Yes | Button title. | | wantAgent | Yes | Yes | WantAgent | Yes | **WantAgent** of the button.| | extras | Yes | Yes | { [key: string]: any } | No | Extra information of the button. | -| userInput9+ | Yes | Yes | [NotificationUserInput](#notificationuserinput8) | No | User input object. | +| userInput8+ | Yes | Yes | [NotificationUserInput](#notificationuserinput8) | No | User input object. | ## NotificationBasicContent @@ -3425,14 +3730,16 @@ Notification.subscribe(subscriber, subscribeCallback); | creatorPid | Yes | No | number | No | PID used for creating the notification. | | creatorUserId8+| Yes | No | number | No | ID of the user who creates the notification. | | hashCode | Yes | No | string | No | Unique ID of the notification. | -| classification | Yes | Yes | string | No | Notification category. | +| classification | Yes | Yes | string | No | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | | groupName8+| Yes | Yes | string | No | Group notification name. | | template8+ | Yes | Yes | [NotificationTemplate](#notificationtemplate8) | No | Notification template. | -| isRemoveAllowed8+ | Yes | No | boolean | No | Whether the notification can be removed. | -| source8+ | Yes | No | number | No | Notification source. | +| isRemoveAllowed8+ | Yes | No | boolean | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| source8+ | Yes | No | number | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | | distributedOption8+ | Yes | Yes | [DistributedOptions](#distributedoptions8) | No | Option of distributed notification. | -| deviceId8+ | Yes | No | string | No | Device ID of the notification source. | +| deviceId8+ | Yes | No | string | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | | notificationFlags8+ | Yes | No | [NotificationFlags](#notificationflags8) | No | Notification flags. | +| removalWantAgent9+ | Yes | Yes | WantAgent | No | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber9+ | Yes | Yes | number | No | Number of notifications displayed on the application icon. | ## DistributedOptions8+ @@ -3444,7 +3751,7 @@ Notification.subscribe(subscriber, subscribeCallback); | isDistributed | Yes | Yes | boolean | No | Whether the notification is a distributed notification. | | supportDisplayDevices | Yes | Yes | Array\ | Yes | Types of the devices to which the notification can be synchronized. | | supportOperateDevices | Yes | Yes | Array\ | No | Devices on which notification can be enabled. | -| remindType | Yes | No | number | No | Notification reminder type. | +| remindType | Yes | No | number | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | ## NotificationSlot @@ -3535,3 +3842,16 @@ Notification.subscribe(subscriber, subscribeCallback); | IDLE_REMIND | 1 | The device is not in use. | | ACTIVE_DONOT_REMIND | 2 | The device is in use. No notification is required. | | ACTIVE_REMIND | 3 | The device is in use. | + + +## SourceType8+ + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | -------------------- | +| TYPE_NORMAL | 0 | Normal notification. | +| TYPE_CONTINUOUS | 1 | Continuous notification. | +| TYPE_TIMER | 2 | Timed notification. | diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index e1dbb5f4a54b3936dc4b52e76ab5ad0fc0a39265..58d29f74c3196918f08da1b8e12babc71efc5347 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -801,7 +801,7 @@ Obtains the OS account ID based on domain account information. This API uses an | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | -------------------------------------------- | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | | callback | AsyncCallback<number> | Yes | Callback used to return the ID of the OS account associated with the domain account.| **Example** @@ -829,7 +829,7 @@ Obtains the OS account ID based on domain account information. This API uses a p | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | ------------ | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information.| +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information.| **Return value** @@ -1156,7 +1156,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | :--------- | ---------------------------------------------------- | ---- | ------------------------------------------ | | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create. | -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | | callback | AsyncCallback<[OsAccountInfo](#osaccountinfo)> | Yes | Callback used to return the OS account created.| **Example** @@ -1187,7 +1187,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | --------------------------------------- | ---- | ---------------------- | | type | [OsAccountType](#osaccounttype) | Yes | Type of the OS account to create.| -| domainInfo | [DomainAccountInfo](#domainaccountinfo) | Yes | Domain account information. | +| domainInfo | [DomainAccountInfo](#domainaccountinfo8) | Yes | Domain account information. | **Return value** @@ -1749,7 +1749,7 @@ This is a system API and cannot be called by third-party applications. getBundleIdFromUid(uid: number, callback: AsyncCallback<number>): void; -Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. +Obtains the bundle ID based on the UID. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1760,7 +1760,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | uid | number | Yes | Process UID.| -| callback | AsyncCallback<number> | Yes | Callback used to return the bundle ID obtained. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the bundle ID obtained. | **Example** @@ -1854,7 +1854,7 @@ This is a system API and cannot be called by third-party applications. queryOsAccountConstraintSourceTypes(localId: number, constraint: string, callback: AsyncCallback<Array<ConstraintSourceTypeInfo>>): void; -Obtains the constraint source information of an OS account. +Obtains the constraint source information of an OS account. This API uses an asynchronous callback to return the result. This is a system API and cannot be called by third-party applications. @@ -1868,7 +1868,7 @@ This is a system API and cannot be called by third-party applications. | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | localId | number | Yes | ID of the target OS account.| | constraint | string | Yes | Name of the [constraint](#constraints) to query.| -| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback used to return the source information about the specified [constraint] (#constraints). | +| callback | AsyncCallback<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Yes | Callback invoked to return the source information about the specified [constraint](#constraints). | **Example** @@ -1902,7 +1902,7 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | :-------------------- | :----------------------------------------------------------- | -| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint] (#constraints).| +| Promise<Array<[ConstraintSourceTypeInfo](#constraintsourcetypeinfo)>> | Promise used to return the source information about the specified [constraint](#constraints).| **Example** @@ -1912,6 +1912,1289 @@ This is a system API and cannot be called by third-party applications. console.info("queryOsAccountConstraintSourceType sourceTypeInfos:" + JSON.stringify(sourceTypeInfos)); ``` +## UserAuth8+ + +Provides APIs for user authentication. + +### constructor8+ + +constructor() + +A constructor used to create an instance for user authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + console.info('====>test for examples constructor success'); + ``` + + +### getVersion8+ + +getVersion(): number; + +Obtains version information. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Return value** + +| Type | Description | +| :----- | :----------- | +| number | Version information obtained.| + +**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)); + ``` + +### getAvailableStatus8+ + +getAvailableStatus(authType: AuthType, authTrustLevel: AuthTrustLevel): number; + +Checks whether the identity authentication function is available. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -----------------------------------------------| ---- | ------------------------- | +| 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+).| + +**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)); + ``` + +### getProperty8+ + +getProperty(request: GetPropertyRequest, callback: AsyncCallback<ExecutorProperty>): void; + +Obtains the executor property based on the request. 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.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| 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. | + +**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)); + }) + ``` + +### getProperty8+ + +getProperty(request: GetPropertyRequest): Promise; + +Obtains the executor property based on the request. This API uses a promise 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.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------------------------------- | +| 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)); + }); + ``` + +### setProperty8+ + +setProperty(request: SetPropertyRequest, callback: AsyncCallback): void; + +Sets the property for the initialization algorithm. 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.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| 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+).| + +**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)); + }); + ``` + +### setProperty8+ + +setProperty(request: SetPropertyRequest): Promise; + +Sets the property for the initialization algorithm. This API uses a promise 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.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------------------------------------- | +| 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+).| + +**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)); + }); + ``` + +### auth8+ + +auth(challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; + +Performs authentication. This API uses a 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.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| 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. | + + +**Return value** + +| Type | Description | +| :--------- | :----------------- | +| Uint8Array | ID of the context for canceling the authentication.| + +**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)); + } + }); + ``` + +### authUser8+ + +authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; + +Perform user authentication. This API uses a 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.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------------------------- | --- | ------------------------------------ | +| 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. | + + +**Return value** + +| Type | Description | +| :--------- | :----------------- | +| Uint8Array | ID of the context for canceling the authentication.| + +**Example** + ```js + let userAuth = new osAccount.UserAuth(); + let authType = osAccount.AuthType.PIN; + let challenge = 1; + let authTrustLevel = osAccount.AuthTrustLevel.ATL1; + let userID = 100; + let onresult = { + authresult: null, + authextr: null, + } + 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)); + } + }); + ``` + +### cancelAuth8+ + +cancelAuth(contextID: Uint8Array): number; + +Cancels authentication. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------| ---------- | ---- | ------------------------------------------ | +| contextID | Uint8Array | Yes | ID of the authentication context. The context ID is dynamically generated.| + +**Return value** + +| Type | Description | +| :----- | :-------------------------------------------------------- | +| 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)); + ``` + +## PINAuth8+ + +Provides methods for PIN authentication. + +### constructor8+ + +constructor() + +A constructor used to create an instance for PIN authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + var pinAuth = new osAccount.PINAuth(); + console.info('====>test for examples constructor success'); + ``` + +### registerInputer + +registerInputer(inputer: IInputer): boolean; + +Registers an inputer. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_PIN_AUTH + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------------------- | --- | ------------------ | +| inputer | [IInputer](#IInputer8+) | Yes | Callback invoked to obtain the PIN.| + +**Return value** + +| Type | Description | +| :------ | :-------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**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); + } + } + }) + console.log("====>test for examples RegisterInputer result is: " + registerresult); + ``` + +### unregisterInputer + +unregisterInputer(): void; + +Unregisters the inputer. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_PIN_AUTH + +**Example** + ```js + var pinAuth = new osAccount.PinAuth(); + pinAuth.unregisterInputer(); + ``` + +## UserIdentityManager8+ + +Provides methods for user identity management. + +### constructor8+ + +constructor() + +A constructor used to create an instance for user authentication. + +**System capability**: SystemCapability.Account.OsAccount + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + console.info('====>test for examples constructor success'); + ``` + +### openSession8+ + +openSession(callback: AsyncCallback<Uint8Array>): void; + +Opens a session to start identity management (IDM) so that a challenge value can be obtained. 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.MANAGE_USER_IDM + +**Parameters** + +| 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.| + +**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)); + } + }); + ``` + +### openSession8+ + +openSession(): Promise<Uint8Array>; + +Opens a session to start IDM so that a challenge value can be obtained. This API uses a promise 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.MANAGE_USER_IDM + +**Return value** + +| 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.| + +**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)); + }) + ``` + +### addCredential8+ + +addCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; + +Adds credential information, which includes the authentication credential type, subtype, and token (if a non-PIN credential is added). This API uses a 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.MANAGE_USER_IDM + +**Parameters** + +| 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. | + +**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; + } + } + }) + ``` + +### updateCredential8+ + +updateCredential(credentialInfo: CredentialInfo, callback: IIdmCallback): void; + +Updates credential information. This API uses a 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.MANAGE_USER_IDM + +**Parameters** + +| 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; + } + console.info('====>test for examples publicupdateCred updateCredential onResult = ' + JSON.stringify(onresult)); + } + }) + ``` + +### closeSession8+ + +closeSession(): void; + +Closes this session to terminate IDM. + +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 + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + userIDM.closeSession(); + ``` + +### cancel8+ + +cancel(challenge: Uint8Array): number; + +Cancels an entry based on the challenge value. + +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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ----- | +| challenge | Uint8Array | Yes | Challenge value.| + +**Return value** + +| Type | Description | +| :----- | :-------------------------------------------------------- | +| number | [Result code](#ResultCode8+).| + +**Example** + ```js + var userIDM = new osAccount.UserIdentityManager(); + let challenge = 1; + let cancelresult = userIDM.cancel(challenge); + ``` + +### delUser8+ + +delUser(token: Uint8Array, callback: IIdmCallback): void; + +Deletes a user based on the authentication token. The API uses a 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.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | --- | ------------------------- | +| token | Uint8Array | Yes | Authentication token. | +| 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; + 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)); + } + }) + ``` + +### delCred8+ + +delCred(credentialId: Uint8Array, token: Uint8Array, callback: IIdmCallback): void; + +Deletes user credential information. The API uses a 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.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ----------------------------------------------- | --- | ---------------------------| +| credentialId | Uint8Array | Yes | Credential ID. | +| token | Uint8Array | Yes | Authentication token. | +| 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)); + } + }) + ``` + +### getAuthInfo8+ + +getAuthInfo(callback: AsyncCallback<Array<EnrolledCredInfo>>, authType?: AuthType): void; + +Obtains authentication information. This API uses 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.MANAGE_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. | + +**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)) + }) + ``` + +### getAuthInfo8+ + +getAuthInfo(authType?: AuthType): Promise<Array<EnrolledCredInfo>>; + +Obtains authentication information. This API uses a promise 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.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------- | +| 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.| + +**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)) + }) + ``` + +## IInputData8+ + +Provides callbacks for PIN operations. + +### onSetData8+ + +onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; + +Called to set data. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | +| 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); + ``` + +## IInputer8+ + +Provides callbacks for the PIN input box. + +### onGetData8+ + +onGetData: (callback: IInputData) => void; + +Called to obtain data. + +**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); + ``` + +## IUserAuthCallback8+ + +Provides callbacks for user authentication. + +### onResult8+ + +onResult: (result: number, extraInfo: AuthResult) => void; + +Called to return the authentication result code. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| 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.| + +**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)); + } + }); + ``` + +### onAcquireInfo?8+ + +onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; + +Called to return the **TipsCode** during the authentication process. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ----------------------------- | +| module | number | Yes | Type of authentication executor. | +| acquire | number | Yes | Tip code of the authentication executor.| +| extraInfo | any | Yes | Reserved. | + +**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)); + } + }); + ``` + +## IIdmCallback8+ + +Provides callbacks for IDM. + +### 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** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------- | ---- | ----------------------- | +| result | number | Yes | Authentication result code. | +| 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)); + } + }) + ``` + +### onAcquireInfo?8+ + +onAcquireInfo?: (module: number, acquire: number, extraInfo: any) => void; + +Called to return the **TipsCode** during the authentication process. + +This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Account.OsAccount + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ----------------------------- | +| module | number | Yes | Type of authentication executor. | +| acquire | number | Yes | Tip code of the authentication executor.| +| extraInfo | any | Yes | Reserved. | + +**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) + } + }) + ``` + +## GetPropertyRequest8+ + +Defines the request for obtaining property information. + +**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.| + +## SetPropertyRequest8+ + +Defines the request for setting property information. + +**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.| +| setInfo | Uint8Array | Yes | Information to set. | + +## ExecutorProperty8+ + +Defines the executor property. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ----- | ----------------- | +| result | number | Yes | Result. | +| authSubType | [AuthSubType](#AuthSubType8+) | Yes | Authentication credential subtype.| +| remainTimes | number | No | Remaining time. | +| freezingTime | number | No | Freezing time. | + +## AuthResult8+ + +Defines the authentication result information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ----------- | ----- | ----------------- | +| token | Uint8Array | No | Authentication token. | +| remainTimes | number | No | Remaining time. | +| freezingTime | number | No | Freezing time. | + +## CredentialInfo8+ + +Defines the credential information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | ----- | ----------------- | +| credType | [AuthType](#AuthType8+) | Yes | Authentication credential type. | +| credSubType | [AuthSubType](#AuthSubType8+) | Yes | Credential subtype. | +| token | Uint8Array | Yes | Authentication token. | + +## RequestResult8+ + +Defines the request result information. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Type | Mandatory | Description | +| ------------ | ----------- | ----- | ----------------- | +| credentialId | Uint8Array | No | Credential ID. | + +## EnrolledCredInfo8+ + +Defines enrolled credential information. + +**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. | + +## GetPropertyType8+ + +Enumerates the types of the properties to obtain. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ------------- | ------ | --------- | +| AUTH_SUB_TYPE | 1 | Authentication subtype.| +| REMAIN_TIMES | 2 | Remaining time. | +| FREEZING_TIME | 3 | Freezing time. | + +## SetPropertyType8+ + +Enumerates the types of the properties to set. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| -------------- | ----- | ----------- | +| INIT_ALGORITHM | 1 | Initialization algorithm.| + +## AuthType8+ + +Enumerates the credential types. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----- | ----- | ---------------- | +| PIN | 1 | PIN authentication.| +| FACE | 2 | Facial authentication.| + +## AuthSubType8+ + +Enumerates the credential subtypes. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ---------- | ----- | ------------------ | +| PIN_SIX | 10000 | Six-digit PIN. | +| PIN_NUMBER | 10001 | Custom PIN.| +| PIN_MIXED | 10002 | Custom mixed credential.| +| FACE_2D | 20000 | 2D face credential. | +| FACE_3D | 20001 | 3D face credential. | + +## AuthTrustLevel8+ + +Enumerates the trust levels of the authentication result. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ---- | ------ | ----------- | +| ATL1 | 10000 | Trust level 1.| +| ATL2 | 20000 | Trust level 2.| +| ATL3 | 30000 | Trust level 3.| +| ATL4 | 40000 | Trust level 4.| + +## Module8+ + +Enumerates the modules from which information is obtained. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| --------- | ------ | ------------------------ | +| FACE_AUTH | 1 | Information obtained from the face authentication module.| + +## ResultCode8+ + +Enumerates the authentication result codes. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----------------------- | ----- | ---------------------------------------- | +| SUCCESS | 0 | The authentication is successful or the authentication function 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.| +| INVALID_PARAMETERS | 8 | Incorrect parameters are detected. | +| LOCKED | 9 | The authentication executor is locked. | +| NOT_ENROLLED | 10 | The authentication executor is not enrolled. | + +## FaceTipsCode8+ + +Enumerates the tip codes for facial authentication. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----------------------------- | ----- | ---------------------------------------- | +| FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained face image is too bright. | +| FACE_AUTH_TIP_TOO_DARK | 2 | The obtained face image is too dark. | +| FACE_AUTH_TIP_TOO_CLOSE | 3 | The face is too close to the device. | +| FACE_AUTH_TIP_TOO_FAR | 4 | The face is too far away from the device. | +| FACE_AUTH_TIP_TOO_HIGH | 5 | Only the upper part of the face is captured because the device is angled too high. | +| FACE_AUTH_TIP_TOO_LOW | 6 | Only the lower part of the face is captured because the device is angled too low. | +| FACE_AUTH_TIP_TOO_RIGHT | 7 | Only the right part of the face is captured because the device is angled too much to the right.| +| FACE_AUTH_TIP_TOO_LEFT | 8 | Only the left part of the face is captured because the device is angled too much to the left.| +| FACE_AUTH_TIP_TOO_MUCH_MOTION | 9 | The face moves too fast during facial information collection. | +| FACE_AUTH_TIP_POOR_GAZE | 10 | The face is not facing the device. | +| FACE_AUTH_TIP_NOT_DETECTED | 11 | No face is detected. | + +## ingerprintTips8+ + +Enumerates the tip codes for fingerprint authentication. + +**System capability**: SystemCapability.Account.OsAccount + +| Name | Default Value| Description | +| ----------------------------- | ----- | ----------------------------------------------- | +| FINGERPRINT_TIP_GOOD | 0 | The captured image is clear. | +| FINGERPRINT_TIP_IMAGER_DIRTY | 1 | The fingerprint image has big noise due to dirt on the sensor.| +| FINGERPRINT_TIP_INSUFFICIENT | 2 | Failed to process the fingerprint image due to big noise. | +| FINGERPRINT_TIP_PARTIAL | 3 | Only part of the fingerprint image is detected. | +| FINGERPRINT_TIP_TOO_FAST | 4 | The fingerprint image is incomplete due to quick motion. | +| FINGERPRINT_TIP_TOO_SLOW | 5 | Failed to read the fingerprint image due to lack of motion. | + ## OsAccountInfo Defines information about an OS account. @@ -1932,7 +3215,7 @@ Defines information about an OS account. | isActived8+ | boolean | Yes | Whether the OS account is activated. | | isCreateCompleted8+ | boolean | Yes | Whether the OS account information is complete. | | distributedInfo | [distributedAccount.DistributedInfo](js-apis-distributed-account.md) | No | Distributed account information. | -| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo) | No | Domain account information. | +| domainInfo8+ | [DomainAccountInfo](#domainaccountinfo8) | No | Domain account information. | ## DomainAccountInfo8+ @@ -2017,6 +3300,8 @@ Domain account information. Defines information about the source of a constraint. +This is a system API. + **System capability**: SystemCapability.Account.OsAccount | Name | Type | Mandatory| Description | @@ -2028,6 +3313,8 @@ Defines information about the source of a constraint. Enumerates the constraint sources. +This is a system API. + **System capability**: SystemCapability.Account.OsAccount | Name | Default Value| Description | diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 3facc0146ebe2484672cffb3c9a45d0ac7d9f164..971b3408c9a9fdd616fe1133ca3cab3844ee7fd1 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -1,22 +1,22 @@ # Prompt +The **Prompt** module provides APIs for creating and showing toasts, dialog boxes, and action menus. + > **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import prompt from '@ohos.prompt' ``` -## Required Permissions - -None. ## prompt.showToast showToast(options: ShowToastOptions): void -Shows the toast. +Shows a toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -26,15 +26,11 @@ Shows the toast. | options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| **Example** - ``` - export default { - showToast() { - prompt.showToast({ - message: 'Message Info', - duration: 2000, - }); - } - } + ```js +prompt.showToast({ + message: 'Message Info', + duration: 2000, +}); ``` ## ShowToastOptions @@ -42,11 +38,11 @@ Describes the options for showing the toast. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| -------- | -------------- | ---- | ---------------------------------------- | -| message | string | 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 | <length> | 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 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. | ## prompt.showDialog @@ -69,38 +65,34 @@ Shows a dialog box. This API uses a promise to return the result synchronously. **Example** - ``` - export default { - showDialog() { - prompt.showDialog({ - title: 'Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button1', - color: '#000000', - }, - { - text: 'button2', - color: '#000000', - } - ], - }) - .then(data => { - console.info('showDialog success, click button: ' + data.index); - }) - .catch(err => { - console.info('showDialog error: ' + err); - }) + ```js +prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', } - } + ], +}) + .then(data => { + console.info('showDialog success, click button: ' + data.index); + }) + .catch(err => { + console.info('showDialog error: ' + err); + }) ``` ## prompt.showDialog showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void -Shows a dialog box. This API uses a callback to return the result asynchronously. +Shows a dialog box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -112,32 +104,27 @@ Shows a dialog box. This API uses a callback to return the result asynchronously | callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | **Example** - ``` - export default { - callback(err, data) { - if(err) { - console.info('showDialog err: ' + err); - return; - } - console.info('showDialog success callback, click button: ' + data.index); + ```js +prompt.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', }, - showDialog() { - prompt.showDialog({ - title: 'showDialog Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button1', - color: '#000000', - }, - { - text: 'button2', - color: '#000000', - } - ] - }, this.callback); + { + text: 'button2', + color: '#000000', } + ] +}, (err, data) => { + if (err) { + console.info('showDialog err: ' + err); + return; } + console.info('showDialog success callback, click button: ' + data.index); +}); ``` ## ShowDialogOptions @@ -146,11 +133,11 @@ Describes the options for showing the dialog box. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---------------------------------------- | -| title | string | No | Title of the text to display. | -| message | string | No | Text body. | -| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. One to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](.../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 @@ -160,7 +147,7 @@ Describes the dialog box response result. | Name | Type | Description | | ----- | ------ | ------------------- | -| index | number | Index of the selected button in the array.| +| index | number | Index of the selected button in the **buttons** array.| ## prompt.showActionMenu @@ -179,36 +166,31 @@ Shows an action menu. This API uses a callback to return the result asynchronous **Example** - ``` - export default { - callback(err, data) { - if(err) { - console.info('showActionMenu err: ' + err); - return; - } - console.info('showActionMenu success callback, click button: ' + data.index); + ```js +prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', }, - showActionMenu() { - prompt.showActionMenu({ - title: 'Title Info', - buttons: [ - { - text: 'item1', - color: '#666666', - }, - { - text: 'item2', - color: '#000000', - }, - ] - }, this.callback) - } + { + text: 'item2', + color: '#000000', + }, + ] +}, (err, data) => { + if (err) { + console.info('showActionMenu err: ' + err); + return; } + console.info('showActionMenu success callback, click button: ' + data.index); +}) ``` ## prompt.showActionMenu -showActionMenu(options: ActionMenuOptions): Promise\ +showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> Shows an action menu. This API uses a promise to return the result synchronously. @@ -225,30 +207,26 @@ Shows an action menu. This API uses a promise to return the result synchronously | Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| **Example** - ``` - export default { - showActionMenu() { - prompt.showActionMenu({ - title: 'showActionMenu Title Info', - buttons: [ - { - text: 'item1', - color: '#666666', - }, - { - text: 'item2', - color: '#000000', - }, - ] - }) - .then(data => { - console.info('showActionMenu success, click button: ' + data.index); - }) - .catch(err => { - console.info('showActionMenu error: ' + err); - }) - } - } + ```js +prompt.showActionMenu({ + title: 'showActionMenu Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] +}) + .then(data => { + console.info('showActionMenu success, click button: ' + data.index); + }) + .catch(err => { + console.info('showActionMenu error: ' + err); + }) ``` ## ActionMenuOptions @@ -256,10 +234,10 @@ Describes the options for showing the action menu. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | ---------------------------------------- | -| title | string | No | Title of the text to display. | -| buttons | Array | Yes | Array of menu items. The array structure is **{text:'button', color: '\#666666'}**. One to six items are supported. If there are more than six items, extra items will not be displayed.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| 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 @@ -269,4 +247,15 @@ Describes the action menu response result. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ------------------------ | -| index | number | No | Index of the selected button in the array, starting from **0**.| +| index | number | No | Index of the selected button in the **buttons** array, starting from **0**.| + +## Button + +Describes the menu item button in the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| 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.| diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 5b371ea07267732eb69de7676cab7f6057954275..16da2e93685e99d26b9af2040af3f294ce68bd08 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -899,9 +899,698 @@ promise.then(data => { }); ``` +## radio.sendUpdateCellLocationRequest8+ + +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 capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.sendUpdateCellLocationRequest((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.sendUpdateCellLocationRequest8+ + +sendUpdateCellLocationRequest\(\): Promise + +Sends a cell location update request. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = radio.sendUpdateCellLocationRequest(); +promise.then(data => { + console.log(`sendUpdateCellLocationRequest success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`sendUpdateCellLocationRequest fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## radio.getCellInformation8+ + +getCellInformation(callback: AsyncCallback>): void + +Obtains cell information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------ | +| callback | AsyncCallback\\> | Yes | Callback used to return the result.| + +**Example** + +```js +radio.getCellInformation((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getCellInformation8+ + +getCellInformation(slotId: number, callback: AsyncCallback\>): void + +Obtains cell information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\\> | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.getCellInformation(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getCellInformation8+ + +getCellInformation(slotId?: number): Promise\> + +Obtains cell information. This API uses a promise to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | ----------------------- | +| Promise\\> | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +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)}`); +}); +``` + +## radio.setNetworkSelectionMode + +setNetworkSelectionMode\(options: NetworkSelectionModeOptions, callback: AsyncCallback\): void + +Sets the network selection mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------ | +| options | [NetworkSelectionModeOptions](#networkselectionmodeoptions) | Yes | Network selection mode.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let networkInformation={ + operatorName: "China Mobile", + operatorNumeric: "898600", + state: 1, + radioTech: "CS" +} +let networkSelectionModeOptions={ + slotid: 0, + selectMode: 1, + networkInformation: networkInformation, + resumeSelection: true +} +radio.setNetworkSelectionMode(networkSelectionModeOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.setNetworkSelectionMode + +setNetworkSelectionMode\(options: NetworkSelectionModeOptions\): Promise + +Sets the network selection mode. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------------------------- | ---- | ------------------ | +| options | [NetworkSelectionModeOptions](#networkselectionmodeoptions) | Yes | Network selection mode.| + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let networkInformation={ + operatorName: "China Mobile", + operatorNumeric: "898600", + state: 1, + radioTech: "CS" +} +let networkSelectionModeOptions={ + slotid: 0, + selectMode: 1, + networkInformation: networkInformation, + resumeSelection: true +} +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)}`); +}); +``` + +## radio.getNetworkSearchInformation + +getNetworkSearchInformation\(slotId: number, callback: AsyncCallback\): void + +Obtains network search information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[NetworkSearchResult](#networksearchresult)\> | Yes | Callback used to return the result. | + +**Example** + +```js +radio.getNetworkSearchInformation(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.getNetworkSearchInformation + +getNetworkSearchInformation\(slotId: number\): Promise + +Obtains network search information. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ----------------------- | +| Promise\<[NetworkSearchResult](#networksearchresult)\> | Promise used to return the result.| + +**Example** + +```js +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)}`); +}); +``` + +## radio.getNrOptionMode8+ + +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 capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\<[NrOptionMode](#nroptionmode8)\> | Yes | Callback used to return the result.| + +**Example** + +```js +radio.getNrOptionMode((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getNrOptionMode8+ + +getNrOptionMode(slotId: number, callback: AsyncCallback): void + +Obtains the NR option mode. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[NrOptionMode](#nroptionmode8)\> | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.getNrOptionMode(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.getNrOptionMode8+ + +getNrOptionMode(slotId?: number): Promise + +Obtains the NR option mode. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ----------------------------------------- | ----------------------- | +| Promise\<[NrOptionMode](#nroptionmode8)\> | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +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)}`); +}); +``` + +## radio.turnOnRadio7+ + +turnOnRadio(callback: AsyncCallback): void + +Turns on the radio function. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.turnOnRadio((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.turnOnRadio7+ + +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. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.turnOnRadio(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.turnOnRadio7+ + +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. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +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)}`); +}); +``` + +## radio.turnOffRadio7+ + +turnOffRadio(callback: AsyncCallback): void + +Turns off the radio function. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.turnOffRadio((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.turnOffRadio7+ + +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. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +radio.turnOffRadio(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## radio.turnOffRadio7+ + +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. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +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)}`); +}); +``` + +## radio.setPreferredNetwork8+ + +setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback: AsyncCallback\): void + +Sets the preferred network. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| networkMode | [PreferredNetworkMode](#preferrednetworkmode8) | Yes | Preferred network mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +radio.setPreferredNetwork(0, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.setPreferredNetwork8+ + +setPreferredNetwork(slotId: number, networkMode: PreferredNetworkMode): Promise + +Sets the preferred network. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| networkMode | [PreferredNetworkMode](#preferrednetworkmode8) | Yes | Preferred network mode. | + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +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)}`); +}); +``` + +## radio.getPreferredNetwork8+ + +getPreferredNetwork\(slotId: number, callback: AsyncCallback\): void + +Obtains the preferred network. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\<[PreferredNetworkMode](#preferrednetworkmode8)\> | Yes | Callback used to return the result. | + +**Example** + +```js +radio.getPreferredNetwork(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.getPreferredNetwork8+ + +getPreferredNetwork(slotId: number): Promise + +Obtains the preferred network. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +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)}`); +}); +``` + ## RadioTechnology -Enumerates the RAT. +Enumerates radio access technologies. **System capability**: SystemCapability.Telephony.CoreService @@ -1010,3 +1699,238 @@ Enumerates network selection modes. | NETWORK_SELECTION_UNKNOWN | 0 | Unknown network selection mode.| | NETWORK_SELECTION_AUTOMATIC | 1 | Automatic network selection mode.| | NETWORK_SELECTION_MANUAL | 2 | Manual network selection mode.| + +## PreferredNetworkMode8+ + +Enumerates preferred network modes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| --------------------------------------------------------- | ---- | --------------------------------------------- | +| PREFERRED_NETWORK_MODE_GSM | 1 | GSM network mode. | +| PREFERRED_NETWORK_MODE_WCDMA | 2 | WCDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE | 3 | LTE network mode. | +| PREFERRED_NETWORK_MODE_LTE_WCDMA | 4 | LTE+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_WCDMA_GSM | 5 | LTE+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_WCDMA_GSM | 6 | WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_CDMA | 7 | CDMA network mode. | +| PREFERRED_NETWORK_MODE_EVDO | 8 | EVDO network mode. | +| PREFERRED_NETWORK_MODE_EVDO_CDMA | 9 | EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_WCDMA_GSM_EVDO_CDMA | 10 | WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_EVDO_CDMA | 11 | LTE+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_WCDMA_GSM_EVDO_CDMA | 12 | LTE+WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA | 13 | TD-SCDMA network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA_GSM | 14 | TD-SCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA_WCDMA | 15 | TD-SCDMA+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA_WCDMA_GSM | 16 | TD-SCDMA+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA | 17 | LTE+TD-SCDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA_GSM | 18 | LTE+TD-SCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA_WCDMA | 19 | LTE+TD-SCDMA+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA_WCDMA_GSM | 20 | LTE+TD-SCDMA+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_TDSCDMA_WCDMA_GSM_EVDO_CDMA | 21 | TD-SCDMA+WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_LTE_TDSCDMA_WCDMA_GSM_EVDO_CDMA | 22 | LTE+TD-SCDMA+WCDMA+GSM+EVDO+CDMA network mode.| +| PREFERRED_NETWORK_MODE_NR | 31 | NR network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE | 32 | NR+LTE network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_WCDMA | 33 | NR+LTE+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_WCDMA_GSM | 34 | NR+LTE+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_EVDO_CDMA | 35 | NR+LTE+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_WCDMA_GSM_EVDO_CDMA | 36 | NR+LTE+WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA | 37 | NR+LTE+TD-SCDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_GSM | 38 | NR+LTE+TD-SCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA | 39 | NR+LTE+TD-SCDMA+WCDMA network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA_GSM | 40 | NR+LTE+TD-SCDMA+WCDMA+GSM network mode. | +| PREFERRED_NETWORK_MODE_NR_LTE_TDSCDMA_WCDMA_GSM_EVDO_CDMA | 41 | NR+LTE+TD-SCDMA+WCDMA+GSM+EVDO+CDMA network mode. | +| PREFERRED_NETWORK_MODE_MAX_VALUE | 99 | Maximum value of the preferred network mode. | + +## CellInformation8+ + +Defines the cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| networkType | [NetworkType](#networkType) | Network type of the cell. | +| isCamped | boolean | Status of the cell. | +| timeStamp | number | Timestamp when cell information is obtained. | +| signalInformation | [SignalInformation](#signalinformation) | Signal information. | +| data | [CdmaCellInformation](#cdmacellinformation) \| [GsmCellInformation](#gsmcellinformation) \| [LteCellInformation](#ltecellinformation) \| [NrCellInformation](#nrcellinformation) \| [TdscdmaCellInformation](#tdscdmacellinformation) | CDMA cell information \| GSM cell information \| LTE cell information \| NR cell information \| TD-SCDMA cell information | + +## CdmaCellInformation8+ + +Defines the CDMA cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| --------- | ------ | ------------ | +| baseId | number | Base station ID. | +| latitude | number | Longitude. | +| longitude | number | Latitude. | +| nid | number | Network ID.| +| sid | number | System ID.| + +## GsmCellInformation8+ + +Defines the GSM cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------ | ------ | -------------------- | +| lac | number | Location area code. | +| cellId | number | Cell ID. | +| arfcn | number | Absolute radio frequency channel number.| +| bsic | number | Base station ID. | +| mcc | string | Mobile country code. | +| mnc | string | Mobile network code. | + +## LteCellInformation8+ + +Defines the LTE cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------------- | ------- | ----------------------- | +| cgi | number | Cell global identification. | +| pci | number | Physical cell ID. | +| tac | number | Tracking area code. | +| earfcn | number | Absolute radio frequency channel number. | +| bandwidth | number | Bandwidth. | +| mcc | string | Mobile country code. | +| mnc | string | Mobile network code. | +| isSupportEndc | boolean | Support New Radio_Dual Connectivity| + +## NrCellInformation8+ + +Defines the NR cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------- | ------ | ---------------- | +| nrArfcn | number | 5G frequency number. | +| pci | number | Physical cell ID. | +| tac | number | Tracking area code. | +| nci | number | 5G network cell ID.| +| mcc | string | Mobile country code. | +| mnc | string | Mobile network code. | + +## TdscdmaCellInformation8+ + +Defines the TD-SCDMA cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------ | ------ | ------------ | +| lac | number | Location area code.| +| cellId | number | Cell ID. | +| cpid | number | Cell parameter ID.| +| uarfcn | number | Absolute radio frequency number.| +| mcc | string | Mobile country code.| +| mnc | string | Mobile network code. | + +## WcdmaCellInformation8+ + +Defines the WCDMA cell information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------ | ------ | ------------ | +| lac | number | Location area code.| +| cellId | number | Cell ID. | +| psc | number | Primary scrambling code. | +| uarfcn | number | Absolute radio frequency number.| +| mcc | string | Mobile country code.| +| mnc | string | Mobile network code. | + +## NrOptionMode8+ + +Enumerates NR selection modes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -------------------- | ---- | ---------------------------------- | +| NR_OPTION_UNKNOWN | 0 | Unknown NR selection mode. | +| NR_OPTION_NSA_ONLY | 1 | NR selection mode in 5G non-standalone networking. | +| NR_OPTION_SA_ONLY | 2 | NR selection mode in 5G standalone networking. | +| NR_OPTION_NSA_AND_SA | 3 | NR selection mode in non-standalone and standalone networking.| + +## NetworkSearchResult + +Defines the network search result. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ---------------------- | ------------------------------------------------- | -------------- | +| isNetworkSearchSuccess | boolean | Successful network search.| +| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Network search result.| + +## NetworkInformation + +Defines the network information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| --------------- | ----------------------------------------- | -------------- | +| operatorName | string | Carrier name.| +| operatorNumeric | string | Carrier number. | +| state | [NetworkInformation](#networkinformationstate) | Network information status.| +| radioTech | string | Radio technology. | + +## NetworkInformationState + +Enumerates network information states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| ----------------- | ---- | ---------------- | +| NETWORK_UNKNOWN | 0 | Unknown state. | +| NETWORK_AVAILABLE | 1 | Available for registration.| +| NETWORK_CURRENT | 2 | Registered state.| +| NETWORK_FORBIDDEN | 3 | Unavailable for registration. | + +## NetworkSelectionModeOptions + +Defines the network selection mode. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------------------ | --------------------------------------------- | -------------------------------------- | +| slotId | number | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| selectMode | [NetworkSelectionMode](#networkselectionmode) | Network selection mode. | +| networkInformation | [NetworkInformation](#networkinformation) | Network information. | +| resumeSelection | boolean | Whether to resume selection. | diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 50c50f574bbcad706077725e3b4c6f69f3334b1c..4f6da3208d7bef31f14e626a8fc09c57b5cb0423 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -17,9 +17,9 @@ import request from '@ohos.request'; ## Constraints -HTTPS is supported by default. To support HTTP, you need to add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. +HTTPS is supported by default in the FA model. To support HTTP, add **network** to the **config.json** file and set the **cleartextTraffic** attribute to **true**. -``` +```js var config = { "deviceConfig": { "default": { @@ -32,6 +32,9 @@ var config = { } ``` +The **cleartextTraffic** attribute is not involved during the development of applications in the stage model. + + ## Constants @@ -39,28 +42,28 @@ var config = { **System capability**: SystemCapability.MiscServices.Download -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| NETWORK_MOBILE | number | Yes | No | Whether download is allowed when the cellular network is used. | -| NETWORK_WIFI | number | Yes | No | Whether download is allowed on a WLAN. | -| ERROR_CANNOT_RESUME7+ | number | Yes | No | Failure to resume the download due to an error. | -| ERROR_DEVICE_NOT_FOUND7+ | number | Yes | No | Failure to find a storage device such as a memory card. | -| ERROR_FILE_ALREADY_EXISTS7+ | number | Yes | No | Failure to download the file because it already exists. | -| ERROR_FILE_ERROR7+ | number | Yes | No | File operation failure. | -| ERROR_HTTP_DATA_ERROR7+ | number | Yes | No | HTTP transmission failure. | -| ERROR_INSUFFICIENT_SPACE7+ | number | Yes | No | Insufficient storage space. | -| ERROR_TOO_MANY_REDIRECTS7+ | number | Yes | No | Error caused by too many network redirections. | -| ERROR_UNHANDLED_HTTP_CODE7+ | number | Yes | No | Unidentified HTTP code. | -| ERROR_UNKNOWN7+ | number | Yes | No | Unknown error. | -| PAUSED_QUEUED_FOR_WIFI7+ | number | Yes | No | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a cellular network session. | -| PAUSED_UNKNOWN7+ | number | Yes | No | Download paused due to unknown reasons. | -| PAUSED_WAITING_FOR_NETWORK7+ | number | Yes | No | Download paused due to a network connection problem, for example, network disconnection. | -| PAUSED_WAITING_TO_RETRY7+ | number | Yes | No | Download paused and then retried. | -| SESSION_FAILED7+ | number | Yes | No | Download failure without retry. | -| SESSION_PAUSED7+ | number | Yes | No | Download paused. | -| SESSION_PENDING7+ | number | Yes | No | Download pending. | -| SESSION_RUNNING7+ | number | Yes | No | Download in progress. | -| SESSION_SUCCESSFUL7+ | number | Yes | No | Successful download. | +| NETWORK_MOBILE | number | Yes| No| Whether download is allowed on a mobile network.| +| NETWORK_WIFI | number | Yes| No| Whether download is allowed on a WLAN.| +| ERROR_CANNOT_RESUME7+ | number | Yes| No| Failure to resume the download due to an error.| +| ERROR_DEVICE_NOT_FOUND7+ | number | Yes| No| Failure to find a storage device such as a memory card.| +| ERROR_FILE_ALREADY_EXISTS7+ | number | Yes| No| Failure to download the file because it already exists.| +| ERROR_FILE_ERROR7+ | number | Yes| No| File operation failure.| +| ERROR_HTTP_DATA_ERROR7+ | number | Yes| No| HTTP transmission failure.| +| ERROR_INSUFFICIENT_SPACE7+ | number | Yes| No| Insufficient storage space.| +| ERROR_TOO_MANY_REDIRECTS7+ | number | Yes| No| Error caused by too many network redirections.| +| ERROR_UNHANDLED_HTTP_CODE7+ | number | Yes| No| Unidentified HTTP code.| +| ERROR_UNKNOWN7+ | number | Yes| No| Unknown error.| +| PAUSED_QUEUED_FOR_WIFI7+ | number | Yes| No| Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.| +| PAUSED_UNKNOWN7+ | number | Yes| No| Download paused due to unknown reasons.| +| PAUSED_WAITING_FOR_NETWORK7+ | number | Yes| No| Download paused due to a network connection problem, for example, network disconnection.| +| PAUSED_WAITING_TO_RETRY7+ | number | Yes| No| Download paused and then retried.| +| SESSION_FAILED7+ | number | Yes| No| Download failure without retry.| +| SESSION_PAUSED7+ | number | Yes| No| Download paused.| +| SESSION_PENDING7+ | number | Yes| No| Download pending.| +| SESSION_RUNNING7+ | number | Yes| No| Download in progress.| +| SESSION_SUCCESSFUL7+ | number | Yes| No| Successful download.| ## request.upload @@ -69,30 +72,36 @@ upload(config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. +This API can be used only in the FA model. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| config | [UploadConfig](#uploadconfig) | Yes | Configurations of the upload. | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object. | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Example** ```js - let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; - let data = { name: "name123", value: "123" }; - let header = { key1: "value1", key2: "value2" }; let uploadTask; - request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }).then((data) => { + let uploadConfig = { + url: 'https://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + request.upload(uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); @@ -106,25 +115,31 @@ upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. +This API can be used only in the FA model. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| config | [UploadConfig](#uploadconfig) | Yes | Configurations of the upload. | -| callback | AsyncCallback<[UploadTask](#uploadtask)> | No | Callback used to return the **UploadTask** object. | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | No| Callback used to return the **UploadTask** object.| **Example** ```js - let file1 = { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }; - let data = { name: "name123", value: "123" }; - let header = { key1: "value1", key2: "value2" }; let uploadTask; - request.upload({ url: 'https://patch', header: header, method: "POST", files: [file1], data: [data] }, (err, data) => { + let uploadConfig = { + url: 'https://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + request.upload(uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -132,8 +147,87 @@ Uploads files. This API uses an asynchronous callback to return the result. uploadTask = data; }); ``` +## request.upload9+ + +upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> + +Uploads files. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | BaseContext | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| + +**Example** + + ```js + let uploadTask; + let uploadConfig = { + url: 'https://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: { filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }, + data: { name: "name123", value: "123" }, + }; + request.upload(globalThis.abilityContext, uploadConfig).then((data) => { + uploadTask = data; + }).catch((err) => { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + }); + ``` +## request.upload9+ + +upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void + +Uploads files. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Upload + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | BaseContext | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | No| Callback used to return the **UploadTask** object.| + +**Example** + + ```js + let uploadTask; + let uploadConfig = { + url: 'https://patch', + header: { key1: "value1", key2: "value2" }, + method: "POST", + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + }; + request.upload(globalThis.abilityContext, uploadConfig, (err, data) => { + if (err) { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + return; + } + uploadTask = data; + }); + ``` + ## UploadTask Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object. @@ -143,7 +237,7 @@ Implements file uploads. Before using any APIs of this class, you must obtain an on(type: 'progress', callback:(uploadedSize: number, totalSize: number) => void): void -Subscribes to the upload progress event. This API uses an asynchronous callback to return the result. +Subscribes to an upload event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -151,17 +245,17 @@ Subscribes to the upload progress event. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **progress** (upload progress). | -| callback | function | Yes | Callback for the upload progress event. | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| +| callback | function | Yes| Callback for the upload progress event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes | Size of the uploaded files, in KB. | -| totalSize | number | Yes | Total size of the files to upload, in KB. | +| uploadedSize | number | Yes| Size of the uploaded files, in KB.| +| totalSize | number | Yes| Total size of the files to upload, in KB.| **Example** @@ -177,7 +271,7 @@ Subscribes to the upload progress event. This API uses an asynchronous callback on(type: 'headerReceive', callback: (header: object) => void): void -Subscribes to the **headerReceive** event, which is triggered when an HTTP response header is received. This API uses an asynchronous callback to return the result. +Subscribes to an upload event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -185,16 +279,16 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **'headerReceive'** (response header). | -| callback | function | Yes | Callback for the HTTP Response Header event. | +| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| +| callback | function | Yes| Callback for the HTTP Response Header event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| header | object | Yes | HTTP Response Header. | +| header | object | Yes| HTTP Response Header.| **Example** @@ -210,7 +304,7 @@ Subscribes to the **headerReceive** event, which is triggered when an HTTP respo off(type: 'progress', callback?: (uploadedSize: number, totalSize: number) => void): void -Unsubscribes from the upload progress event. This API uses an asynchronous callback to return the result. +Unsubscribes from an upload event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -218,17 +312,17 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (upload progress). | -| callback | function | No | Callback for the upload progress event. | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| +| callback | function | No| Callback for the upload progress event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes | Size of the uploaded files, in KB. | -| totalSize | number | Yes | Total size of the files to upload, in KB. | +| uploadedSize | number | Yes| Size of the uploaded files, in KB.| +| totalSize | number | Yes| Total size of the files to upload, in KB.| **Example** @@ -244,7 +338,7 @@ Unsubscribes from the upload progress event. This API uses an asynchronous callb off(type: 'headerReceive', callback?: (header: object) => void): void -Unsubscribes from the **headerReceive** event. This API uses an asynchronous callback to return the result. +Unsubscribes from an upload event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -252,16 +346,16 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **'headerReceive'** (response header). | -| callback | function | No | Callback for the HTTP Response Header event. | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| +| callback | function | No| Callback for the HTTP Response Header event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| header | object | Yes | HTTP Response Header. | +| header | object | Yes| HTTP Response Header.| **Example** @@ -277,7 +371,7 @@ Unsubscribes from the **headerReceive** event. This API uses an asynchronous cal remove(): Promise<boolean> -Removes this upload task. This API uses a promise to return the result. +Removes this upload task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -285,9 +379,9 @@ Removes this upload task. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return the task removal result. If **true** is returned, the task is removed. If **false** is returned, the task fails to be removed. | +| Promise<boolean> | Promise used to return the task removal result. If **true** is returned, the task is removed. If **false** is returned, the task fails to be removed.| **Example** @@ -308,7 +402,7 @@ Removes this upload task. This API uses a promise to return the result. remove(callback: AsyncCallback<boolean>): void -Removes this upload task. This API uses an asynchronous callback to return the result. +Removes this upload task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -316,9 +410,9 @@ Removes this upload task. This API uses an asynchronous callback to return the r **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** @@ -339,37 +433,42 @@ Removes this upload task. This API uses an asynchronous callback to return the r ## UploadConfig +**Required permissions**: ohos.permission.INTERNET + **System capability**: SystemCapability.MiscServices.Upload -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| url | string | Yes | Resource URL. | -| header | object | Yes | HTTP or HTTPS header added to an upload request. | -| method | string | Yes | Request method, which can be **POST** or **PUT**. The default value is **POST**. | -| files | Array<[File](#file)> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | -| data | Array<[RequestData](#requestdata)> | Yes | Form data in the request body. | +| url | string | Yes| Resource URL.| +| header | object | Yes| HTTP or HTTPS header added to an upload request.| +| method | string | Yes| Request method, which can be **'POST'** or **'PUT'**. The default value is **'POST'**.| +| files | Array<[File](#file)> | Yes| List of files to upload, which is submitted through **multipart/form-data**.| +| data | Array<[RequestData](#requestdata)> | Yes| Form data in the request body.| ## File -**System capability**: SystemCapability.MiscServices.Upload +**Required permissions**: ohos.permission.INTERNET -| Name | Type | Mandatory | Description | +**System capability**: SystemCapability.MiscServices.Download + +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| filename | string | No | File name in the header when **multipart** is used. | -| name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | -| uri | string | Yes | Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | -| type | string | No | Type of the file content. By default, the type is obtained based on the extension of the file name or URI. | +| filename | string | No| File name in the header when **multipart** is used.| +| name | string | No| Name of a form item when **multipart** is used. The default value is **file**.| +| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt

internal://cache/path/to/file.txt | +| type | string | No| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| ## RequestData -**System capability**: SystemCapability.MiscServices.Upload +**Required permissions**: ohos.permission.INTERNET -| Name | Type | Mandatory | Description | +**System capability**: SystemCapability.MiscServices.Download +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes | Name of a form element. | -| value | string | Yes | Value of a form element. | +| name | string | Yes| Name of a form element.| +| value | string | Yes| Value of a form element.| ## request.download @@ -378,21 +477,23 @@ download(config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. +This API can be used only in the FA model. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| config | [DownloadConfig](#downloadconfig) | Yes | Configurations of the download. | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result. | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Example** @@ -412,16 +513,18 @@ download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): v Downloads files. This API uses an asynchronous callback to return the result. +This API can be used only in the FA model. + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| config | [DownloadConfig](#downloadconfig) | Yes | Configurations of the download. | -| callback | AsyncCallback<[DownloadTask](#downloadtask)> | No | Callback used to return the result. | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | No| Callback used to return the result.| **Example** @@ -437,7 +540,72 @@ Downloads files. This API uses an asynchronous callback to return the result. }); ``` +## request.download9+ + +download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> + +Downloads files. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | BaseContext | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| + +**Example** + + ```js + let downloadTask; + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + downloadTask = data; + }).catch((err) => { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + }) + ``` + + +## request.download9+ +download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; + +Downloads files. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | BaseContext | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | No| Callback used to return the result.| + +**Example** + + ```js + let downloadTask; + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + filePath: 'xxx/xxxxx.hap'}, (err, data) => { + if (err) { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + return; + } + downloadTask = data; + }); + ``` ## DownloadTask Implements file downloads. @@ -447,7 +615,7 @@ Implements file downloads. on(type: 'progress', callback:(receivedSize: number, totalSize: number) => void): void -Subscribes to the download progress event. This API uses an asynchronous callback to return the result. +Subscribes to a download event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -455,17 +623,17 @@ Subscribes to the download progress event. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to subscribe to. The value is **'progress'** (download progress). | -| callback | function | Yes | Callback for the download progress event. | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| +| callback | function | Yes| Callback for the download progress event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| receivedSize | number | Yes | Size of the downloaded files, in KB. | -| totalSize | number | Yes | Total size of the files to download, in KB. | +| receivedSize | number | Yes| Size of the downloaded files, in KB.| +| totalSize | number | Yes| Total size of the files to download, in KB.| **Example** @@ -481,7 +649,7 @@ Subscribes to the download progress event. This API uses an asynchronous callbac off(type: 'progress', callback?: (receivedSize: number, totalSize: number) => void): void -Unsubscribes from the download progress event. This API uses an asynchronous callback to return the result. +Unsubscribes from a download event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -489,17 +657,17 @@ Unsubscribes from the download progress event. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **'progress'** (download progress). | -| callback | function | No | Callback for the download progress event. | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| +| callback | function | No| Callback for the download progress event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| receivedSize | number | Yes | Size of the downloaded files, in KB. | -| totalSize | number | Yes | Total size of the files to download, in KB. | +| receivedSize | number | Yes| Size of the downloaded files.| +| totalSize | number | Yes| Total size of the files to download.| **Example** @@ -523,10 +691,10 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Event type.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event. | -| callback | function | Yes | Callback used to return the result. | +| type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | Yes| Callback used to return the result.| **Example** @@ -542,7 +710,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return off(type: 'complete'|'pause'|'remove', callback?:() => void): void -Unsubscribes from the download event. This API uses an asynchronous callback to return the result. +Unsubscribes from a download event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -550,10 +718,10 @@ Unsubscribes from the download event. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Event type.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event. | -| callback | function | No | Callback used to return the result. | +| type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | No| Callback used to return the result.| **Example** @@ -577,16 +745,16 @@ Subscribes to the download task failure event. This API uses an asynchronous cal **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the subscribed event. The value is **'fail'** (download failure). | -| callback | function | Yes | Callback for the download task failure event. | +| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| +| callback | function | Yes| Callback for the download task failure event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| err | number | Yes | Error code of the download failure. For details about the error cause, see [ERROR_*](#constants). | +| err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| **Example** @@ -602,7 +770,7 @@ Subscribes to the download task failure event. This API uses an asynchronous cal off(type: 'fail', callback?: (err: number) => void): void -Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result. +Unsubscribes from the download task failure event. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -610,16 +778,16 @@ Unsubscribes from the download task failure event. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Type of the event to unsubscribe from. The value is **'fail'** (download failure). | -| callback | function | No | Callback for the download task failure event. | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| +| callback | function | No| Callback for the download task failure event.| -**callback** parameters +Parameters of the callback function -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| err | number | Yes | Error code of the download failure. For details about the error cause, see [ERROR_*](#constants). | +| err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| **Example** @@ -643,9 +811,9 @@ Removes this download task. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return the task removal result. | +| Promise<boolean> | Promise used to return the task removal result.| **Example** @@ -674,9 +842,9 @@ Removes this download task. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the task removal result. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| **Example** @@ -706,10 +874,9 @@ Queries this download task. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Download **Parameters** - -| Type | Description | -| -------- | -------- | -| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information. | + | Type| Description| + | -------- | -------- | + | Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| **Example** @@ -734,9 +901,9 @@ Queries this download task. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes | Callback used to return the download task information. | +| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| **Example** @@ -755,7 +922,7 @@ Queries this download task. This API uses an asynchronous callback to return the queryMimeType(): Promise<string> -Queries **MimeType** of this download task. This API uses a promise to return the result. +Queries the **MimeType** of this download task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -763,9 +930,9 @@ Queries **MimeType** of this download task. This API uses a promise to return th **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<string> | Promise used to return **MimeType** of the download task. | +| Promise<string> | Promise used to return the **MimeType** of the download task.| **Example** @@ -782,7 +949,7 @@ Queries **MimeType** of this download task. This API uses a promise to return th queryMimeType(callback: AsyncCallback<string>): void; -Queries **MimeType** of this download task. This API uses an asynchronous callback to return the result. +Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -790,9 +957,9 @@ Queries **MimeType** of this download task. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<string> | Yes | Callback used to return **MimeType** of the download task. | +| callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| **Example** @@ -819,9 +986,9 @@ Pauses this download task. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the download task pause result. | +| Promise<void> | Promise used to return the download task pause result.| **Example** @@ -850,9 +1017,9 @@ Pauses this download task. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -883,9 +1050,9 @@ Resumes this download task. This API uses a promise to return the result. **Parameters** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. | +| Promise<void> | Promise used to return the result.| **Example** @@ -915,9 +1082,9 @@ Resumes this download task. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** @@ -938,34 +1105,39 @@ Resumes this download task. This API uses an asynchronous callback to return the ## DownloadConfig +**Required permissions**: ohos.permission.INTERNET + **System capability**: SystemCapability.MiscServices.Download -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| url | string | Yes | Resource URL. | -| header | object | No | HTTP or HTTPS header added to a download request. | -| enableMetered | boolean | No | Download allowed in metered connections. | -| enableRoaming | boolean | No | Download allowed on a roaming network. | -| description | string | No | Description of the download session. | -| filePath7+ | string | No | Download path. (The default path is **'internal://cache/'**.
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files. | -| networkType | number | No | Network type allowed for download. | -| title | string | No | Title of the download session. | +| url | string | Yes| Resource URL.| +| header | object | No| HTTP or HTTPS header added to a download request.| +| enableMetered | boolean | No| Whether download is allowed on a metered connection.
- **true**: yes
**false**: no| +| enableRoaming | boolean | No| Whether download is allowed on a roaming network.
- **true**: yes
**false**: no| +| description | string | No| Description of the download session.| +| filePath7+ | string | No| Download path. (The default path is **'internal://cache/'**.)
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files.| +| networkType | number | No| Network type allowed for download.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| +| title | string | No| Title of the download session.| +| background | boolean | No| Whether to enable the background task notification. When this parameter is enabled, the download status is displayed in the notification panel.| ## DownloadInfo7+ +**Required permissions**: ohos.permission.INTERNET + **System capability**: SystemCapability.MiscServices.Download -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| downloadId | number | Yes | ID of the downloaded file. | -| failedReason | number | No | Download failure cause, which can be any constant of [ERROR_*](#constants). | -| fileName | string | Yes | Name of the downloaded file. | -| filePath | string | Yes | URI of the saved file. | -| pausedReason | number | No | Reason for session pause, which can be any constant of [PAUSED_*](#constants). | -| status | number | Yes | Download status code, which can be any constant of [SESSION_*](#constants). | -| targetURI | string | Yes | URI of the downloaded file. | -| downloadTitle | string | Yes | Title of the downloaded file. | -| downloadTotalBytes | number | Yes | Total size of the downloaded file (int bytes). | -| description | string | Yes | Description of the file to download. | -| downloadedBytes | number | Yes | Size of the files downloaded (int bytes). | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| downloadId | number | Yes| ID of the downloaded file.| +| failedReason | number | No| Download failure cause, which can be any constant of [ERROR_*](#constants).| +| fileName | string | Yes| Name of the downloaded file.| +| filePath | string | Yes| URI of the saved file.| +| pausedReason | number | No| Reason for session pause, which can be any constant of [PAUSED_*](#constants).| +| status | number | Yes| Download status code, which can be any constant of [SESSION_*](#constants).| +| targetURI | string | Yes| URI of the downloaded file.| +| downloadTitle | string | Yes| Title of the downloaded file.| +| downloadTotalBytes | number | Yes| Total size of the files to download (int bytes).| +| description | string | Yes| Description of the file to download.| +| downloadedBytes | number | Yes| Size of the files downloaded (int bytes).| diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 7f83f0250c209dbd6b5d57970fe7beb8d9b9a494..8f88d00f0d246628e3669ae376da04191efedb92 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -68,29 +68,30 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | options | [ScreenshotOptions](#screenshotoptions) | No | Screenshot settings consist of **screenRect**, **imageSize**, **rotation**, and **displayId**. You can set the parameters separately.| -| callback | AsyncCallback<image.PixelMap> | Yes | Callback used to return a **PixelMap** object. | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return a **PixelMap** object. | **Example** ```js - var ScreenshotOptions = { - "screenRect": { - "left": 200, - "top": 100, - "width": 200, - "height": 200}, - "imageSize": { - "width": 300, - "height": 300}, - "rotation": 0, - "displayId": 0 + var screenshotOptions = { + "screenRect": { + "left": 200, + "top": 100, + "width": 200, + "height": 200}, + "imageSize": { + "width": 300, + "height": 300}, + "rotation": 0, + "displayId": 0 }; - screenshot.save(ScreenshotOptions, (err, data) => { - if (err) { - console.error('Failed to save the screenshot. Error: ' + JSON.stringify(err)); - return; - } - console.info('Screenshot saved. Data: ' + JSON.stringify(data)); + screenshot.save(screenshotOptions, (err, pixelMap) => { + if (err) { + console.log('Failed to save screenshot: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. }); ``` @@ -114,12 +115,12 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis | Type | Description | | ----------------------------- | ----------------------------------------------- | -| Promise<image.PixelMap> | Promise used to return a **PixelMap** object.| +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return a **PixelMap** object.| **Example** ```js - var ScreenshotOptions = { + var screenshotOptions = { "screenRect": { "left": 200, "top": 100, @@ -131,10 +132,11 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis "rotation": 0, "displayId": 0 }; - let promise = screenshot.save(ScreenshotOptions); - promise.then(() => { - console.log('screenshot save success'); + let promise = screenshot.save(screenshotOptions); + promise.then((pixelMap) => { + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. }).catch((err) => { - console.log('screenshot save fail: ' + JSON.stringify(err)); + console.log('Failed to save screenshot: ' + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-service-extension-ability.md b/en/application-dev/reference/apis/js-apis-service-extension-ability.md index 388657b05dce3f05601cc88123ff2d64adbf127b..388b4308555f8dc061bfa62da40fd4dc5d97cfee 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-ability.md +++ b/en/application-dev/reference/apis/js-apis-service-extension-ability.md @@ -23,9 +23,9 @@ None. **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate @@ -40,9 +40,9 @@ Called when a Service Extension ability is created to initialize the service log **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -88,10 +88,10 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| -| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** @@ -116,15 +116,15 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Return value** -| Type| Description| -| -------- | -------- | -| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| + | Type| Description| + | -------- | -------- | + | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| **Example** @@ -158,9 +158,9 @@ Called when this Service Extension ability is disconnected. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Example** @@ -184,16 +184,16 @@ Called when this Service Extension ability is reconnected. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| **Example** ```js class ServiceExt extends ServiceExtension { - onDisconnect(want) { - console.log('onDisconnect, want:' + want.abilityName); + onReconnect(want) { + console.log('onReconnect, want:' + want.abilityName); } } ``` @@ -202,7 +202,7 @@ Called when this Service Extension ability is reconnected. onConfigurationUpdated(config: Configuration): void; -Called when the configuration of this Service Extension ability is updated. + Called when the configuration of this Service Extension ability is updated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -210,9 +210,9 @@ Called when the configuration of this Service Extension ability is updated. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| **Example** @@ -236,9 +236,9 @@ Dumps the client information. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| params | Array\ | Yes| Parameters in the form of a command.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | params | Array\ | Yes| Parameters in the form of a command.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md index 241a8bf17f94a3362fe6d12d4662b139c4c4cd8b..cb56fdccb85fd5aa96e161df2f86fbc1a5573b2d 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 @@ -26,7 +26,7 @@ Before using the **ServiceExtensionContext** module, you must define a child cla startAbility(want: Want, callback: AsyncCallback<void>): void; -Starts an ability. This API uses a callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -36,8 +36,8 @@ Starts an ability. This API uses a callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| - | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the API is successfully called.| + | want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Example** @@ -64,14 +64,14 @@ Starts an ability. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| + | want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -92,7 +92,7 @@ Starts an ability. This API uses a promise to return the result. startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void -Starts an ability. This API uses a callback to return the result. +Starts an ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -102,7 +102,7 @@ Starts an ability. This API uses a callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| @@ -136,8 +136,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -169,8 +169,8 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -206,10 +206,16 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + **Example** ```js @@ -245,7 +251,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -275,7 +281,13 @@ Starts a new Service Extension ability. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -310,8 +322,8 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -344,8 +356,14 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -369,7 +387,7 @@ Starts a new Service Extension ability with the account ID specified. This API u stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops Service Extension abilities in the same application. This API uses an asynchronous callback to return the result. +Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -379,7 +397,7 @@ Stops Service Extension abilities in the same application. This API uses an asyn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -399,7 +417,7 @@ Stops Service Extension abilities in the same application. This API uses an asyn stopServiceExtensionAbility(want: Want): Promise\; -Stops Service Extension abilities in the same application. This API uses a promise to return the result. +Stops a Service Extension ability in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -409,7 +427,13 @@ Stops Service Extension abilities in the same application. This API uses a promi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -432,7 +456,7 @@ Stops Service Extension abilities in the same application. This API uses a promi stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops Service Extension abilities in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -444,8 +468,8 @@ Stops Service Extension abilities in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -466,7 +490,7 @@ Stops Service Extension abilities in the same application with the account ID sp stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops Service Extension abilities in the same application with the account ID specified. This API uses a promise to return the result. +Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS @@ -478,8 +502,14 @@ Stops Service Extension abilities in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| **Example** @@ -503,7 +533,7 @@ Stops Service Extension abilities in the same application with the account ID sp terminateSelf(callback: AsyncCallback<void>): void; -Terminates this ability. This API uses a callback to return the result. +Terminates this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -513,7 +543,7 @@ Terminates this ability. This API uses a callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the API is successfully called.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Example** @@ -537,7 +567,7 @@ Terminates this ability. This API uses a promise to return the result. | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -563,7 +593,7 @@ Connects this ability to a Service ability. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to connect to, such as the ability name and bundle name.| + | want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| | options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| **Return value** @@ -601,8 +631,8 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the **Want** used for starting an ability.| -| accountId | number | Yes| ID of the account.| +| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | options | ConnectOptions | No| Remote object instance.| **Return value** @@ -633,7 +663,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect disconnectAbility(connection: number, callback:AsyncCallback<void>): void; -Disconnects this ability from the Service ability. This API uses a callback to return the result. +Disconnects this ability from the Service ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -644,7 +674,7 @@ Disconnects this ability from the Service ability. This API uses a callback to r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | connection | number | Yes| Number returned after **connectAbility** is called.| - | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the API is successfully called.| + | callback | AsyncCallback<void> | No| Callback used to return the result.| **Example** @@ -676,7 +706,7 @@ Disconnects this ability from the Service ability. This API uses a promise to re | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result indicating whether the API is successfully called.| + | Promise<void> | Promise used to return the result.| **Example** @@ -689,3 +719,41 @@ Disconnects this ability from the Service ability. This API uses a promise to re console.log('failed:' + JSON.stringify(error)); }); ``` + +## ServiceExtensionContext.startAbilityByCall + +startAbilityByCall(want: Want): Promise<Caller>; + +Starts an ability in the background and obtains the caller interface for communication. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**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.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Caller> | Promise used to return the caller object to communicate with.| + +**Example** + + ```js + let caller = undefined; + this.context.startAbilityByCall({ + 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); + }); + ``` + diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index a546ee0cc3fc95d286b1f2a835998426372c874a..3cb8380f9f35b7fa584f09b0d88c5fb45e0c22fe 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,6 +1,6 @@ # Settings -This module provides APIs for setting data items. +The **Settings** module provides APIs for setting data items. > **NOTE** > @@ -21,7 +21,7 @@ getUriSync(name: string): string Obtains the URI of a data item. -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** @@ -50,7 +50,7 @@ getValueSync(dataAbilityHelper: DataAbilityHelper, name: string, defValue: strin Obtains the value of a data item. -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** | Name| Type| Mandatory| Description| @@ -87,7 +87,7 @@ If the specified data item exists in the database, the **setValueSync** method u **Required permissions**: ohos.permission.MODIFY_SETTINGS -**System capability**: SystemCapability.Applictaions.settings.Core +**System capability**: SystemCapability.Applications.settings.Core **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 41a4cfc71c77ff92c77b4b16ed19de9af6395bd3..958de3d7d1bb9d7295bedac1c844867160d687ca 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -144,7 +144,7 @@ sim.hasOperatorPrivileges(0, (err, data) => { hasOperatorPrivileges(slotId: number): Promise -Checks whether the application (caller) has been granted the operator permission. This API uses a promise to return the result. +Checks whether the application (caller) has been granted the carrier permission. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -158,7 +158,7 @@ Checks whether the application (caller) has been granted the operator permission | Type | Description | | :----------------- | :---------------------------------------------------------- | -| Promise\ | Promise used to return the result. The value **true** indicates that the application (caller) has been granted the operator permission, and the value **false** indicates the opposite.| +| Promise\ | Promise used to return the result. The value **true** indicates that the application (caller) has been granted the carrier permission, and the value **false** indicates the opposite.| **Example** @@ -184,7 +184,7 @@ Obtains the ISO country code of the SIM card in the specified slot. This API use | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ---------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result, which is an ISO country code, for example, **CN** (China).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. which is an ISO country code, for example, **CN** (China).| **Example** @@ -467,7 +467,7 @@ Checks whether the SIM card in the specified slot is installed. This API uses an **Example** -```jsjs +```js sim.hasSimCard(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -522,7 +522,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[IccAccountInfo](#IccAccountInfo7)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[IccAccountInfo](#iccaccountinfo7)\> | Yes | Callback used to return the result. | **Example** @@ -555,7 +555,7 @@ This is a system API. | Type | Description | | -------------------------------------------- | ------------------------------------------ | -| Promise<[IccAccountInfo](#IccAccountInfo7)\> | Promise used to return the result.| +| Promise<[IccAccountInfo](#iccaccountinfo7)\> | Promise used to return the result.| **Example** @@ -584,7 +584,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | ---------- | -| callback | AsyncCallback\\> | Yes | Callback used to return the result.| +| callback | AsyncCallback\\> | Yes | Callback used to return the result.| **Example** @@ -611,7 +611,7 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | ---------------------------------------------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** @@ -646,7 +646,7 @@ This is a system API. **Example** ```js -sim.setDefaultVoiceSlotId(0,(err, data) => { +sim.setDefaultVoiceSlotId(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -672,9 +672,9 @@ This is a system API. **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -711,7 +711,7 @@ This is a system API. ```js const name='China Mobile'; -sim.setShowName(0, name,(err, data) => { +sim.setShowName(0, name, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -737,15 +737,15 @@ This is a system API. **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** ```js const name='China Mobile'; -let promise = sim.setShowName(0,name); +let promise = sim.setShowName(0, name); promise.then(data => { console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -839,8 +839,8 @@ This is a system API. **Example** ```js -let number='+861xxxxxxxxxx'; -sim.setShowNumber(0, number,(err, data) => { +let number = '+861xxxxxxxxxx'; +sim.setShowNumber(0, number, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -869,13 +869,13 @@ This is a system API. | Type | Description | | -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Promise | Promise used to return the result.| **Example** ```js -let number='+861xxxxxxxxxx'; -let promise = sim.setShowNumber(0,number); +let number = '+861xxxxxxxxxx'; +let promise = sim.setShowNumber(0, number); promise.then(data => { console.log(`setShowNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -994,9 +994,9 @@ This is a system API. **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -1057,8 +1057,8 @@ This is a system API. **Return value** -| Type | Description | -| -------------- | ------------------------------- | +| Type | Description | +| --------------- | ------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -1089,16 +1089,18 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | -| options | [LockInfo](#LockInfo8) | Yes | Lock information.
- **lockType**: [LockType](#LockType8)
- **password**: string
- **state**: [LockState](#LockState8) | +| callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
lockType: [LockType](#locktype8)
password: string
state: [LockState](#lockstate8) | **Example** ```js -LockInfo.lockType = 1; -LockInfo.password = "1234"; -LockInfo.state = 0; -sim.setLockState(0, LockInfo, (err, data) => { +let lockInfo = { + lockType = 1, + password = "1234", + state = 0 +}; +sim.setLockState(0, lockInfo, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1121,21 +1123,23 @@ This is a system API. | Name | Type | Mandatory| Description | | ------- | ---------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| options | [LockInfo](#LockInfo8) | Yes | Lock information.
- **lockType**: [LockType](#LockType8)
**password**: string
**state**: [LockState](#LockState8) | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
lockType: [LockType](#locktype8)
password: string
state: [LockState](#lockstate8) | **Return value** | Type | Description | | ---------------------------------------------------- | -------------------------------------------- | -| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| +| Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -LockInfo.lockType = 1; -LockInfo.password = "1234"; -LockInfo.state = 0; -let promise = sim.setLockState(0, LockInfo); +let lockInfo = { + lockType = 1, + password = "1234", + state = 0 +}; +let promise = sim.setLockState(0, lockInfo); promise.then(data => { console.log(`setLockState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1158,8 +1162,8 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | --------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback\<[LockState](#LockState8)\> | Yes | Callback used to return the result. | -| options | [LockType](#LockType8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN2 lock| +| callback | AsyncCallback\<[LockState](#lockstate8)\> | Yes | Callback used to return the result. | +| options | [LockType](#locktype8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN 2 lock| **Example** @@ -1185,13 +1189,13 @@ This is a system API. | Name | Type | Mandatory| Description | | ------- | ---------------------- | ---- | --------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| options | [LockType](#LockType8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN2 lock| +| options | [LockType](#locktype8) | Yes | Lock type.
- **1**: PIN lock
- **2**: PIN 2 lock| **Return value** | Type | Description | | ---------------------------------- | -------------------------------------------- | -| Promise<[LockState](#LockState8)\> | Promise used to return the result.| +| Promise<[LockState](#lockstate8)\> | Promise used to return the result.| **Example** @@ -1208,7 +1212,7 @@ promise.then(data => { alterPin(slotId: number, newPin: string, oldPin: string, callback: AsyncCallback): void -Changes the PIN. This API uses an asynchronous callback to return the result. +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. @@ -1221,14 +1225,14 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | | newPin | string | Yes | New PIN. | | oldPin | string | Yes | Old PIN. | **Example** ```js -sim.alterPin(0, "1234", "0000"(err, data) => { +sim.alterPin(0, "1234", "0000", (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1238,7 +1242,7 @@ sim.alterPin(0, "1234", "0000"(err, data) => { alterPin(slotId: number, newPin: string, oldPin: string): Promise; -Changes the PIN. This API uses a promise to return the result. +Changes the PIN of the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1258,7 +1262,7 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | --------------------------------------------- | -| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| +| Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** @@ -1275,7 +1279,7 @@ promise.then(data => { alterPin2(slotId: number, newPin2: string, oldPin2: string, callback: AsyncCallback): void -Changes PIN 2. This API uses an asynchronous callback to return the result. +Changes PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1288,7 +1292,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| callback | AsyncCallback\<[LockStatusResponse](#LockStatusResponse7)\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | | newPin2 | string | Yes | New PIN. | | oldPin2 | string | Yes | Old PIN. | @@ -1305,7 +1309,7 @@ sim.alterPin2(0, "1234", "0000", (err, data) => { alterPin2(slotId: number, newPin2: string, oldPin2: string): Promise -Changes PIN 2. This API uses a promise to return the result. +Changes PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1325,12 +1329,12 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | --------------------------------------------- | -| Promise<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| +| Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -let promise = sim.alterPin2(0, "1234","0000"); +let promise = sim.alterPin2(0, "1234", "0000"); promise.then(data => { console.log(`alterPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1342,7 +1346,7 @@ promise.then(data => { unlockPin(slotId: number,pin: string ,callback: AsyncCallback): void -Unlocks the PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. +Unlocks PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1356,13 +1360,13 @@ This is a system API. | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | pin | string | Yes | PIN of the SIM card. | -| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | **Example** ```js -let pin='1234'; -sim.unlockPin(0, pin,(err, data) => { +let pin = '1234'; +sim.unlockPin(0, pin, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1391,13 +1395,13 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | -------------------------------------------------- | -| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| +| Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -let pin='1234'; -let promise = sim.unlockPin(0,pin); +let pin = '1234'; +let promise = sim.unlockPin(0, pin); promise.then(data => { console.log(`unlockPin success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1424,14 +1428,14 @@ This is a system API. | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | newPin | string | Yes | New PIN. | | puk | string | Yes | PUK of the SIM card. | -| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | **Example** ```js -let puk='1xxxxxxx'; -let newPin='1235'; -sim.unlockPuk(0, newPin,puk,(err, data) => { +let puk = '1xxxxxxx'; +let newPin = '1235'; +sim.unlockPuk(0, newPin, puk, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1461,14 +1465,14 @@ This is a system API. | Type | Description | | ---------------------------------------------------- | -------------------------------------------------- | -| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| +| Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -let puk='1xxxxxxx'; -let newPin='1235'; -let promise = sim.unlockPuk(0,newPin,puk); +let puk = '1xxxxxxx'; +let newPin = '1235'; +let promise = sim.unlockPuk(0, newPin, puk); promise.then(data => { console.log(`unlockPuk success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1493,14 +1497,14 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| pin2 | string | Yes | PIN of the SIM card. | -| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | +| pin2 | string | Yes | PIN 2 of the SIM card. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | **Example** ```js -let pin2='1234'; -sim.unlockPin2(0, pin2,(err, data) => { +let pin2 = '1234'; +sim.unlockPin2(0, pin2, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1523,13 +1527,13 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| pin2 | string | Yes | PIN of the SIM card. | +| pin2 | string | Yes | PIN 2 of the SIM card. | **Return value** | Type | Description | | ----------------------------------------------------- | -------------------------------------------------- | -| Promise\<[LockStatusResponse](#LockStatusResponse7)\> | Promise used to return the result.| +| Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** @@ -1560,16 +1564,16 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| newPin2 | string | Yes | New PIN. | -| puk2 | string | Yes | PUK of the SIM card. | -| callback | AsyncCallback<[LockStatusResponse](#LockStatusResponse7)> | Yes | Callback used to return the result. | +| newPin2 | string | Yes | New PIN 2. | +| puk2 | string | Yes | PUK 2 of the SIM card. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)> | Yes | Callback used to return the result. | **Example** ```js -let puk2='1xxxxxxx'; -let newPin2='1235'; -sim.unlockPuk2(0, newPin2,puk2,(err, data) => { +let puk2 = '1xxxxxxx'; +let newPin2 = '1235'; +sim.unlockPuk2(0, newPin2, puk2, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -1592,21 +1596,21 @@ This is a system API. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | -------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| newPin2 | string | Yes | New PIN. | -| puk2 | string | Yes | PUK of the SIM card. | +| newPin2 | string | Yes | New PIN 2. | +| puk2 | string | Yes | PUK 2 of the SIM card. | **Return value** | Type | Description | | ---------------------------------------------------- | -------------------------------------------------- | -| Promise\<[LockStatusResponse](#LockStatusResponse)\> | Promise used to return the result.| +| Promise\<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| **Example** ```js -let puk2='1xxxxxxx'; -let newPin2='1235'; -let promise = sim.unlockPuk2(0,newPin2,puk2); +let puk2 = '1xxxxxxx'; +let newPin2 = '1235'; +let promise = sim.unlockPuk2(0, newPin2, puk2); promise.then(data => { console.log(`unlockPuk2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1634,142 +1638,1313 @@ Obtains the number of card slots. console.log("Result: "+ sim.getMaxSimCount()) ``` +## sim.getSimIccId7+ -## SimState +getSimIccId(slotId: number, callback: AsyncCallback): void -Enumerates SIM card states. +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. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| --------------------- | ---- | ---------------------------------------------------------- | -| SIM_STATE_UNKNOWN | 0 | The SIM card is in **unknown** state; that is, the SIM card status cannot be obtained. | -| SIM_STATE_NOT_PRESENT | 1 | The SIM card is in **not present** state; that is, no SIM card is inserted into the card slot. | -| SIM_STATE_LOCKED | 2 | The SIM card is in **locked** state; that is, the SIM card is locked by the personal identification number (PIN), PIN unblocking key (PUK), or network. | -| SIM_STATE_NOT_READY | 3 | The SIM card is in **not ready** state; that is, the SIM card has been installed but cannot work properly. | -| SIM_STATE_READY | 4 | The SIM card is in **ready** state; that is, the SIM card has been installed and is working properly. | -| SIM_STATE_LOADED | 5 | The SIM card is in **loaded** state; that is, the SIM card is present and all its files have been loaded.| +**Parameters** -## CardType7+ +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getSimIccId(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getSimIccId7+ + +getSimIccId(slotId: number): Promise + +Obtains the ICCID of the SIM card in the specified slot. This API uses a promise to return the result. -Enumerates card types. +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE **System capability**: SystemCapability.Telephony.CoreService -| Name| Value| Description| -| ----- | ----- | ----- | -|UNKNOWN_CARD | -1 | Unknown| -|SINGLE_MODE_SIM_CARD | 10 | Single-card (SIM)| -|SINGLE_MODE_USIM_CARD | 20 | Single-card (USIM)| -|SINGLE_MODE_RUIM_CARD | 30 | Single-card (RUIM)| -|DUAL_MODE_CG_CARD | 40 | Dual-card (CDMA+GSM)| -|CT_NATIONAL_ROAMING_CARD | 41 | China Telecom internal roaming card| -|CU_DUAL_MODE_CARD | 42 | China Unicom dual-mode card| -|DUAL_MODE_TELECOM_LTE_CARD | 43 | China Telecom dual-mode LTE card| -|DUAL_MODE_UG_CARD | 50 | Dual-mode card (UMTS+GSM)| -|SINGLE_MODE_ISIM_CARD8+ | 60 | Single-card (ISIM)| +**Parameters** -## LockType8+ +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -Enumerates lock types. +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getSimIccId(0); +promise.then(data => { + console.log(`getSimIccId success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getSimIccId fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getVoiceMailIdentifier8+ + +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. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| -------- | ---- | ----------- | -| PIN_LOCK | 1 | SIM card password lock| -| FDN_LOCK | 2 | Fixed dialing lock | +**Parameters** -## LockState8+ +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getVoiceMailIdentifier(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` -Enumerates lock states. + +## sim.getVoiceMailIdentifier8+ + +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. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| -------- | ---- | ---------- | -| LOCK_OFF | 0 | The lock is off.| -| LOCK_ON | 1 | The lock is on.| +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -## **PersoLockType**8+ +**Return value** -Enumerates personalized lock types. +| Type | Description | +| ---------------- | ------------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getVoiceMailIdentifier(0); +promise.then(data => { + console.log(`getVoiceMailIdentifier success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getVoiceMailIdentifier fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getVoiceMailNumber8+ + +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. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Value | Description | -| ------------ | ---- | ----------------------------------------------- | -| PN_PIN_LOCK | 0 | Personalized network PIN lock. For details, see *3GPP TS 22.022 [33]*. | -| PN_PUK_LOCK | 1 | Personalized network PUK lock. | -| PU_PIN_LOCK | 2 | Personalized network subset PIN lock. For details, see *3GPP TS 22.022 [33]*. | -| PU_PUK_LOCK | 3 | Personalized network subset PUK lock. | -| PP_PIN_LOCK | 4 | Personalized service provider PIN lock. For details, see *3GPP TS 22.022 [33]*.| -| PP_PUK_LOCK | 5 | Personalized service provider PUK lock. | -| PC_PIN_LOCK | 6 | Personalized corporate PIN lock. For details, see *3GPP TS 22.022 [33]*. | -| PC_PUK_LOCK | 7 | Personalized corporate PUK lock. | -| SIM_PIN_LOCK | 8 | Personalized SIM card PIN lock. For details, see *3GPP TS 22.022 [33]*. | -| SIM_PUK_LOCK | 9 | Personalized SIM card PUK lock. | +**Parameters** -## **LockStatusResponse**7+ +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | -Defines the lock status response. +**Example** + +```js +sim.getVoiceMailNumber(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getVoiceMailNumber8+ + +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. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| --------------- | ------ | ------------------ | -| result | number | Operation result. | -| remain?: number | number | Remaining attempts (can be null).| +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------ | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getVoiceMailNumber(0); +promise.then(data => { + console.log(`getVoiceMailNumber success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getVoiceMailNumber fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.setVoiceMailInfo8+ -## **LockInfo**8+ +setVoiceMailInfo(slotId: number, mailName: string, mailNumber: string, callback: AsyncCallback): void -Defines the personalized lock status response. +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. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| -------- | --------- | ------ | -| lockType | LockType | Lock type.| -| password | string | Password. | -| state | LockState | Lock state.| +**Parameters** -## **PersoLockInfo**8+ +| Name | Type | Mandatory| Description | +| ---------- | -------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| mailName | string | Yes | Voice mailbox name. | +| mailNumber | string | Yes | Voice mailbox number. | +| callback | AsyncCallback | Yes | Callback used to return the result. | -Defines the personalized lock information. +**Example** + +```js +sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com" , (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.setVoiceMailInfo8+ + +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. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| -------- | ------------- | ------------ | -| lockType | PersoLockType | Personalized lock type.| -| password | string | Password. | +**Parameters** -## **IccAccountInfo**7+ +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| mailName | string | Yes | Voice mailbox name. | +| mailNumber | string | Yes | Voice mailbox number. | -Defines the ICC account information. +**Return value** + +| Type | Description | +| -------------- | ----------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com"); +promise.then(data => { + console.log(`setVoiceMailInfo success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`setVoiceMailInfo fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getSimTelephoneNumber8+ + +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. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ---------- | ------- | ---------------- | -| simId | number | SIM card ID. | -| slotIndex | number | Card slot ID. | -| isEsim | boolean | Whether the SIM card is an eSim card.| -| isActive | boolean | Whether the card is activated. | -| iccId | string | ICCID number. | -| showName | string | SIM card display name. | -| showNumber | string | SIM card display number. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getSimTelephoneNumber(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getSimTelephoneNumber8+ + +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. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | -------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getSimTelephoneNumber(0); +promise.then(data => { + console.log(`getSimTelephoneNumber success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getSimTelephoneNumber fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getSimGid17+ + +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. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getSimGid1(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getSimGid17+ + +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. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getSimGid1(0); +promise.then(data => { + console.log(`getSimGid1 success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getSimGid1 fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getIMSI + +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. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getIMSI(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getIMSI + +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. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getIMSI(0); +promise.then(data => { + console.log(`getIMSI success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getIMSI fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getOperatorConfigs8+ + +getOperatorConfigs(slotId: number, callback: AsyncCallback>): void + +Obtains the carrier configuration of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getOperatorConfigs(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getOperatorConfigs8+ + +getOperatorConfigs(slotId: number): Promise> + +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. + +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------------------------------------------- | ----------------------------- | +| Promise> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getOperatorConfigs(0); +promise.then(data => { + console.log(`getOperatorConfigs success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getOperatorConfigs fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.queryIccDiallingNumbers8+ + +queryIccDiallingNumbers(slotId: number, type: ContactType, callback: AsyncCallback>): void + +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. + +**Permission required**: ohos.permission.READ_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
1 : GENERAL_CONTACT
2 : FIXED_DIALING | +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Example** + +```js +sim.queryIccDiallingNumbers(0, 1, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.queryIccDiallingNumbers8+ + +queryIccDiallingNumbers(slotId: number, type: ContactType): Promise> + +Queries contact numbers of the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Permission required**: ohos.permission.READ_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
1 : GENERAL_CONTACT
2 : FIXED_DIALING | + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------ | +| Promise> | Promise used to return the result.| + +**Example** + +```js +let promise = sim.queryIccDiallingNumbers(0, 1); +promise.then(data => { + console.log(`queryIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`queryIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.addIccDiallingNumbers8+ + +addIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void + +Adds contact numbers for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +sim.addIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.addIccDiallingNumbers8+ + +addIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise + +Adds contact numbers for the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +let promise = sim.addIccDiallingNumbers(0, 1, diallingNumbersInof); +promise.then(data => { + console.log(`addIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`addIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.delIccDiallingNumbers8+ + +delIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void + +Deletes contact numbers from the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +sim.delIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.delIccDiallingNumbers8+ + +delIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise + +Deletes contact numbers from the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +let promise = sim.delIccDiallingNumbers(0, 1, diallingNumbersInof); +promise.then(data => { + console.log(`delIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`delIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.updateIccDiallingNumbers8+ + +updateIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo, callback: AsyncCallback): void + +Updates contact numbers for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.updateIccDiallingNumbers8+ + +updateIccDiallingNumbers(slotId: number, type: ContactType, diallingNumbers: DiallingNumbersInfo): Promise + +Updates contact numbers for the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Permission required**: ohos.permission.WRITE_CONTACTS + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | + +**Return value** + +| Type | Description | +| -------------- | ----------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let diallingNumbersInof = { + alphaTag = "alpha", + number = "138xxxxxxxx", + recordNumber = 123, + pin2 = "1234" +}; +let promise = sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof); +promise.then(data => { + console.log(`updateIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`updateIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.sendEnvelopeCmd8+ + +sendEnvelopeCmd(slotId: number, cmd: string, callback: AsyncCallback): void + +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. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| cmd | string | Yes | Envelope command. | +| callback | AsyncCallback | Yes | Yes | + +**Example** + +```js +sim.sendEnvelopeCmd(0, "ls", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.sendEnvelopeCmd8+ + +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. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| cmd | string | Yes | Envelope command. | + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.sendEnvelopeCmd(0, "ls"); +promise.then(data => { + console.log(`sendEnvelopeCmd success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`sendEnvelopeCmd fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.sendTerminalResponseCmd8+ + +sendTerminalResponseCmd(slotId: number, cmd: string, callback: AsyncCallback): void + +Sends a terminal response command to the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| cmd | string | Yes | Command | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.sendTerminalResponseCmd(0, "ls", (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.sendTerminalResponseCmd8+ + +sendTerminalResponseCmd(slotId: number, cmd: string): Promise + +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. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| cmd | string | Yes | Command | + +**Return value** + +| Type | Description | +| -------------- | --------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.sendTerminalResponseCmd(0, "ls"); +promise.then(data => { + console.log(`sendTerminalResponseCmd success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`sendTerminalResponseCmd fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.unlockSimLock8+ + +unlockSimLock(slotId: number, lockInfo: PersoLockInfo, callback: AsyncCallback): void + +Unlocks the SIM card in the specified slot. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| lockInfo | [PersoLockInfo](#persolockinfo8) | Yes | Personalized lock information. | +| callback | AsyncCallback<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | + +**Example** + +```js +let persoLockInfo = { + lockType = 0, + password = "1234" +}; +sim.unlockSimLock(0, persoLockInfo, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.unlockSimLock8+ + +unlockSimLock(slotId: number, lockInfo: PersoLockInfo): Promise + +Unlocks the SIM card in the specified slot. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| lockInfo | [PersoLockInfo](#persolockinfo8) | Yes | Personalized lock information. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[LockStatusResponse](#lockstatusresponse7)\> | Promise used to return the result.| + +**Example** + +```js +let persoLockInfo = { + lockType = 0, + password = "1234" +}; +let promise = sim.unlockSimLock(0, persoLockInfo); +promise.then(data => { + console.log(`unlockSimLock success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`unlockSimLock fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getOpKey9+ + +getOpKey(slotId: number, 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 capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getOpKey(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getOpKey9+ + +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 capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------------- | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getOpKey(0); +promise.then(data => { + console.log(`getOpKey success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getOpKey fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sim.getOpName9+ + +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 capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +sim.getOpName(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sim.getOpName9+ + +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 capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------ | +| Promise | Promise used to return the result.| + +**Example** + +```js +let promise = sim.getOpName(0); +promise.then(data => { + console.log(`getOpName success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.log(`getOpName fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## SimState + +Enumerates SIM card states. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| --------------------- | ---- | ---------------------------------------------------------- | +| SIM_STATE_UNKNOWN | 0 | The SIM card is in **unknown** state; that is, the SIM card status cannot be obtained. | +| SIM_STATE_NOT_PRESENT | 1 | The SIM card is in **not present** state; that is, no SIM card is inserted into the card slot. | +| SIM_STATE_LOCKED | 2 | The SIM card is in **locked** state; that is, the SIM card is locked by the personal identification number (PIN), PIN unblocking key (PUK), or network. | +| SIM_STATE_NOT_READY | 3 | The SIM card is in **not ready** state; that is, the SIM card has been installed but cannot work properly. | +| SIM_STATE_READY | 4 | The SIM card is in **ready** state; that is, the SIM card has been installed and is working properly. | +| SIM_STATE_LOADED | 5 | The SIM card is in **loaded** state; that is, the SIM card is present and all its files have been loaded.| + +## CardType7+ + +Enumerates SIM card types. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name| Value| Description| +| ----- | ----- | ----- | +|UNKNOWN_CARD | -1 | Unknown| +|SINGLE_MODE_SIM_CARD | 10 | Single-card (SIM)| +|SINGLE_MODE_USIM_CARD | 20 | Single-card (USIM)| +|SINGLE_MODE_RUIM_CARD | 30 | Single-card (RUIM)| +|DUAL_MODE_CG_CARD | 40 | Dual-card (CDMA+GSM)| +|CT_NATIONAL_ROAMING_CARD | 41 | China Telecom internal roaming card| +|CU_DUAL_MODE_CARD | 42 | China Unicom dual-mode card| +|DUAL_MODE_TELECOM_LTE_CARD | 43 | China Telecom dual-mode LTE card| +|DUAL_MODE_UG_CARD | 50 | Dual-mode card (UMTS+GSM)| +|SINGLE_MODE_ISIM_CARD8+ | 60 | Single-card (ISIM)| + +## LockType8+ + +Enumerates lock types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -------- | ---- | ----------- | +| PIN_LOCK | 1 | SIM card password lock.| +| FDN_LOCK | 2 | Fixed dialing lock. | + +## LockState8+ + +Enumerates lock states. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| -------- | ---- | ---------- | +| LOCK_OFF | 0 | The lock is off.| +| LOCK_ON | 1 | The lock is on.| + +## PersoLockType8+ + +Enumerates personalized lock types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| ------------ | ---- | ----------------------------------------------- | +| PN_PIN_LOCK | 0 | Personalized network PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PN_PUK_LOCK | 1 | Personalized network PUK lock. | +| PU_PIN_LOCK | 2 | Personalized network subset PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PU_PUK_LOCK | 3 | Personalized network subset PUK lock. | +| PP_PIN_LOCK | 4 | Personalized service provider PIN lock. For details, see *3GPP TS 22.022 [33]*.| +| PP_PUK_LOCK | 5 | Personalized service provider PUK lock. | +| PC_PIN_LOCK | 6 | Personalized corporate PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| PC_PUK_LOCK | 7 | Personalized corporate PUK lock. | +| SIM_PIN_LOCK | 8 | Personalized SIM card PIN lock. For details, see *3GPP TS 22.022 [33]*. | +| SIM_PUK_LOCK | 9 | Personalized SIM card PUK lock. | + +## LockStatusResponse7+ + +Defines the lock status response. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| --------------- | ------ | ------------------ | +| result | number | Operation result. | +| remain?: number | number | Remaining attempts (can be null).| + +## LockInfo8+ + +Defines the lock information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| -------- | ------------------------ | ------ | +| lockType | [LockType](#locktype8) | Lock type.| +| password | string | Password. | +| state | [LockState](#lockstate8) | Lock state.| + +## PersoLockInfo8+ + +Defines the personalized lock information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| -------- | -------------------------------- | ------------ | +| lockType | [PersoLockType](#persolocktype8) | Personalized lock type.| +| password | string | Password. | + +## IccAccountInfo7+ + +Defines the ICC account information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ---------- | ------- | ---------------- | +| simId | number | SIM card ID. | +| slotIndex | number | Card slot ID. | +| isEsim | boolean | Whether the SIM card is an eSim card.| +| isActive | boolean | Whether the card is activated. | +| iccId | string | ICCID number. | +| showName | string | SIM card display name. | +| showNumber | string | SIM card display number. | + +## OperatorConfig8+ + +Defines the carrier configuration. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description| +| ----- | ------ | ---- | +| field | string | Field| +| value | string | Value | + +## DiallingNumbersInfo8+ + +Defines the contact number information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Type | Description | +| ------------ | ------ | -------- | +| alphaTag | string | Alpha tag. | +| number | string | Contact number. | +| recordNumber | number | Record number.| +| pin2 | string | PIN 2.| + +## ContactType8+ + +Enumerates contact types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| :-------------- | ---- | ---------- | +| GENERAL_CONTACT | 1 | Common contact number.| +| FIXED_DIALING | 2 | Fixed dialing number. | diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 25069b318add375d68d97084e45b08c1f69f3804..fa226f072e2a1c4aa568937455e7ee78e3513469 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -174,7 +174,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -202,7 +202,7 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| **Return value** @@ -360,7 +360,7 @@ promise.then(data => { hasSmsCapability(): boolean -Checks whether the current device can send and receive SMS messages. This API works in synchronous mode. +Checks whether the current device can send and receive SMS messages. This API returns the result synchronously. **System capability**: SystemCapability.Telephony.SmsMms @@ -375,6 +375,739 @@ let result = sms.hasSmsCapability(); console.log(`hasSmsCapability: ${JSON.stringify(result)}`); ``` +## sms.splitMessage8+ + +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. + +**Required permission**: ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ----------------------------- | +| content | string | Yes | SMS message content. The value cannot be null.| +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Example** + +```js +string content= "long message"; +sms.splitMessage(content, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.splitMessage8+ + +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. + +**Required permission**: ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------------- | +| content | string | Yes | SMS message content. The value cannot be null.| + +**Return value** + +| Type | Description | +| ----------------------- | ----------------------------------- | +| Promise> | Promise used to return the result.| + +**Example** + +```js +string content = "long message"; +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)}`); +}); +``` + +## sms.addSimMessage7+ + +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. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | --------------- | +| options | [SimMessageOptions](#simmessageoptions7) | Yes | SIM message options.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let simMessageOptions = { + slotId = 0, + smsc = "test", + pdu = "xxxxxx", + status = 0 +}; +sms.addSimMessage(simMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.addSimMessage7+ + +addSimMessage(options: SimMessageOptions): Promise + +Adds a SIM message. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | --------------- | +| options | [SimMessageOptions](#simmessageoptions7) | Yes | SIM message options.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let simMessageOptions = { + slotId = 0, + smsc = "test", + pdu = "xxxxxx", + status = 0 +}; +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)}`); +}); +``` + +## sms.delSimMessage7+ + +delSimMessage(slotId: number, msgIndex: number, callback: AsyncCallback): void + +Deletes a SIM message. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| msgIndex | number | Yes | Message index. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +let msgIndex = 1; +sms.delSimMessage(slotId, msgIndex, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.delSimMessage7+ + +delSimMessage(slotId: number, msgIndex: number): Promise + +Deletes a SIM message. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| msgIndex | number | Yes | Message index. | + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +let msgIndex = 1; +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)}`); +}); +``` + +## sms.updateSimMessage7+ + +updateSimMessage(options: UpdateSimMessageOptions, callback: AsyncCallback): void + +Updates a SIM message. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------- | +| options | [UpdateSimMessageOptions](#updatesimmessageoptions7) | Yes | SIM message updating options.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let updateSimMessageOptions = { + slotId = 0, + msgIndex = 1, + newStatus = 0, + pdu = "xxxxxxx", + smsc = "test" +}; +sms.updateSimMessage(updateSimMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.updateSimMessage7+ + +updateSimMessage(options: UpdateSimMessageOptions): Promise + +Updates a SIM message. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS,ohos.permission.SEND_MESSAGES + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------------------- | ---- | ------------------- | +| options | [UpdateSimMessageOptions](#updatesimmessageoptions7) | Yes | SIM message updating options.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let updateSimMessageOptions = { + slotId = 0, + msgIndex = 1, + newStatus = 0, + pdu = "xxxxxxx", + smsc = "test" +}; +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)}`); +}); +``` + +## sms.getAllSimMessages7+ + +getAllSimMessages(slotId: number, callback: AsyncCallback>): void + +Obtains all SIM card messages. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| callback | AsyncCallback> | Yes | Callback used to return the result. | + +**Example** + +```js +let slotId = 0; +sms.getAllSimMessages(slotId, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.getAllSimMessages7+ + +getAllSimMessages(slotId: number): Promise> + +Obtains all SIM card messages. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | ---------------------------------- | +| PromiseArray<[SimShortMessage](#simshortmessage8)\>> | Promise used to return the result.| + +**Example** + +```js +let slotId = 0; +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)}`); +}); +``` + +## sms.setCBConfig7+ + +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. + +**Required permission**: ohos.permission.RECEIVE_SMS + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------ | +| options | [CBConfigOptions](#cbconfigoptions8) | Yes | Cell broadcast configuration options.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let cbConfigOptions = { + slotId = 0, + smsc = "test", + pdu = "xxxxxxxx", + status = 0 +}; +sms.setCBConfig(cbConfigOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.setCBConfig7+ + +setCBConfig(options: CBConfigOptions): Promise + +Sets the cell broadcast configuration. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.RECEIVE_SMS + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------ | ---- | ------------ | +| options | [CBConfigOptions](#cbconfigoptions8) | Yes | Cell broadcast configuration options.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +let cbConfigOptions = { + slotId = 0, + smsc = "test", + pdu = "xxxxxxxx", + status = 0 +}; +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)}`); +}); +``` + +## sms.getSmsSegmentsInfo8+ + +getSmsSegmentsInfo(slotId: number, message: string, force7bit: boolean, callback: AsyncCallback): void + +Obtains SMS message segment information. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| message | string | Yes | SMS message. | +| force7bit | boolean | Yes | Whether to use 7-bit coding. | +| callback | AsyncCallback<[SmsSegmentsInfo](# { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.getSmsSegmentsInfo8+ + +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 capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------- | ---- | ----------------------------------------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| message | string | Yes | Message | +| force7bit | boolean | Yes | Whether to use 7-bit coding. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | ----------------------------- | +| Promise<[SmsSegmentsInfo](# + console.log(`getSmsSegmentsInfo success, promise: data->${JSON.stringify(data)}`); +}).catch(err => { + console.error(`getSmsSegmentsInfo fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## sms.isImsSmsSupported8+ + +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 capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| + +**Example** + +```js +sms.isImsSmsSupported((err, data) => { + console.log(`callback: err->${JSON.(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.isImsSmsSupported8+ + +isImsSmsSupported(): Promise + +Checks whether SMS is supported on IMS. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Return value** + +| Type | Description | +| ---------------------- | ----------------------- | +| Promise<boolean> | Promise used to return the result.| + +**Example** + +```js +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)}`); +}); +``` + +## sms.getImsShortMessageFormat8+ + +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 capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------- | +| callback | AsyncCallback<string> | Yes | Callback used to return the result.| + +**Example** + +```js +sms.getImsShortMessageFormat((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.getImsShortMessageFormat8+ + +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 capability**: SystemCapability.Telephony.SmsMms + +**Return value** + +| Type | Description | +| --------------------- | -------------------------- | +| Promise<string> | Promise used to return the result. | + +**Example** + +```js +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)}`); +}); +``` + +## sms.decodeMms8+ + +decodeMms(mmsFilePathName: string | Array, callback: AsyncCallback): void + +Decodes MMS messages. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------- | ---- | -------------- | +| mmsFilePathName | string \|Array | Yes | MMS message file path.| +| callback | AsyncCallback<[MmsInformation](#mmsinformation8)> | Yes | Callback used to return the result. | + +**Example** + +```js +let mmsFilePathName = "filename"; +sms.decodeMms(mmsFilePathName, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.decodeMms8+ + +decodeMms(mmsFilePathName: string | Array): Promise + +Decodes MMS messages. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ----------------------- | ---- | -------------- | +| mmsFilePathName | string \|Array | Yes | MMS message file path.| + +**Return value** + +| Type | Description | +| --------------------------------------------------------- | --------------------------- | +| Promise<<[MmsInformation](#mmsinformation8)>> | Promise used to return the result.| + +**Example** + +```js +let mmsFilePathName = "filename"; +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)}`); +}); +``` + +## sms.encodeMms8+ + +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 capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ---------- | +| mms | [MmsInformation](#mmsinformation8) | Yes | MMS message information.| +| callback | AsyncCallback<Array> | Yes | Callback used to return the result.| + +**Example** + +```js +let mmsAcknowledgeInd = { + transactionId = "100", + version = 0x10, + reportAllowed = 128 +}; +let mmsInformation = { + messageType = 133, + mmsType = mmsAcknowledgeInd +}; +sms.encodeMms(mmsInformation, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## sms.encodeMms8+ + +encodeMms(mms: MmsInformation): Promise> + +Encodes MMS messages. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------- | ---- | ---------- | +| mms | [MmsInformation](#mmsinformation8) | Yes | MMS message information.| + +**Return value** + +| Type | Description | +| ----------------------------- | ----------------------------------- | +| Promise<Array> | Promise used to return the result.| + +**Example** + +```js +let mmsAcknowledgeInd = { + transactionId = "100", + version = 0x10, + reportAllowed = 128 +}; +let mmsInformation = { + messageType = 133, + mmsType = mmsAcknowledgeInd +}; +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)}`); +}); +``` + ## ShortMessage Defines an SMS message instance. @@ -383,7 +1116,7 @@ Defines an SMS message instance. | Name | Type | Description | | ------------------------ | --------------------------------------- | ------------------------------------------------------------ | -| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
TP-Reply-Path: The device returns a response based on the SMSC that sends the SMS message.| +| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.| | isReplaceMessage | boolean | Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| | isSmsStatusReportMessage | boolean | Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| | messageClass | [ShortMessageClass](#shortmessageclass) | Enumerates SMS message types. | @@ -464,3 +1197,422 @@ Enumerates SMS message sending results. | SEND_SMS_FAILURE_UNKNOWN | 1 | Failed to send the SMS message due to an unknown reason. | | SEND_SMS_FAILURE_RADIO_OFF | 2 | Failed to send the SMS message because the modem is shut down. | | SEND_SMS_FAILURE_SERVICE_UNAVAILABLE | 3 | Failed to send the SMS message because the network is unavailable or SMS message sending or receiving is not supported.| + + +## MmsInformation8+ + +Defines the MMS message information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------------------------------------ | ---- | --------- | +| messageType | [MessageType](#messagetype8) | Yes | Message type. | +| mmsType | [MmsSendReq](#mmssendreq8) \|[MmsSendConf](#mmssendconf8) \|[MmsNotificationInd](#mmsnotificationind8) \|[MmsRespInd](#mmsrespind8) \|[MmsRetrieveConf](#mmsretrieveconf8)\|[MmsAcknowledgeInd](#mmsacknowledgeind8)\|[MmsDeliveryInd](#mmsdeliveryind8)\|[MmsReadOrigInd](#mmsreadorigind8)\|[MmsReadRecInd](#mmsreadrecind8)| Yes | PDU header type.| +| attachment | Array<[MmsAttachment](#mmsattachment8)\> | No | Attachment. | + +## MmsSendReq8+ + +Defines an MMS message sending request. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ---------------- | ------------------------------------ | ---- | ------------ | +| from | [MmsAddress](#mmsaddress8) | Yes | MMS message source. | +| transactionId | string | Yes | Transaction ID. | +| contentType | string | Yes | Content type. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| to | Array<[MmsAddress](#mmsaddress8)\> | No | Address to which the message is sent. | +| date | number | No | Date. | +| cc | Array<[MmsAddress](#mmsaddress8)\> | No | Carbon copy. | +| bcc | Array<[MmsAddress](#mmsaddress8)\> | No | Blind carbon copy. | +| subject | string | No | Subject. | +| messageClass | number | No | Message class. | +| expiry | number | No | Expiration. | +| priority | [MmsPriorityType](#mmsprioritytype8) | No | Priority. | +| senderVisibility | number | No | Sender visibility.| +| deliveryReport | number | No | Delivery report. | +| readReport | number | No | Read report. | + +## MmsSendConf8+ + +Defines the MMS message sending configuration. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ---- | -------- | +| responseState | number | Yes | Response status.| +| transactionId | string | Yes | Transaction ID. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| messageId | string | No | Message ID. | + +## MmsNotificationInd8+ + +Defines an MMS notification index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| --------------- | ---------------------------------- | ---- | -------- | +| transactionId | string | Yes | Transaction ID. | +| messageClass | number | Yes | Message class. | +| messageSize | number | Yes | Message size.| +| expiry | number | Yes | Expiration. | +| contentLocation | string | Yes | Content location.| +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| from | [MmsAddress](#mmsaddress8) | No | Source. | +| subject | string | No | Subject. | +| deliveryReport | number | No | Status report.| +| contentClass | number | No | Content class. | + +## MmsAcknowledgeInd8+ + +Defines an MMS confirmation index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ---- | -------- | +| transactionId | string | Yes | Transaction ID. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| reportAllowed | [ReportType](#reporttype8) | No | Report allowed.| + +## MmsRetrieveConf8+ + +Defines the MMS message retrieval configuration. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------ | ---- | -------- | +| transactionId | string | Yes | Transaction ID. | +| messageId | string | Yes | Message ID. | +| date | number | Yes | Date. | +| contentType | string | Yes | Content type.| +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version | +| from | [MmsAddress](#mmsaddress8) | No | Source. | +| cc | Array<[MmsAddress](#mmsaddress8)\> | No | Carbon copy. | +| subject | string | No | Subject. | +| priority | [MmsPriorityType](#mmsprioritytype8) | No | Priority. | +| deliveryReport | number | No | Status report.| +| readReport | number | No | Read report.| +| retrieveStatus | number | No | Retrieval status.| +| retrieveText | string | No | Retrieval text.| + +## MmsReadOrigInd8+ + +Defines the original MMS message reading index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------- | ---- | -------- | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| messageId | string | Yes | Message ID. | +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent. | +| from | [MmsAddress](#mmsaddress8) | Yes | Source. | +| date | number | Yes | Date. | +| readStatus | number | Yes | Read status.| + +## MmsAttachment8+ + +Defines the attachment of an MMS message. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ----------------------- | ------------------------------------ | ---- | ------------------ | +| contentId | string | Yes | Content ID. | +| contentLocation | string | Yes | Content location. | +| contentDisposition | [DispositionType](#dispositiontype8) | Yes | Content disposition. | +| contentTransferEncoding | string | Yes | Encoding for content transfer. | +| contentType | string | Yes | Content type. | +| isSmil | boolean | Yes | Whether the synchronized multimedia integration language is used.| +| path | string | No | Path. | +| inBuff | Array | No | In the buffer | +| fileName | string | No | File name. | +| charset | [MmsCharSets](#mmscharsets8) | No | Character set. | + +## MmsAddress8+ + +Defines an MMSC address. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------- | ---- | ------ | +| address | string | Yes | MMSC address. | +| charset | [MmsCharSets](#mmscharsets8) | Yes | Character set.| + +## MessageType8+ + +Enumerates message types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| ------------------------- | ---- | -------------------- | +| TYPE_MMS_SEND_REQ | 128 | MMS message sending request. | +| TYPE_MMS_SEND_CONF | 129 | MMS message sending configuration. | +| TYPE_MMS_NOTIFICATION_IND | 130 | MMS notification index. | +| TYPE_MMS_RESP_IND | 131 | MMS message response index. | +| TYPE_MMS_RETRIEVE_CONF | 132 | MMS message retrieval configuration. | +| TYPE_MMS_ACKNOWLEDGE_IND | 133 | MMS message acknowledgement index. | +| TYPE_MMS_DELIVERY_IND | 134 | MMS message delivery index. | +| TYPE_MMS_READ_REC_IND | 135 | MMS message reading and receiving index.| +| TYPE_MMS_READ_ORIG_IND | 136 | Original MMS message reading index.| + +## MmsPriorityType8+ + +Enumerates MMS message priorities. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| ---------- | ---- | -------------- | +| MMS_LOW | 128 | Low priority. | +| MMS_NORMAL | 129 | Normal priority.| +| MMS_HIGH | 130 | High priority. | + +## MmsVersionType8+ + +Enumerates MMS versions. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| --------------- | ---- | ----------- | +| MMS_VERSION_1_0 | 0x10 | MMS version 1_0.| +| MMS_VERSION_1_1 | 0x11 | MMS version 1_1.| +| MMS_VERSION_1_2 | 0x12 | MMS version 1_2.| +| MMS_VERSION_1_3 | 0x13 | MMS version 1_3.| + +## MmsCharSets8+ + +Enumerates MMS character sets. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| --------------- | ------ | ------------------- | +| BIG5 | 0X07EA | BIG5 format. | +| ISO_10646_UCS_2 | 0X03E8 | ISO_10646_UCS_2 format.| +| ISO_8859_1 | 0X04 | ISO_8859_1 format. | +| ISO_8859_2 | 0X05 | ISO_8859_2 format. | +| ISO_8859_3 | 0X06 | ISO_8859_3 format. | +| ISO_8859_4 | 0X07 | ISO_8859_4 format. | +| ISO_8859_5 | 0X08 | ISO_8859_5 format. | +| ISO_8859_6 | 0X09 | ISO_8859_6 format. | +| ISO_8859_7 | 0X0A | ISO_8859_7 format. | +| ISO_8859_8 | 0X0B | ISO_8859_8 format. | +| ISO_8859_9 | 0X0C | ISO_8859_9 format. | +| SHIFT_JIS | 0X11 | SHIFT_JIS format. | +| US_ASCII | 0X03 | US_ASCII format. | +| UTF_8 | 0X6A | UTF_8 format. | + +## DispositionType8+ + +Enumerates disposition types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| ---------- | ---- | -------- | +| FROM_DATA | 0 | Data source.| +| ATTACHMENT | 1 | Attachment. | +| INLINE | 2 | Inlining. | + +## ReportType8+ + +Enumerates report types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description| +| ------- | ---- | ---- | +| MMS_YES | 128 | YES | +| MMS_NO | 129 | NO | + +## CBConfigOptions8+ + +Defines the cell broadcast configuration options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| -------------- | -------------------- | ---- | ------------ | +| slotId | number | Yes | Card slot ID. | +| enable | boolean | Yes | Whether to enable cell broadcast. | +| startMessageId | number | Yes | Start message ID. | +| endMessageId | number | Yes | End message ID. | +| ranType | [RanType](#rantype7) | Yes | RAN type.| + +## SimMessageStatus7+ + +Defines the SIM message status. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| ------------------------- | ---- | --------------------------- | +| SIM_MESSAGE_STATUS_FREE | 0 | Free state. | +| SIM_MESSAGE_STATUS_READ | 1 | Read state. | +| SIM_MESSAGE_STATUS_UNREAD | 3 | Unread state. | +| SIM_MESSAGE_STATUS_SENT | 5 | Storage of sent messages (applicable only to SMS).| +| SIM_MESSAGE_STATUS_UNSENT | 7 | Storage of unsent messages (applicable only to SMS).| + +## RanType7+ + +Enumerates RAN types. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description| +| --------- | ---- | ---- | +| TYPE_GSM | 1 | GSM | +| TYPE_CDMA | 2 | CMDA | + +## SmsEncodingScheme8+ + +Enumerates SMS encoding schemes. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Value | Description | +| -------------------- | ---- | ------------ | +| SMS_ENCODING_UNKNOWN | 0 | Unknown code.| +| SMS_ENCODING_7BIT | 1 | 7-digit code. | +| SMS_ENCODING_8BIT | 2 | 8-digit code. | +| SMS_ENCODING_16BIT | 3 | 16-digit code.| + +## SimMessageOptions7+ + +Defines the SIM message options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | -------------- | +| slotId | number | Yes | Card slot ID. | +| smsc | string | Yes | Short message service center.| +| pdu | string | Yes | Protocol data unit. | +| status | [SimMessageStatus](#simmessagestatus7) | Yes | Message status. | + +## UpdateSimMessageOptions7+ + +Defines the updating SIM message options. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | -------------- | +| slotId | number | Yes | Card slot ID. | +| msgIndex | number | Yes | Message index. | +| newStatus | [SimMessageStatus](#simmessagestatus7) | Yes | New status. | +| pdu | string | Yes | Protocol data unit. | +| smsc | string | Yes | Short message service center.| + +## SimShortMessage8+ + +Defines a SIM message. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------------------- | ---- | ------------- | +| shortMessage | [ShortMessage](#shortmessage) | Yes | SMS message. | +| simMessageStatus | [SimMessageStatus](#simmessagestatus7) | Yes | SIM message status.| +| indexOnSim | number | Yes | SIM card index. | + +## MmsDeliveryInd8+ + +Defines an MMS message delivery index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------- | ---- | ------ | +| messageId | string | Yes | Message ID.| +| date | number | Yes | Date. | +| to | Array<[MmsAddress](#mmsaddress8)\> | Yes | Address to which the message is sent.| +| status | number | Yes | Status. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | + +## MmsRespInd8+ + +Defines an MMS response index. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------- | ---- | -------- | +| transactionId | string | Yes | Event ID. | +| status | number | Yes | Status. | +| version | [MmsVersionType](#mmsversiontype8) | Yes | Version. | +| reportAllowed | [ReportType](#reporttype8) | No | Report allowed.| + +## SmsSegmentsInfo8+ + +Defines the SMS message segment information. + +This is a system API. + +**System capability**: SystemCapability.Telephony.SmsMms + +| Name | Type | Mandatory| Description | +| -------------------- | ---------------------------------------- | ---- | ------------ | +| splitCount | number | Yes | Split count. | +| encodeCount | number | Yes | Encoding count. | +| encodeCountRemaining | number | Yes | Remaining encoding count.| +| scheme | [SmsEncodingScheme](#smsencodingscheme8) | Yes | Encoding scheme.| diff --git a/en/application-dev/reference/apis/js-apis-system-mediaquery.md b/en/application-dev/reference/apis/js-apis-system-mediaquery.md index f2057a86685a5d212e84caf27e69468b8169c267..841cebeb1da0380128d3704650a0aaf9ef095d5f 100644 --- a/en/application-dev/reference/apis/js-apis-system-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-system-mediaquery.md @@ -1,7 +1,9 @@ # Media Query +The **mediaquery** module provides different styles for different media types. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + +> **NOTE** > > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.mediaquery`](js-apis-mediaquery.md) instead. > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -38,11 +40,7 @@ Creates a **MediaQueryList** object based on the query condition. **Example** ``` -export default { - matchMedia() { - var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); - }, -} +var mMediaQueryList = mediaquery.matchMedia('(max-width: 466)'); ``` ## MediaQueryEvent @@ -95,11 +93,16 @@ Adds a listener for this **MediaQueryList** object. The listener must be added b | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | -------------- | -| callback | (event: MediaQueryEvent) => void | Yes | Callback invoked when the matching condition changes.| +| callback | (event: MediaQueryEvent) => void | Yes | Callback invoked when the query condition changes.| **Example** ``` +function maxWidthMatch(e){ + if(e.matches){ + // do something + } +} mMediaQueryList.addListener(maxWidthMatch); ``` @@ -116,10 +119,15 @@ Removes the listener for this **MediaQueryList** object. | Name | Type | Mandatory | Description | | -------- | --------------------------------- | ---- | -------------- | -| callback | (event: MediaQueryEvent) => void) | Yes | Callback invoked when the matching condition changes.| +| callback | (event: MediaQueryEvent) => void) | Yes | Callback invoked when the query condition changes.| **Example** ``` +function maxWidthMatch(e){ + if(e.matches){ + // do something + } +} mMediaQueryList.removeListener(maxWidthMatch); ``` diff --git a/en/application-dev/reference/apis/js-apis-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md new file mode 100644 index 0000000000000000000000000000000000000000..5ed3760a0cf3664cc6991a73489dd7f53ab9d83b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -0,0 +1,127 @@ +# Standard NFC Tag Session + +The **tagSession** module provides common APIs for establishing connections and transferring data. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## **Modules to Import** + +```js +import tag from '@ohos.nfc.tag'; +``` + +## tagSession + +Provides common APIs for establishing connections and transferring data. **tagSession** is the base class of all [NFC tag technologies](js-apis-nfctech.md). + +A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. + +The specific method varies with the NFC tag technology in use. For details, see [nfcTag](js-apis-nfcTag.md). + +### tagSession.connectTag + +connectTag(): boolean; + +Connects to this tag. + +Call this method to set up a connection before reading data from or writing data to a tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); +console.log("isNfcConnected:" +isNfcConnected); +``` + +### tagSession.reset() + +reset(): void + +Resets the connection to this tag and restores the default timeout duration for writing data to the tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let reset = tag.getXXXTag(taginfo).reset(); +console.log("reset:" +reset); +``` + +### tagSession.isTagConnected + +isTagConnected(): boolean + +Checks whether the tag is connected. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the tag is connected; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an Object given by nfc service when tag is dispatched. +let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); +console.log("isTagConnected:" +isTagConnected); +``` + +### tagSession.getMaxSendLength + +getMaxSendLength(): number + +Obtains the maximum length of the data that can be sent to the tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Maximum data length obtained.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object given by the NFC service when a tag is dispatched. +let mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); +console.log("mazSendLen:" +mazSendLen); +``` diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index 4a711c1f7cbf0defdbcd9ea0c28a08e981c594a9..7d8018a4e82916df0c218a10ca7d5e8fdb9e6364 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -79,7 +79,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -106,7 +106,7 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: Clears the default configuration.| +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| **Return value** @@ -274,7 +274,7 @@ promise.then((data) => { isCellularDataRoamingEnabled(slotId: number, callback: AsyncCallback\): void -Checks whether roaming is enabled for the cellular data service. This API uses an asynchronous callback to return the result. +Checks whether the cellular data roaming service is enabled. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -285,7 +285,7 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
- **true**: Roaming is enabled for the cellular data service.
- **false**: Roaming is disabled for the cellular data service.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
- **true**: The cellular data roaming service is enabled.
- **false**: The cellular data roaming service is disabled. | **Example** @@ -299,7 +299,7 @@ data.isCellularDataRoamingEnabled(0,(err, data) => { isCellularDataRoamingEnabled(slotId: number): Promise\ -Checks whether roaming is enabled for the cellular data service. This API uses a promise to return the result. +Checks whether the cellular data roaming service is enabled. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -315,7 +315,7 @@ Checks whether roaming is enabled for the cellular data service. This API uses a | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
- **true**: Roaming is enabled for the cellular data service.
- **false**: Roaming is disabled for the cellular data service.| +| Promise\ | Promise used to return the result.
- **true**: The cellular data roaming service is enabled.
- **false**: The cellular data roaming service is disabled.| **Example** @@ -328,6 +328,241 @@ promise.then((data) => { }); ``` +## data.enableCellularData + +enableCellularData(callback: AsyncCallback): void + +Enables the cellular data service. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +data.enableCellularData((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.enableCellularData + +enableCellularData(): Promise + +Enables the cellular data service. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Return value** + +| Type | Description | +| --------------- | ----------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = data.enableCellularData(); +promise.then((data) => { + console.log(`enableCellularData success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`enableCellularData fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## data.disableCellularData + +disableCellularData(callback: AsyncCallback): void + +Disables the cellular data service. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +data.disableCellularData((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.disableCellularData + +disableCellularData(): Promise + +Disables the cellular data service. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Return value** + +| Type | Description | +| --------------- | --------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = data.disableCellularData(); +promise.then((data) => { + console.log(`disableCellularData success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`disableCellularData fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## data.enableCellularDataRoaming + +enableCellularDataRoaming(slotId: number, callback: AsyncCallback): void + +Enables the cellular data roaming service. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------- | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +data.enableCellularDataRoaming(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.enableCellularDataRoaming + +enableCellularDataRoaming(slotId: number): Promise + +Enables the cellular data roaming service. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------- | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = data.enableCellularDataRoaming(0); +promise.then((data) => { + console.log(`enableCellularDataRoaming success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`enableCellularDataRoaming fail, promise: err->${JSON.stringify(err)}`); +}); +``` + +## data.disableCellularDataRoaming + +disableCellularDataRoaming(slotId: number, callback: AsyncCallback): void + +Disables the cellular data roaming service. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------------------- | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +data.disableCellularDataRoaming(0, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## data.disableCellularDataRoaming + +disableCellularDataRoaming(slotId: number): Promise + +Disables the cellular data roaming service. This API uses a promise to return the result. + +This is a system API. + +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + +**System capability**: SystemCapability.Telephony.CellularData + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------- | +| slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2| + +**Return value** + +| Type | Description | +| --------------- | ------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let promise = data.disableCellularDataRoaming(0); +promise.then((data) => { + console.log(`disableCellularDataRoaming success, promise: data->${JSON.stringify(data)}`); +}).catch((err) => { + console.error(`disableCellularDataRoaming fail, promise: err->${JSON.stringify(err)}`); +}); +``` + + ## DataFlowType Defines the cellular data flow type. diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index 71b0490ea8c610dc0169222042ec7770c19d0a83..82932c99be0a0c8c39ab989d656cb6b0fcde99f5 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -26,6 +26,7 @@ Obtains the USB device list. | Array<Readonly<[USBDevice](#usbdevice)>> | Device information list. | - **Example** + ```js let devicesList = usb.getDevices(); console.log(`devicesList = ${JSON.stringify(devicesList)}`); @@ -93,16 +94,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | device | [USBDevice](#usbdevice) | Yes| USB device information. | - **Return value** + | Type| Description| | -------- | -------- | | Readonly<[USBDevicePipe](#usbdevicepipe)> | USB device pipe for data transfer. | - **Example** + ```js let devicepipe= usb.connectDevice(device); console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); @@ -118,16 +122,19 @@ Checks whether the application has the permission to access the device. **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | deviceName | string | Yes| Device name. | - **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise. | - **Example** + ```js let devicesName="1-1"; let bool = usb.hasRight(devicesName); @@ -144,16 +151,19 @@ Requests the temporary permission for the application to access the USB device. **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | deviceName | string | Yes| Device name. | - **Return value** + | Type| Description| | -------- | -------- | | Promise<boolean> | Returns **true** if the temporary device access permissions are granted; returns **false** otherwise. | - **Example** + ```js let devicesName="1-1"; usb.requestRight(devicesName).then((ret) => { @@ -172,6 +182,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | @@ -179,11 +190,13 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | force | boolean | No| Whether to forcibly claim the USB interface. The default value is **false**, indicating not to forcibly claim the USB interface. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise. | - **Example** + ```js let ret = usb.claimInterface(devicepipe, interfaces); console.log(`claimInterface = ${ret}`); @@ -201,17 +214,20 @@ Before you do this, ensure that you have claimed the interface by calling [usb.c **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | | iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to release. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB interface is successfully released; returns an error code otherwise. | - **Example** + ```js let ret = usb.releaseInterface(devicepipe, interfaces); console.log(`releaseInterface = ${ret}`); @@ -229,17 +245,20 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | | config | [USBConfig](#usbconfig) | Yes| USB configuration to set. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise. | - **Example** + ```js let ret = usb.setConfiguration(devicepipe, config); console.log(`setConfiguration = ${ret}`); @@ -256,17 +275,20 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | | iface | [USBInterface](#usbinterface) | Yes| USB interface to set. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB interface is successfully set; returns an error code otherwise. | - **Example** + ```js let ret = usb.setInterface(devicepipe, interfaces); console.log(`setInterface = ${ret}`); @@ -284,16 +306,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | - **Return value** + | Type| Description| | -------- | -------- | | Uint8Array | Raw descriptor data. The value **undefined** indicates that the operation has failed. | - **Example** + ```js let ret = usb.getRawDescriptor(devicepipe); ``` @@ -310,16 +335,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address. | - **Return value** + | Type| Description| | -------- | -------- | | number | File descriptor of the USB device. The value **-1** indicates that the operation has failed. | - **Example** + ```js let ret = usb.getFileDescriptor(devicepipe); ``` @@ -336,6 +364,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device. | @@ -343,11 +372,13 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | timeout | number | No| Timeout duration. The default value is **0**, indicating no timeout. | - **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Returns the size of the transmitted or received data block if the control transfer is successful; returns **-1** if an exception occurs. | - **Example** + ```js usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { console.log(`controlTransfer = ${JSON.stringify(ret)}`); @@ -366,6 +397,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device. | @@ -374,11 +406,13 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | timeout | number | No| Timeout duration. The default value is **0**, indicating no timeout. | - **Return value** + | Type| Description| | -------- | -------- | | Promise<number> | Returns the size of the transmitted or received data block if the control transfer is successful; returns **-1** if an exception occurs. | - **Example** + ```js // Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission. // Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. @@ -400,16 +434,19 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi **System capability**: SystemCapability.USB.USBManager - **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe. | - **Return value** + | Type| Description| | -------- | -------- | | number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise. | - **Example** + ```js let ret = usb.closePipe(devicepipe); console.log(`closePipe = ${ret}`); @@ -556,3 +593,68 @@ Enumerates request directions. | -------- | -------- | -------- | | USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device. | | USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host. | + +## FunctionType9+ + +Enumerates function types for the USB device. + +This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------------ | ---- | ---------- | +| NONE | 0 | No function.| +| ACM | 1 | ACM function. | +| ECM | 2 | ECM function. | +| HDC | 4 | HDC function. | +| MTP | 8 | Not supported currently.| +| PTP | 16 | Not supported currently.| +| RNDIS | 32 | Not supported currently.| +| MIDI | 64 | Not supported currently.| +| AUDIO_SOURCE | 128 | Not supported currently.| +| NCM | 256 | Not supported currently.| + +## PortModeType9+ + +Enumerates USB port mode types. + +This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| --------- | ---- | ---------------------------------------------------- | +| NONE | 0 | None. | +| UFP | 1 | Upstream facing port, which functions as the sink of power supply. | +| DFP | 2 | Downstream facing port, which functions as the source of power supply. | +| DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.| +| NUM_MODES | 4 | Not supported currently. | + +## PowerRoleType9+ + +Enumerates power role types. + +This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------ | ---- | ---------- | +| NONE | 0 | None. | +| SOURCE | 1 | External power supply.| +| SINK | 2 | Internal power supply.| + +## DataRoleType9+ + +Enumerates data role types. + +This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------ | ---- | ------------ | +| NONE | 0 | None. | +| HOST | 1 | USB host.| +| DEVICE | 2 | USB device.| diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 602a3b7e2a318119b1e8dbfa80a59fdc65a6bede..f49a5fb22443b5c66641581fccb6b4a4f3133232 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -1,4 +1,5 @@ # WLAN +The WLAN module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. > **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -10,20 +11,54 @@ import wifi from '@ohos.wifi'; ``` +## wifi.enableWifi + +enableWifi(): boolean + +Enables WLAN. +This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableWifi + +disableWifi(): boolean + +Disables WLAN. +This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + ## wifi.isWifiActive isWifiActive(): boolean -Checks whether the WLAN is activated. +Checks whether WLAN is enabled. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the WLAN is activated; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| ## wifi.scan @@ -32,14 +67,14 @@ scan(): boolean Starts a scan for WLAN. -**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.LOCATION +**Required permissions**: **ohos.permission.SET_WIFI_INFO** and **ohos.permission.LOCATION** **System capability**: SystemCapability.Communication.WiFi.STA **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the scan is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getScanInfos @@ -48,14 +83,14 @@ getScanInfos(): Promise<Array<WifiScanInfo>> Obtains the scan result. This API uses a promise to return the result. -**Required permissions**: at least one of ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) **System capability**: SystemCapability.Communication.WiFi.STA **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the hotspots detected.| + | **Type**| **Description**| + | -------- | -------- | + | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| ## wifi.getScanInfos @@ -64,14 +99,14 @@ getScanInfos(callback: AsyncCallback<Array<WifiScanInfo>>): void Obtains the scan result. This API uses an asynchronous callback to return the result. -**Required permissions**: at least one of ohos.permission.GET_WIFI_INFO, ohos.permission.GET_WIFI_PEERS_MAC, and ohos.permission.LOCATION +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the hotspots detected.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| **Example** ```js @@ -120,18 +155,21 @@ Obtains the scan result. This API uses an asynchronous callback to return the re Represents WLAN hotspot information. +**System capability**: SystemCapability.Communication.WiFi.STA + | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | | ssid | string | Read only| Hotspot service set identifier (SSID), in UTF-8 format.| | bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| | capabilities | string | Read only| Hotspot capabilities.| -| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| WLAN security type.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| WLAN security type.| | rssi | number | Read only| Received signal strength indicator (RSSI) of the hotspot, in dBm.| | band | number | Read only| Frequency band of the WLAN access point (AP).| | frequency | number | Read only| Frequency of the WLAN AP.| -| channelWidth | number | Read only| Bandwidth of the WLAN AP.| -| centerFrequency0 | number | Read only| Center frequency.| -| centerFrequency1 | number | Read only| Center frequency.| +| channelWidth | number | Read only| Channel width of the WLAN AP.| +| centerFrequency09+ | number | Read only| Center frequency.| +| centerFrequency19+ | number | Read only| Center frequency.| +| infoElems9+ | Array<[WifiInfoElem](#wifiinfoelem9)> | Read only| Information elements.| | timestamp | number | Read only| Timestamp.| @@ -139,103 +177,467 @@ Represents WLAN hotspot information. Enumerates the WLAN security types. +**System capability**: SystemCapability.Communication.WiFi.Core + | **Name**| **Default Value**| **Description**| | -------- | -------- | -------- | -| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type| -| WIFI_SEC_TYPE_OPEN | 1 | Open security type| -| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP)| -| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK)| -| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE)| +| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| +| WIFI_SEC_TYPE_OPEN | 1 | Open security type.| +| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| +| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| +| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| +| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| +| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| +| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| +| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| +| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| -## wifi.addUntrustedConfig7+ +## WifiInfoElem9+ -addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> +Represents a WLAN information element. -Adds untrusted WLAN configuration. This API uses a promise to return the result. +**System capability**: SystemCapability.Communication.WiFi.STA -**Required permissions**: - ohos.permission.SET_WIFI_INFO +| **Name**| **Type**| **Readable/Writable**| **Description**| +| -------- | -------- | -------- | -------- | +| eid | number | Read only| ID of the information element.| +| content | Uint8Array | Read only| Content of the information element.| -**System capability**: - SystemCapability.Communication.WiFi.STA + +## WifiChannelWidth9+ + +Enumerates the Wi-Fi channel widths. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Default Value**| **Description**| +| -------- | -------- | -------- | +| WIDTH_20MHZ | 0 | 20 MHz.| +| WIDTH_40MHZ | 1 | 40 MHz.| +| WIDTH_80MHZ | 2 | 80 MHz.| +| WIDTH_160MHZ | 3 | 160 MHz.| +| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| +| WIDTH_INVALID | 5 | Invalid value.| + + +## wifi.getScanInfosSync9+ + +getScanInfosSync():  Array<[WifiScanInfo](#wifiscaninfo)> + +Obtains the scan result. This API returns the result synchronously. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| + + +## wifi.addDeviceConfig + +addDeviceConfig(config: WifiDeviceConfig): Promise<number> + +Adds network configuration. This API uses a promise to return the result. +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.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| ## WifiDeviceConfig Represents the WLAN configuration. +**System capability**: SystemCapability.Communication.WiFi.STA + | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| Hotspot service set identifier (SSID), in UTF-8 format.| +| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| -| preSharedKey | string | Read only| Private key of the hotspot.| +| preSharedKey | string | Read only| PSK of the hotspot.| | isHiddenSsid | boolean | Read only| Whether to hide the network.| -| securityType | [WifiSecurityType](#WifiSecurityType) | Read only| Security type.| +| 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.| + + +## IpType7+ + +Enumerate the IP address types. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| STATIC | 0 | Static IP address.| +| DHCP | 1 | IP address allocated by DHCP.| +| UNKNOWN | 2 | Not specified.| + + +## IpConfig7+ + +Represents IP configuration information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable/Writable**| **Description**| +| -------- | -------- | -------- | -------- | +| ipAddress | number | Read only| IP address.| +| gateway | number | Read only| Gateway.| +| dnsServers | number[] | Read only| Domain name server (DNS) information.| +| domains | Array<string> | Read only| Domain information.| + + +## WifiEapConfig9+ + +Represents EAP configuration information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable/Writable**| **Description**| +| -------- | -------- | -------- | -------- | +| eapMethod | [EapMethod](#eapmethod9) | Read only| EAP authentication method.| +| phase2Method | [Phase2Method](#phase2method9) | Read only| Phase 2 authentication method.| +| identity | string | Read only| Identity Information.| +| anonymousIdentity | string | Read only| Anonymous identity.| +| password | string | Read only| Password.| +| caCertAliases | string | Read only| CA certificate alias.| +| caPath | string | Read only| CA certificate path.| +| clientCertAliases | string | Read only| Client certificate alias.| +| altSubjectMatch | string | Read only| A string to match the alternate subject.| +| domainSuffixMatch | string | Read only| A string to match the domain suffix.| +| realm | string | Read only| Realm for the passpoint credential.| +| plmn | string | Read only| Public land mobile network (PLMN) of the passpoint credential provider.| +| eapSubId | number | Read only| Sub-ID of the SIM card.| + + +## EapMethod9+ + +Enumerates the EAP authentication methods. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| EAP_NONE | 0 | Not specified.| +| EAP_PEAP | 1 | PEAP.| +| EAP_TLS | 2 | TLS.| +| EAP_TTLS | 3 | TTLS.| +| EAP_PWD | 4 | Password.| +| EAP_SIM | 5 | SIM.| +| EAP_AKA | 6 | AKA.| +| EAP_AKA_PRIME | 7 | AKA Prime.| +| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| + + +## Phase2Method9+ + +Enumerates the Phase 2 authentication methods. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| PHASE2_NONE | 0 | Not specified.| +| PHASE2_PAP | 1 | PAP.| +| PHASE2_MSCHAP | 2 | MS-CHAP.| +| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| +| PHASE2_GTC | 4 | GTC .| +| PHASE2_SIM | 5 | SIM.| +| PHASE2_AKA | 6 | AKA.| +| PHASE2_AKA_PRIME | 7 | AKA Prime.| + + +## wifi.addDeviceConfig + +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. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + + +## wifi.addUntrustedConfig7+ + +addUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> + +Adds the configuration of an untrusted network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.addUntrustedConfig7+ addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void -Adds untrusted WLAN configuration. This API uses an asynchronous callback to return the result. +Adds the configuration of an untrusted network. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.SET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| ## wifi.removeUntrustedConfig7+ removeUntrustedConfig(config: WifiDeviceConfig): Promise<boolean> -Removes untrusted WLAN configuration. This API uses a promise to return the result. +Removes the configuration of an untrusted network. This API uses a promise to return the result. **Required permissions**: ohos.permission.SET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove. | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<boolean> | Promise used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.removeUntrustedConfig7+ removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void -Removes untrusted WLAN configuration. This API uses an asynchronous callback to return the result. +Removes the configuration of an untrusted network. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.SET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.STA **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#WifiDeviceConfig) | Yes| WLAN configuration to remove. | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result. The value **true** indicates that the operation is successful; **false** indicates the opposite.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig): Promise<number> + +Adds the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the network configuration ID.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(config: WifiDeviceConfig): Promise<boolean> + +Removes the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<boolean>): void + +Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| + + +## wifi.getCandidateConfigs9+ + +getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains candidate network configuration. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| + + +## wifi.connectToCandidateConfig9+ + +connectToCandidateConfig(networkId: number): boolean + +Connects to a candidate network. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the candidate network configuration.| + +**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. + +**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| Network configuration ID.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.connectToDevice + +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 capability**: + SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disconnect + +disconnect(): boolean + +Connects to the specified network. +This is a system API. + +**Required permissions**: + ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getSignalLevel @@ -249,15 +651,15 @@ 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.| + | **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].| + | **Type**| **Description**| + | -------- | -------- | + | number | Signal level obtained. The value range is [0, 4].| ## wifi.getLinkedInfo @@ -271,9 +673,9 @@ 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.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| ## wifi.getLinkedInfo @@ -287,9 +689,9 @@ 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 WLAN connection information obtained.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -315,25 +717,34 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r Represents the WLAN connection information. +**System capability**: SystemCapability.Communication.WiFi.STA + | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | -| ssid | string | Read only| Hotspot SSID, in UTF-8 format.| +| ssid | string | Read only| SSID, in UTF-8 format.| | bssid | string | Read only| BSSID of the hotspot.| -| rssi | number | Read only| RSSI of the hotspot, in dBm. | +| networkId | number | Read only| Network configuration ID, which is available only to system applications.| +| 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.| +| 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.| -| connState | [ConnState](#ConnState) | Read only| WLAN connection state.| +| suppState | [SuppState](#suppstate) | Read only| Supplicant state, which is available only to system applications.| +| connState | [ConnState](#connstate) | Read only| WLAN connection state.| ## ConnState Enumerates the WLAN connection states. +**System capability**: SystemCapability.Communication.WiFi.STA + | Name| Default Value| Description| | -------- | -------- | -------- | | SCANNING | 0 | The device is scanning for available APs.| @@ -346,6 +757,28 @@ Enumerates the WLAN connection states. | UNKNOWN | 7 | Failed to set up a WLAN connection.| +## SuppState + +Enumerates the supplicant states. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | The supplicant is disconnected from the AP.| +| INTERFACE_DISABLED | 1 | The network interface is disabled.| +| INACTIVE | 2 | The supplicant is inactive.| +| SCANNING | 3 | The supplicant is scanning for a WLAN connection.| +| AUTHENTICATING | 4 | The supplicant is being authenticated.| +| ASSOCIATING | 5 | The supplicant is being associated with an AP.| +| ASSOCIATED | 6 | The supplicant is associated with an AP.| +| FOUR_WAY_HANDSHAKE | 7 | A four-way handshake is being performed for the supplicant.| +| GROUP_HANDSHAKE | 8 | A group handshake is being performed for the supplicant.| +| COMPLETED | 9 | The authentication is complete.| +| UNINITIALIZED | 10 | The supplicant failed to set up a connection.| +| INVALID | 11 | Invalid value.| + + ## wifi.isConnected7+ isConnected(): boolean @@ -357,9 +790,41 @@ Checks whether the WLAN is connected. **System capability**: SystemCapability.Communication.WiFi.STA **Return value** -| **Type**| **Description**| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + + +## wifi.getSupportedFeatures7+ + +getSupportedFeatures(): number + +Obtains the features supported by this device. +This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | number | Feature value.| + +**Feature IDs** + +| Value| Description| | -------- | -------- | -| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| ## wifi.isFeatureSupported7+ @@ -368,135 +833,430 @@ isFeatureSupported(featureId: number): boolean Checks whether the device supports the specified WLAN feature. -**Required permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Parameters** + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.getDeviceMacAddress7+ + +getDeviceMacAddress(): string[] + +Obtains the device MAC address. +This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_LOCAL_MAC and ohos.permission.GET_WIFI_INFO (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | string[] | MAC address obtained.| + + +## wifi.getIpInfo7+ + +getIpInfo(): IpInfo + +Obtains IP information. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#ipinfo7) | IP information obtained.| + + +## IpInfo7+ + +Represents IP information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable/Writable**| **Description**| +| -------- | -------- | -------- | -------- | +| ipAddress | number | Read only| IP address.| +| gateway | number | Read only| Gateway.| +| netmask | number | Read only| Subnet mask.| +| primaryDns | number | Read only| IP address of the preferred DNS server.| +| secondDns | number | Read only| IP address of the alternate DNS server.| +| serverIp | number | Read only| IP address of the DHCP server.| +| leaseDuration | number | Read only| Lease duration of the IP address.| + + +## wifi.getCountryCode7+ + +getCountryCode(): string + +Obtains the country code. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| + + +## wifi.reassociate7+ + +reassociate(): boolean + +Re-associates with the network. +This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.reconnect7+ + +reconnect(): boolean + +Reconnects to the network. +This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getDeviceConfigs7+ + +getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains network configuration. +This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| + + +## wifi.updateNetwork7+ + +updateNetwork(config: WifiDeviceConfig): boolean + +Updates network configuration. +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.| + + +## wifi.disableNetwork7+ + +disableNetwork(netId: number): boolean + +Disables network configuration. +This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the network configuration to disable.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeAllNetwork7+ + +removeAllNetwork(): boolean + +Removes the configuration of all networks. +This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeDevice7+ + +removeDevice(id: number): boolean + +Removes the configuration of a network. +This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | id | number | Yes| ID of the network configuration to remove.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.enableHotspot7+ + +enableHotspot(): boolean + +Enables this hotspot. +This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableHotspot7+ + +disableHotspot(): boolean + +Disables this hotspot. +This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isHotspotDualBandSupported7+ + +isHotspotDualBandSupported(): boolean + +Checks whether the hotspot supports dual band. +This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.isHotspotActive7+ + +isHotspotActive(): boolean -**System capability**: SystemCapability.Communication.WiFi.Core +Checks whether this hotspot is active. +This is a system API. -**Parameters** +**Required permissions**: ohos.permission.GET_WIFI_INFO -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| featureId | number | Yes| Feature ID.| +**System capability**: SystemCapability.Communication.WiFi.AP.Core **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| - -**Feature IDs** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| -| Value| Description| -| -------- | -------- | -| 0x0001 | WLAN infrastructure mode| -| 0x0002 | 5 GHz bandwidth| -| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| -| 0x0008 | Wi-Fi Direct| -| 0x0010 | SoftAP| -| 0x0040 | Wi-Fi AWare| -| 0x8000 | WLAN AP/STA concurrency| -| 0x8000000 | WPA3 Personal (WPA-3 SAE)| -| 0x10000000 | WPA3-Enterprise Suite-B | -| 0x20000000 | Enhanced open feature| +## wifi.setHotspotConfig7+ -## wifi.getIpInfo7+ +setHotspotConfig(config: HotspotConfig): boolean -getIpInfo(): IpInfo +Sets hotspot configuration. +This is a system API. -Obtains IP information. +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG -**Required permissions**: ohos.permission.GET_WIFI_INFO +**System capability**: SystemCapability.Communication.WiFi.AP.Core -**System capability**: SystemCapability.Communication.WiFi.STA +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| [IpInfo](#IpInfo) | IP information obtained.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -## IpInfo7+ +## HotspotConfig7+ -Represents IP information. +Represents the hotspot configuration. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core | **Name**| **Type**| **Readable/Writable**| **Description**| | -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address| -| gateway | number | Read only| Gateway| -| netmask | number | Read only| Subnet mask| -| primaryDns | number | Read only| IP address of the preferred DNS server| -| secondDns | number | Read only| IP address of the alternate DNS server| -| serverIp | number | Read only| IP address of the DHCP server| -| leaseDuration | number | Read only| Lease duration of the IP address| +| ssid | string | Read only| SSID, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| +| band | number | Read only| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Read only| SPK of the hotspot.| +| maxConn | number | Read only| Maximum number of connections allowed.| -## wifi.getCountryCode7+ +## wifi.getHotspotConfig7+ -getCountryCode(): string +getHotspotConfig(): HotspotConfig -Obtains the country code. +obtains hotspot configuration. +This is a system API. -**Required permissions**: ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG -**System capability**: SystemCapability.Communication.WiFi.Core +**System capability**: SystemCapability.Communication.WiFi.AP.Core **Return value** -| **Type**| **Description**| -| -------- | -------- | -| string | Country code obtained.| + | **Type**| **Description**| + | -------- | -------- | + | [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| -## wifi.getP2pLinkedInfo8+ +## wifi.getStations7+ -getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> +getStations():  Array<[StationInfo](#stationinfo7)> -Obtains peer-to-peer (P2P) connection information. This API uses a promise to return the result. +Obtains information about the connected stations. +This is a system API. -**Required permissions**: ohos.permission.GET_WIFI_INFO +**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.P2P +**System capability**: SystemCapability.Communication.WiFi.AP.Core **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Promise used to return the P2P connection information obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[StationInfo](#stationinfo7)> | Connected stations obtained.| + + +## StationInfo7+ + +Represents the station information. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable/Writable**| **Description**| +| -------- | -------- | -------- | -------- | +| name | string | Read only| Device name.| +| macAddress | string | Read only| MAC address.| +| ipAddress | string | Read only| IP address.| ## wifi.getP2pLinkedInfo8+ -getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void +getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> -Obtains P2P connection information. This API uses an asynchronous callback to return the result. +Obtains P2P link information. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO **System capability**: SystemCapability.Communication.WiFi.P2P -**Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback used to return the P2P connection information obtained.| +**Return value** + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise used to return the P2P link information obtained.| + ## WifiP2pLinkedInfo8+ -Represents the WLAN connection information. +Represents the P2P link information. + +**System capability**: SystemCapability.Communication.WiFi.P2P | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | -| connectState | [P2pConnectState](#P2pConnectState) | Read only| P2P connection state.| -| isGroupOwner | boolean | Read only| Whether it is a group owner.| -| groupOwnerAddr | string | Read only| MAC address of the group owner.| +| connectState | [P2pConnectState](#p2pconnectstate8) | Read only| P2P connection state.| +| isGroupOwner | boolean | Read only| Whether the device is the group owner.| +| groupOwnerAddr | string | Read only| MAC address of the group. ## P2pConnectState8+ Enumerates the P2P connection states. +**System capability**: SystemCapability.Communication.WiFi.P2P + | Name| Default Value| Description| | -------- | -------- | -------- | -| DISCONNECTED | 0 | Disconnected| -| CONNECTED | 1 | Connected| +| DISCONNECTED | 0 | Disconnected.| +| CONNECTED | 1 | Connected.| + + +## wifi.getP2pLinkedInfo8+ + +getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void + +Obtains P2P link information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#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.| ## wifi.getCurrentGroup8+ @@ -510,162 +1270,124 @@ 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](#WifiP2pGroupInfo)> | Promise used to return the P2P group information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| ## wifi.getCurrentGroup8+ getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void -Obtains the P2P group information. This API uses an asynchronous callback to return the result. +Obtains the current P2P group information. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> | Yes| Callback used to return the P2P group information obtained.| + | 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.| -## wifi.getP2pGroups9+ -getP2pGroups(): Promise<Array<WifiP2pGroupInfo> +## wifi.getP2pPeerDevices8+ + +getP2pPeerDevices(): Promise<WifiP2pDevice[]> -Obtains information about all P2P groups. This API uses a promise to return the result. +Obtains the peer device list in a P2P connection. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** -| Type| Description| -| -------- | -------- | -| Promise< Array<[WifiP2pGroupInfo](#WifiP2pGroupInfo)> > | Information about all created P2P groups obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise used to return the peer device list.| -## wifi.getP2pGroups9+ -getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>): void +## wifi.getP2pPeerDevices8+ -Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. +getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void + +Obtains the peer device list in a P2P connection. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback< Array<[WifiP2pGroupInfo](#WifiP2pGroupInfo)>> | Yes| Callback invoked to return the P2P group information obtained.| - -## WifiP2pGroupInfo8+ + | 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.| -Represents the P2P group information. - -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| isP2pGo | boolean | Read only| Whether it is a group.| -| ownerInfo | [WifiP2pDevice](#WifiP2pDevice) | Read only| Device information of the group.| -| passphrase | string | Read only| Private key of the group.| -| interface | string | Read only| Interface name.| -| groupName | string | Read only| Group name.| -| networkId | number | Read only| Network ID.| -| frequency | number | Read only| Frequency of the group.| -| clientDevices | [WifiP2pDevice[]](#WifiP2pDevice) | Read only| List of connected devices.| -| goIpAddress | string | Read only| IP address of the group.| ## WifiP2pDevice8+ Represents the P2P device information. +**System capability**: SystemCapability.Communication.WiFi.P2P + | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | | deviceName | string | Read only| Device name.| | deviceAddress | string | Read only| MAC address of the device.| | primaryDeviceType | string | Read only| Type of the primary device.| -| deviceStatus | [P2pDeviceStatus](#P2pDeviceStatus) | Read only| Device status.| +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Read only| Device status.| | groupCapabilitys | number | Read only| Group capabilities.| -## P2pDeviceStatus8+ - -Enumerates the device states. - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| CONNECTED | 0 | Connected| -| INVITED | 1 | Invited| -| FAILED | 2 | Failed| -| AVAILABLE | 3 | Available| -| UNAVAILABLE | 4 | Unavailable| - - -## wifi.getP2pPeerDevices8+ - -getP2pPeerDevices(): Promise<WifiP2pDevice[]> -Obtains the list of peer devices in a P2P connection. This API uses a promise to return the result. +## P2pDeviceStatus8+ -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION +Enumerates the P2P device states. **System capability**: SystemCapability.Communication.WiFi.P2P -**Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pDevice[]](#WifiP2pDevice)> | Promise used to return the peer device list obtained.| - - -## wifi.getP2pPeerDevices8+ - -getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void - -Obtains the list of peer devices in a P2P connection. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P +| Name| Default Value| Description| +| -------- | -------- | -------- | +| CONNECTED | 0 | Connected.| +| INVITED | 1 | Invited.| +| FAILED | 2 | Failed.| +| AVAILABLE | 3 | Available.| +| UNAVAILABLE | 4 | Unavailable.| -**Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback used to return the peer device list obtained.| ## wifi.getP2pLocalDevice9+ getP2pLocalDevice(): Promise<WifiP2pDevice> -Obtains local device information. This API uses a promise to return the result. +Obtains the local device information in a P2P connection. This API uses a promise to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pDevice](#WifiP2pDevice)> | Promise used to return the local device information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| -## wifi.getP2pLocalDevice8+ +## wifi.getP2pLocalDevice9+ getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void -Obtains local device information. This API uses an asynchronous callback to return the result. +Obtains the local device information in a P2P connection. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG **System capability**: SystemCapability.Communication.WiFi.P2P **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pDevice](#WifiP2pDevice)> | Yes| Callback invoked to returnthe local device information obtained.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + ## wifi.createGroup8+ -createGroup(config: WifiP2PConfig): boolean; +createGroup(config: WifiP2PConfig): boolean Creates a P2P group. @@ -675,41 +1397,47 @@ Creates a P2P group. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Group configuration.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + ## WifiP2PConfig8+ Represents P2P configuration. +**System capability**: SystemCapability.Communication.WiFi.P2P + | Name| Type| Readable/Writable| Description| | -------- | -------- | -------- | -------- | | deviceAddress | string | Read only| Device address.| -| netId | number | Read only| Network ID. The value **-1** indicates that a temporary group, and **-2** indicates that a persistent group.| -| passphrase | string | Read only| Private key of the group.| +| netId | number | Read only| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| +| passphrase | string | Read only| Passphrase of the group.| | groupName | string | Read only| Name of the group.| -| goBand | [GroupOwnerBand](#GroupOwnerBand) | Read only| Bandwidth of the group.| +| goBand | [GroupOwnerBand](#groupownerband8) | Read only| Frequency band of the group.| ## GroupOwnerBand8+ -Enumerates the P2P group bandwidths. +Enumerates the P2P group frequency bands. + +**System capability**: SystemCapability.Communication.WiFi.P2P | Name| Default Value| Description| | -------- | -------- | -------- | -| GO_BAND_AUTO | 0 | Auto| -| GO_BAND_2GHZ | 1 | 2 GHz| -| GO_BAND_5GHZ | 2 | 5 GHz| +| GO_BAND_AUTO | 0 | Auto.| +| GO_BAND_2GHZ | 1 | 2 GHz.| +| GO_BAND_5GHZ | 2 | 5 GHz.| + ## wifi.removeGroup8+ -removeGroup(): boolean; +removeGroup(): boolean Removes this P2P group. @@ -718,14 +1446,14 @@ 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.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.p2pConnect8+ -p2pConnect(config: WifiP2PConfig): boolean; +p2pConnect(config: WifiP2PConfig): boolean Sets up a P2P connection. @@ -735,14 +1463,14 @@ Sets up a P2P connection. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiP2PConfig](#WifiP2PConfig) | Yes| Connection configuration.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Connection configuration.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -792,7 +1520,7 @@ Sets up a P2P connection. } wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); - var recvP2pPersistentGroupChangeFunc = result => { + var recvP2pPersistentGroupChangeFunc = () => { console.info("p2p persistent group change receive event"); wifi.getCurrentGroup((err, data) => { @@ -814,7 +1542,7 @@ Sets up a P2P connection. ## wifi.p2pCancelConnect8+ -p2pCancelConnect(): boolean; +p2pCancelConnect(): boolean Cancels this P2P connection. @@ -823,14 +1551,14 @@ 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.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.startDiscoverDevices8+ -startDiscoverDevices(): boolean; +startDiscoverDevices(): boolean Starts to discover devices. @@ -839,14 +1567,14 @@ 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.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.stopDiscoverDevices8+ -stopDiscoverDevices(): boolean; +stopDiscoverDevices(): boolean Stops discovering devices. @@ -855,9 +1583,106 @@ Stops discovering devices. **System capability**: SystemCapability.Communication.WiFi.P2P **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.deletePersistentGroup8+ + +deletePersistentGroup(netId: number): boolean + +Deletes a persistent group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of a group to delete.| + +**Return value** + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getP2pGroups9+ +This is a system API. + +getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> + +Obtains information about all P2P groups. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + | Type| Description| + | -------- | -------- | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| + + +## WifiP2pGroupInfo8+ + +Represents the P2P group information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable/Writable| Description| +| -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Read only| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Read only| Device information of the group.| +| passphrase | string | Read only| Passphrase of the group.| +| interface | string | Read only| Interface name.| +| groupName | string | Read only| Group name.| +| networkId | number | Read only| Network ID.| +| frequency | number | Read only| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Read only| List of connected devices.| +| goIpAddress | string | Read only| IP address of the group.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void + +Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. + +**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.| + + +## wifi.setDeviceName8+ + +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 capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | devName | string | Yes| Device name to set.| + +**Return value** + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.on('wifiStateChange')7+ @@ -871,10 +1696,10 @@ 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**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| **WLAN states** @@ -897,10 +1722,10 @@ 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**.| -| callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -930,10 +1755,10 @@ 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**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| **WLAN connection states** @@ -954,10 +1779,10 @@ 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**.| -| callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiScanStateChange')7+ @@ -971,10 +1796,10 @@ 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**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiScanStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| **WLAN scan states** @@ -1013,10 +1838,10 @@ 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**.| -| callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| ## wifi.off('wifiRssiChange')7+ @@ -1030,10 +1855,10 @@ 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**.| -| callback | Callback<number> | No| Callback used to return the RSSI, in dBm. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | No| Callback used to return the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('hotspotStateChange')7+ @@ -1047,10 +1872,10 @@ 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**.| -| callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| **Hotspot states** @@ -1073,10 +1898,10 @@ 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**.| -| callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pStateChange')8+ @@ -1090,10 +1915,10 @@ 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**.| -| callback | Callback<number> | Yes| Callback invoked to return the P2P state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| **P2P states** @@ -1116,10 +1941,10 @@ 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**.| -| callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pConnectionChange')8+ @@ -1133,10 +1958,10 @@ 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**.| -| callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | Yes| Callback invoked to return the P2P connection state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the P2P connection state.| ## wifi.off('p2pConnectionChange')8+ @@ -1150,10 +1975,10 @@ 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**.| -| callback | Callback<[WifiP2pLinkedInfo](#WifiP2pLinkedInfo)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDeviceChange')8+ @@ -1167,10 +1992,10 @@ 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**.| -| callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P device state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P device state.| ## wifi.off('p2pDeviceChange')8+ @@ -1184,10 +2009,10 @@ 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**.| -| callback | Callback<[WifiP2pDevice](#WifiP2pDevice)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPeerDeviceChange')8+ @@ -1201,10 +2026,10 @@ 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**.| -| callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | Yes| Callback invoked to return the P2P peer device state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P peer device state.| ## wifi.off('p2pPeerDeviceChange')8+ @@ -1218,10 +2043,10 @@ 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**.| -| callback | Callback<[WifiP2pDevice[]](#WifiP2pDevice)> | No| Callback used to return the P2P peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pPersistentGroupChange')8+ @@ -1235,10 +2060,10 @@ 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**.| -| callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| ## wifi.off('p2pPersistentGroupChange')8+ @@ -1252,10 +2077,10 @@ 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**.| -| callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('p2pDiscoveryChange')8+ @@ -1269,10 +2094,10 @@ 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**.| -| callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| **P2P discovered device states** @@ -1293,7 +2118,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**.| -| callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index 2e2e9394b2a4361fa8adad332c459d4ff33a4e4d..f54b65d4b492cf65bb367b52a021cb1f061af6bb 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,6 +1,7 @@ # WLAN +This **wifiext** module provides WLAN extension interfaces for non-universal products. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs described in this document are used only for non-universal products, such as routers. @@ -17,13 +18,11 @@ enableHotspot(): boolean; Enables the WLAN hotspot. -- Required permissions: - ohos.permission.MANAGE_WIFI_HOTSPOT_EXT +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT -- System capability: - SystemCapability.Communication.WiFi.AP.Extension +**System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Return value +**Return value** | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -35,13 +34,11 @@ disableHotspot(): boolean; Disables the WLAN hotspot. -- Required permissions: - ohos.permission.MANAGE_WIFI_HOTSPOT_EXT +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT -- System capability: - SystemCapability.Communication.WiFi.AP.Extension +**System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Return value +**Return value** | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| @@ -51,24 +48,24 @@ Disables the WLAN hotspot. getSupportedPowerModel(): Promise<Array<PowerModel>> -Obtains the supported power models. The method uses a promise to return the result. +Obtains the supported power models. This API uses a promise to return the result. -- Required permissions: - ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: - SystemCapability.Communication.WiFi.AP.Extension +**System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Return value +**Return value** | Type| Description| | -------- | -------- | - | Promise<Array<[PowerModel](#PowerModel)>> | Promise used to return the power models obtained.| + | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| ## PowerModel Enumerates of the power models. +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + | Name| Default Value| Description| | -------- | -------- | -------- | | SLEEPING | 0 | Sleeping| @@ -80,54 +77,48 @@ Enumerates of the power models. getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): void -Obtains the supported power models. The method uses an asynchronous callback to return the result. +Obtains the supported power models. This API uses an asynchronous callback to return the result. -- Required permissions: - ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: - SystemCapability.Communication.WiFi.AP.Extension +**System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Callback used to return the power models obtained.| + | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| ## wifiext.getPowerModel getPowerModel(): Promise<PowerModel> -Obtains the power model. The method uses a promise to return the result. +Obtains the power model. This API uses a promise to return the result. -- Required permissions: - ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: - SystemCapability.Communication.WiFi.AP.Extension +**System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Return value +**Return value** | Type| Description| | -------- | -------- | - | Promise<[PowerModel](#PowerModel)> | Promise used to return the power model obtained.| + | Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| ## wifiext.getPowerModel getPowerModel(callback: AsyncCallback<PowerModel>): void -Obtains the power model. The method uses an asynchronous callback to return the result. +Obtains the power model. This API uses an asynchronous callback to return the result. -- Required permissions: - ohos.permission.GET_WIFI_INFO +**Required permissions**: ohos.permission.GET_WIFI_INFO -- System capability: - SystemCapability.Communication.WiFi.AP.Extension +**System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Callback invoked to return the power mode obtained.| + | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power mode obtained. If **err** is not **0**, an error has occurred.| ## wifiext.setPowerModel @@ -136,18 +127,16 @@ setPowerModel(model: PowerModel) : boolean; Sets the power model. -- Required permissions: - ohos.permission.MANAGE_WIFI_HOTSPOT_EXT +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT -- System capability: - SystemCapability.Communication.WiFi.AP.Extension +**System capability**: SystemCapability.Communication.WiFi.AP.Extension -- Parameters +**Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | model | AsyncCallback<[PowerModel](#PowerModel)> | Yes| Power model to set.| + | model | AsyncCallback<[PowerModel](#powermodel)> | Yes| Power model to set.| -- Return value +**Return value** | **Type**| **Description**| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index b5eab0ff1825741b77cf81ae966c499aff4c1398..76bba2f5b15c6a9da9b2f4bb4f5201f4552a9cbd 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -25,21 +25,24 @@ Enumerates the window types. | Name | Value| Description | | ----------------- | ------ | ------------------ | -| TYPE_APP | 0 | Application subwindow. This type can be used only in the FA model.| +| TYPE_APP | 0 | Application subwindow.
**Model restriction**: This API can be used only in the FA model.| | TYPE_SYSTEM_ALERT | 1 | System alert window.| -| TYPE_INPUT_METHOD9+ | 2 | Input method window. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_STATUS_BAR9+ | 3 | Status bar. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_PANEL9+ | 4 | Notification panel. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_KEYGUARD9+ | 5 | Lock screen. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_VOLUME_OVERLAY9+ | 6 | Volume bar. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_NAVIGATION_BAR9+ | 7 | Navigation bar. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_FLOAT9+ | 8 | Floating window. This type can be used only in the stage model.
**Required permissions**: ohos.permission.SYSTEM_FLOAT_WINDOW| -| TYPE_WALLPAPER9+ | 9 | Wallpaper. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_DESKTOP9+ | 10 | Home screen. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_LAUNCHER_RECENT9+ | 11 | Recent tasks screen. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_LAUNCHER_DOCK9+ | 12 | Dock bar on the home screen. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_VOICE_INTERACTION9+ | 13 | Voice assistant. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| -| TYPE_POINTER9+ | 14 | Mouse. This type can be used only in the stage model.
This is a system API and cannot be called by third-party applications.| +| TYPE_INPUT_METHOD9+ | 2 | Input method window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_STATUS_BAR9+ | 3 | Status bar.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_PANEL9+ | 4 | Notification panel.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_KEYGUARD9+ | 5 | Lock screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_VOLUME_OVERLAY9+ | 6 | Volume bar.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_NAVIGATION_BAR9+ | 7 | Navigation bar.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_FLOAT9+ | 8 | Floating window.
**Model restriction**: This API can be used only in the stage model.
**Required permissions**: ohos.permission.SYSTEM_FLOAT_WINDOW| +| TYPE_WALLPAPER9+ | 9 | Wallpaper.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_DESKTOP9+ | 10 | Home screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_LAUNCHER_RECENT9+ | 11 | Recent tasks screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_LAUNCHER_DOCK9+ | 12 | Dock bar on the home screen.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_VOICE_INTERACTION9+ | 13 | Voice assistant.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_POINTER9+ | 14 | Mouse.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_FLOAT_CAMERA9+ | 15 | Floating camera window.
**Model restriction**: This API can be used only in the stage model.
**Required permissions**: ohos.permission.SYSTEM_FLOAT_WINDOW| +| TYPE_DIALOG9+ | 16 | Modal window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +| TYPE_SCREENSHOT9+ | 17 | Screenshot window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| ## AvoidAreaType7+ @@ -58,7 +61,7 @@ Enumerates the types of the area where the window cannot be displayed. Enumerates the window modes. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -74,7 +77,7 @@ This is a system API and cannot be called by third-party applications. Enumerates the window layout modes. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -119,11 +122,26 @@ Enumerates the window orientations. | AUTO_ROTATION_LANDSCAPE_RESTRICTED | 10 | Switched-determined auto rotation in the horizontal direction.| | LOCKED | 11 | Locked.| +## BlurStyle9+ + +Enumerates the window blur styles. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Value | Description | +| ------- | ---- | -------------------- | +| OFF | 0 | Blur disabled. | +| THIN | 1 | Thin blur.| +| REGULAR | 2 | Regular blur.| +| THICK | 3 | Thick blur.| + ## SystemBarRegionTint8+ Describes the callback for a single system bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -139,7 +157,7 @@ This is a system API and cannot be called by third-party applications. Describes the callback for the current system bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -169,7 +187,7 @@ Describes the area where the window cannot be displayed. | Name | Type | Readable| Writable| Description | | ---------- | ------------- | ---- | ---- | ------------------ | -| visible9+ | boolean | Yes | Yes | Whether the area is visible.| +| visible9+ | boolean | Yes | Yes | Whether the window can be displayed in the area.| | leftRect | [Rect](#rect) | Yes | Yes | Rectangle on the left of the screen.| | topRect | [Rect](#rect) | Yes | Yes | Rectangle at the top of the screen.| | rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.| @@ -192,20 +210,20 @@ Describes the window properties. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable| Writable| Description | -| ------------------------------- | ------------------------- | ---- | ---- | -------------------------------------------- | -| windowRect7+ | [Rect](#rect) | Yes | Yes | Window size. | -| type7+ | [WindowType](#windowtype) | Yes | Yes | Window type. | -| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | -| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. | -| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | -| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | -| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | -| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness.
**NOTE**
This attribute is deprecated since API version 9.
| -| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | -| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | -| isRoundCorner7+ | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`. | -| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | +| Name | Type | Readable| Writable| Description | +| ------------------------------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | +| windowRect7+ | [Rect](#rect) | Yes | Yes | Window size. | +| type7+ | [WindowType](#windowtype) | Yes | Yes | Window type. | +| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | +| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. | +| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | +| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | +| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | +| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| +| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | +| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | +| isRoundCorner(deprecated) | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| +| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | ## ColorSpace8+ @@ -218,13 +236,58 @@ Describes the color gamut mode. | DEFAULT | 0 | Default color gamut mode.| | WIDE_GAMUT | 1 | Wide color gamut mode. | +## ScaleOptions9+ + +Describes the scale parameters. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | -------------------------------------------------- | +| x | number | No | Yes | Scale factor of the x-axis. The default value is `1.0`. | +| y | number | No | Yes | Scale factor of the y-axis. The default value is `1.0`. | +| pivotX | number | No | Yes | X coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| +| pivotY | number | No | Yes | Y coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| + +## RotateOptions9+ + +Describes the rotation parameters. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type| Readable| Writable| Description | +| ------ | -------- | ---- | ---- | -------------------------------------------------- | +| x | number | No | Yes | Rotation angle around the x-axis. The default value is `0.0`. | +| y | number | No | Yes | Rotation angle around the y-axis. The default value is `0.0`. | +| z | number | No | Yes | Rotation angle around the z-xis. The default value is `0.0`. | +| pivotX | number | No | Yes | X coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| +| pivotY | number | No | Yes | Y coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| + +## TranslateOptions9+ + +Describes the translation parameters. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name| Type| Readable| Writable| Description | +| ---- | -------- | ---- | ---- | ---------------------------- | +| x | number | No | Yes | Distance to translate along the x-axis. The default value is `0.0`.| +| y | number | No | Yes | Distance to translate along the y-axis. The default value is `0.0`.| +| z | number | No | Yes | Distance to translate along the z-axis. The default value is `0.0`.| + ## window.create7+ create(id: string, type: WindowType, callback: AsyncCallback<Window>): void Creates a subwindow. This API uses an asynchronous callback to return the result. -This API can be used only in the FA model. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -240,13 +303,14 @@ This API can be used only in the FA model. ```js var windowClass = null; - let promise = window.create("first", window.WindowType.TYPE_APP); - promise.then((data)=> { - windowClass = data; - console.info('SubWindow created. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); - }); +window.create("first", window.WindowType.TYPE_APP,(err,data) => { + if(err.code){ + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); +}); ``` ## window.create7+ @@ -255,7 +319,7 @@ create(id: string, type: WindowType): Promise<Window> Creates a subwindow. This API uses a promise to return the result. -This API can be used only in the FA model. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -279,7 +343,7 @@ var windowClass = null; let promise = window.create("first", window.WindowType.TYPE_APP); promise.then((data)=> { windowClass = data; - console.info('SubWindow created. Data: ' + JSON.stringify(data)); + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); }); @@ -300,7 +364,7 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype) | Yes | Window type. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window created. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | **Example** @@ -308,11 +372,11 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). var windowClass = null; window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { if (err.code) { - console.error('Failed to create the Window. Cause: ' + JSON.stringify(err)); + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); return; } windowClass = data; - console.info('Window created. Data: ' + JSON.stringify(data)); + console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); windowClass.resetSize(500, 1000); }); ``` @@ -337,7 +401,7 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). | Type | Description | | -------------------------------- | --------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the window created. | +| Promise<[Window](#window)> | Promise used to return the subwindow created.| **Example** @@ -345,8 +409,8 @@ Creates a subwindow (in API version 8) or a system window (from API version 9). var windowClass = null; let promise = window.create(this.context, "alertWindow", window.WindowType.TYPE_SYSTEM_ALERT); promise.then((data)=> { - windowClass = data; - console.info('Window created. Data:' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); }); @@ -377,7 +441,7 @@ var windowClass = null; return; } windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)); + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); }); ``` @@ -408,7 +472,7 @@ var windowClass = null; let promise = window.find("alertWindow"); promise.then((data)=> { windowClass = data; - console.info('window found. Data: ' + JSON.stringify(data)); + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); }); @@ -420,7 +484,7 @@ getTopWindow(callback: AsyncCallback<Window>): void Obtains the top window of the current application. This API uses an asynchronous callback to return the result. -This API can be used only in the FA model. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -450,7 +514,7 @@ getTopWindow(): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. -This API can be used only in the FA model. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -540,7 +604,7 @@ minimizeAll(id: number, callback: AsyncCallback<void>): void Minimizes all windows on a display. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -548,7 +612,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------- | -| id | number | Yes | ID of the [display](js-apis-display.md#display). | +| id | number | Yes | ID of the [display](js-apis-display.md#display).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -578,7 +642,7 @@ minimizeAll(id: number): Promise<void> Minimizes all windows on a display. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -620,7 +684,7 @@ toggleShownStateForAllAppWindows(callback: AsyncCallback<void>): void Hides or restores the application's windows during quick multi-window switching. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -647,7 +711,7 @@ toggleShownStateForAllAppWindows(): Promise<void> Hides or restores the application's windows during quick multi-window switching. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -673,7 +737,7 @@ setWindowLayoutMode(mode: WindowLayoutMode, callback: AsyncCallback<void>) Sets the window layout mode. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -697,7 +761,7 @@ setWindowLayoutMode(mode: WindowLayoutMode): Promise<void> Sets the window layout mode. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -730,7 +794,7 @@ on(type: 'systemBarTintChange', callback: Callback<SystemBarTintState>): v Enables listening for properties changes of the status bar and navigation bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -755,7 +819,7 @@ off(type: 'systemBarTintChange', callback?: Callback<SystemBarTintState >) Disables listening for properties changes of the status bar and navigation bar. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -784,7 +848,7 @@ hide (callback: AsyncCallback<void>): void Hides this window. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -802,7 +866,7 @@ windowClass.hide((err, data) => { console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); return; } - console.info('window hidden. data: ' + JSON.stringify(data)); + console.info('Succeeded in hiding the window. data: ' + JSON.stringify(data)); }) ``` @@ -812,7 +876,7 @@ hide(): Promise<void> Hides this window. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -827,12 +891,67 @@ This is a system API and cannot be called by third-party applications. ```js let promise = windowClass.hide(); promise.then((data)=> { - console.info('window hidden. Data: ' + JSON.stringify(data)); + console.info('Succeeded in hiding the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); }) ``` +### hideWithAnimation9+ + +hideWithAnimation(callback: AsyncCallback<void>): void + +Hides this window and plays an animation during the process. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +windowClass.hideWithAnimation((err, data) => { + if (err.code) { + console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in hiding the window with animation. data: ' + JSON.stringify(data)); +}) +``` + +### hideWithAnimation9+ + +hideWithAnimation(): Promise<void> + +Hides this window and plays an animation during the process. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = windowClass.hideWithAnimation(); +promise.then((data)=> { + console.info('Succeeded in hiding the window with animation. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); +}) +``` + ### show7+ show(callback: AsyncCallback<void>): void @@ -884,6 +1003,61 @@ promise.then((data)=> { }) ``` +### showWithAnimation9+ + +showWithAnimation(callback: AsyncCallback<void>): void + +Shows this window and plays an animation during the process. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +windowClass.showWithAnimation((err, data) => { + if (err.code) { + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); +}) +``` + +### showWithAnimation9+ + +showWithAnimation(): Promise<void> + +Shows this window and plays an animation during the process. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let promise = windowClass.showWithAnimation(); +promise.then((data)=> { + console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); +}) +``` + ### destroy7+ destroy(callback: AsyncCallback<void>): void @@ -959,7 +1133,7 @@ windowClass.moveTo(300, 300, (err, data)=>{ console.error('Failed to move the window. Cause:' + JSON.stringify(err)); return; } - console.info('Window moved. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); }); ``` @@ -990,7 +1164,7 @@ Moves this window. This API uses a promise to return the result. ```js let promise = windowClass.moveTo(300, 300); promise.then((data)=> { - console.info('Window moved. Data: ' + JSON.stringify(data)); + console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); }) @@ -1020,7 +1194,7 @@ windowClass.resetSize(500, 1000, (err, data) => { console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); return; } - console.info('Window size changed. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); }); ``` @@ -1050,19 +1224,23 @@ Changes the size of this window. This API uses a promise to return the result. ```js let promise = windowClass.resetSize(500, 1000); promise.then((data)=> { - console.info('Window size changed. Data: ' + JSON.stringify(data)); + console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); }).catch((err)=>{ console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); }); ``` -### setWindowType7+ +### setWindowType(deprecated) setWindowType(type: WindowType, callback: AsyncCallback<void>): void Sets the type of this window. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. +> +> **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1086,13 +1264,17 @@ windowClass.setWindowType(type, (err, data) => { }); ``` -### setWindowType7+ +### setWindowType(deprecated) setWindowType(type: WindowType): Promise<void> Sets the type of this window. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. +> +> **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1183,7 +1365,7 @@ Obtains the area where this window cannot be displayed, for example, the system | Name | Type | Mandatory| Description | | -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area.| +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. `TYPE_SYSTEM_GESTURE` indicates the gesture area. `TYPE_KEYBOARD` indicates the soft keyboard area.| | callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** @@ -1211,7 +1393,7 @@ Obtains the area where this window cannot be displayed, for example, the system | Name| Type | Mandatory| Description | | ------ |----------------------------------| ---- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area.| +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. `TYPE_SYSTEM_GESTURE` indicates the gesture area. `TYPE_KEYBOARD` indicates the soft keyboard area.| **Return value** @@ -1368,13 +1550,14 @@ Sets whether to display the status bar and navigation bar in this window. This A **Example** ```js -var names = ["status", "navigation"]; +// In this example, the status bar and navigation bar are not displayed. +var names = []; windowClass.setSystemBarEnable(names, (err, data) => { if (err.code) { - console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); }); ``` @@ -1401,12 +1584,13 @@ Sets whether to display the status bar and navigation bar in this window. This A **Example** ```js -var names = ["status", "navigation"]; +// In this example, the status bar and navigation bar are not displayed. +var names = []; let promise = windowClass.setSystemBarEnable(names); promise.then((data)=> { - console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); }); ``` @@ -1611,7 +1795,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void Loads content from a page associated with a local storage to this window. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1620,14 +1804,14 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```ts class myAbility extends Ability { - storage : LocalStorage + storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); this.storage.setOrCreate("storageSimpleProp",121); @@ -1649,7 +1833,7 @@ loadContent(path: string, storage: LocalStorage): Promise<void> Loads content from a page associated with a local storage to this window. This API uses a promise to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1658,7 +1842,7 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| **Return value** @@ -1670,7 +1854,7 @@ This API can be used only in the stage model. ```ts class myAbility extends Ability { - storage : LocalStorage + storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); this.storage.setOrCreate("storageSimpleProp",121); @@ -1786,9 +1970,9 @@ windowClass.off('windowSizeChange'); on(type: 'systemAvoidAreaChange', callback: Callback<[AvoidArea](#avoidarea7)>): void Enables listening for changes to the area where the window cannot be displayed. -> **NOTE** +> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. > -> This API is deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. +> **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1812,9 +1996,9 @@ windowClass.on('systemAvoidAreaChange', (data) => { off(type: 'systemAvoidAreaChange', callback?: Callback<[AvoidArea](#avoidarea7)>): void Disables listening for changes to the area where the window cannot be displayed. -> **NOTE** +> **NOTE**
This API is supported since API version 7 and deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. > -> This API is deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. +> **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1850,8 +2034,8 @@ Enables listening for changes to the area where the window cannot be displayed. **Example** ```js -windowClass.on('avoidAreaChange', (type, data) => { - console.info('Succeeded in enabling the listener for system avoid area changes. type:' + JSON.stringify(type) + 'Data: ' + JSON.stringify(data)); +windowClass.on('avoidAreaChange', (data) => { + console.info('Succeeded in enabling the listener for system avoid area changes. type:' + JSON.stringify(data.type) + ', area: ' + JSON.stringify(data.area)); }); ``` @@ -1925,7 +2109,8 @@ windowClass.off('keyboardHeightChange'); on(type: 'touchOutside', callback: Callback<void>): void Enables listening for click events outside this window. -This is a system API and cannot be called by third-party applications. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1949,7 +2134,8 @@ windowClass.on('touchOutside', () => { off(type: 'touchOutside', callback?: Callback<void>): void Disables listening for click events outside this window. -This is a system API and cannot be called by third-party applications. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -1966,6 +2152,209 @@ This is a system API and cannot be called by third-party applications. windowClass.off('touchOutside'); ``` +### on('screenshot')9+ + +on(type: 'screenshot', callback: Callback<void>): void + +Subscribes to screenshot events. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| +| callback | Callback<void> | Yes | Callback invoked when a screenshot event occurs. | + +**Example** + +```js +windowClass.on('screenshot', () => { + console.info('screenshot happened'); +}); +``` + +### off('screenshot')9+ + +off(type: 'screenshot', callback?: Callback<void>): void + +Unsubscribes from screenshot events. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| +| callback | Callback<void> | No | Callback invoked when a screenshot event occurs.| + +**Example** + +```js +var callback = ()=>{ + console.info('screenshot happened'); +} +windowClass.on('screenshot', callback) +windowClass.off('screenshot', callback) + +// If multiple callbacks are enabled in on(), they will all be disabled. +windowClass.off('screenshot'); +``` + +### on('dialogTargetTouch')9+ + +on(type: 'dialogTargetTouch', callback: Callback<void>): void + +Subscribes to click events of the target window in the modal window mode. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| +| callback | Callback<void>| Yes | Callback invoked when the click event occurs in the target window of the modal window mode.| + +**Example** + +```js +windowClass.on('dialogTargetTouch', () => { + console.info('touch dialog target'); +}); +``` + +### off('dialogTargetTouch')9+ + +off(type: 'dialogTargetTouch', callback?: Callback<void>): void + +Unsubscribes from click events of the target window in the modal window mode. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| +| callback | Callback<void> | No | Callback invoked when the click event occurs in the target window of the modal window mode.| + +**Example** + +```js +windowClass.off('dialogTargetTouch'); +``` + +### bindDialogTarget9+ + +bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback<void>, callback: AsyncCallback<void>): void + +Binds the modal window to the target window, and adds a callback to listen for modal window destruction events. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| token | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes | Token of the target window.| +| deathCallback | Callback<void> | Yes | Callback used to listen for modal window destruction events.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } +} +class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } +} +let token = new TestRemoteObject("testObject"); +windowClass.bindDialogTarget(token, () => { + console.info('Dialog Window Need Destroy.'); +}, (err, data) => { + if (err.code) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in binding dialog target. Data:' + JSON.stringify(data)); +}); +``` + +### bindDialogTarget9+ + +bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback<void>): Promise<void> + +Binds the modal window to the target window, and adds a callback to listen for modal window destruction events. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| token | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes | Token of the target window.| +| deathCallback | Callback<void> | Yes | Callback used to listen for modal window destruction events.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } +} +class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } +} +let token = new TestRemoteObject("testObject"); +let promise = windowClass.bindDialogTarget(token, () => { + console.info('Dialog Window Need Destroy.'); +}); +promise.then((data)=> { + console.info('Succeeded in binding dialog target. Data:' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); +}); +``` + ### isSupportWideGamut8+ isSupportWideGamut(callback: AsyncCallback<boolean>): void @@ -2138,7 +2527,7 @@ Sets the background color for this window. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| color | string | Yes | Background color to set. The value is a hexadecimal color and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -2166,7 +2555,7 @@ Sets the background color for this window. This API uses a promise to return the | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| color | string | Yes | Background color to set. The value is a hexadecimal color and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| **Return value** @@ -2186,26 +2575,49 @@ promise.then((data)=> { }); ``` -### setBrightness +### setWakeUpScreen()9+ -setBrightness(brightness: number, callback: AsyncCallback<void>): void +setWakeUpScreen(wakeUp: boolean): void; -Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. +Wakes up the screen. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value `1` indicates the brightest.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------------- | ------- | ---- | ---------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen.| **Example** ```js -var brightness = 1; -windowClass.setBrightness(brightness, (err, data) => { +var wakeUp = true; +windowClass.setWakeUpScreen(wakeUp); +``` + +### setBrightness + +setBrightness(brightness: number, callback: AsyncCallback<void>): void + +Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------------------------------ | +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value `1` indicates the brightest.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +var brightness = 1; +windowClass.setBrightness(brightness, (err, data) => { if (err.code) { console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); return; @@ -2253,8 +2665,10 @@ setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. > **NOTE** -> -> This API is deprecated since API version 9. +> +> This API cannot be used. +> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2284,8 +2698,10 @@ setDimBehind(dimBehindValue: number): Promise<void> Sets the dimness of the window that is not on top. This API uses a promise to return the result. > **NOTE** -> -> This API is deprecated since API version 9. +> +> This API cannot be used. +> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2428,7 +2844,7 @@ let promise = windowClass.setKeepScreenOn(isKeepScreenOn); promise.then((data) => { console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); }); ``` @@ -2439,8 +2855,10 @@ setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): vo Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. > **NOTE** -> -> This API is deprecated since API version 9. +> +> This API cannot be used. +> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2470,8 +2888,10 @@ setOutsideTouchable(touchable: boolean): Promise<void> Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. > **NOTE** -> -> This API is deprecated since API version 9. +> +> This API cannot be used. +> +> This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2502,7 +2922,7 @@ promise.then((data)=> { setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void -Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. +Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2531,7 +2951,7 @@ windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { setPrivacyMode(isPrivacyMode: boolean): Promise<void> -Sets whether this window is in privacy mode. This API uses a promise to return the result. +Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2559,6 +2979,25 @@ promise.then((data)=> { }); ``` +### setSnapshotSkip9+ +setSnapshotSkip(isSkip: boolean): void + +Sets whether to ignore this window during screen capturing or recording. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------- | ---- | -------------------- | +| isSkip | boolean | Yes | Whether to ignore the window. The default value is `false`.
The value `true` means that the window is ignored, and `false` means the opposite.
| +```js +var isSkip = true; +windowClass.setSnapshotSkip(isSkip); +``` + ### setTouchable7+ setTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void @@ -2626,7 +3065,7 @@ setForbidSplitMove(isForbidSplitMove: boolean, callback: AsyncCallback<void&g Sets whether this window is forbidden to move in split-screen mode. This API uses an asynchronous callback to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2657,7 +3096,7 @@ setForbidSplitMove(isForbidSplitMove: boolean): Promise<void> Sets whether this window is forbidden to move in split-screen mode. This API uses a promise to return the result. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2685,11 +3124,330 @@ promise.then((data)=> { }); ``` +### snapshot9+ + +snapshot(callback: AsyncCallback<image.PixelMap>): void + +Captures this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | + +**Example** + +```js +windowClass.snapshot((err, data) => { + if (err.code) { + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + data.release(); // Release the memory in time after the PixelMap is used. +}); +``` + +### snapshot9+ + +snapshot(): Promise<image.PixelMap> + +Captures this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the window screenshot.| + +**Example** + +```js +let promise = windowClass.snapshot(); +promise.then((pixelMap)=> { + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. +}).catch((err)=>{ + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); +}); +``` + +### setBlur9+ + +setBlur(radius: number): void + +Blurs this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value `0` means that the blur is disabled for the window.| + +**Example** + +```js +windowClass.setBlur(4.0); +``` + +### setBackdropBlur9+ + +setBackdropBlur(radius: number): void + +Blurs the background of this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value `0` means that the blur is disabled for the background of the window.| + +**Example** + +```js +windowClass.setBackdropBlur(4.0); +``` + +### setBackdropBlurStyle9+ + +setBackdropBlurStyle(blurStyle: BlurStyle): void + +Sets the blur style for the background of this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------- | ---- | ---------------------- | +| blurStyle | [BlurStyle](#blurstyle9) | Yes | Blur style to set for the background of the window.| + +**Example** + +```js +windowClass.setBackdropBlurStyle(window.BlurType.THIN); +``` + +### setShadow9+ + +setShadow(radius: number, color?: string, offsetX?: number, offsetY?: number): void + +Sets the shadow for the window borders. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur for the borders. The value is greater than or equal to 0. The value `0` means that the shadow is disabled for the window borders.| +| color | string | No | Color of the shadow. The value is a hexadecimal color and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | +| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | + +**Example** + +```js +windowClass.setShadow(4.0, '#FF00FF00', 2, 3); +``` + +### setCornerRadius9+ + +setCornerRadius(cornerRadius: number): void + +Sets the radius of the rounded corners for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | -------------------- | +| radius | number | Yes | Radius of the rounded corners. The value is greater than or equal to 0. The value `0` means that the window does not use rounded corners.| + +**Example** + +```js +windowClass.setCornerRadius(4.0); +``` + +### opacity9+ + +opacity(opacity: number): void + +Sets the opacity for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------- | +| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0.| + +**Example** + +```js +windowClass.opacity(0.5); +``` + +### scale9+ + +scale(scaleOptions: ScaleOptions): void + +Sets the scale parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------ | ---- | ---------- | +| scaleOptions | [ScaleOptions](#scaleoptions9) | Yes | Scale parameters to set.| + +**Example** + +```js +var obj : window.ScaleOptions; +obj.x = 2.0; +obj.y = 1.0; +obj.pivotX = 0.5; +obj.pivotY = 0.5; +windowClass.scale(obj); +``` + +### rotate9+ + +rotate(rotateOptions: RotateOptions): void + +Sets the rotation parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------------- | ---- | ---------- | +| rotateOptions | [RotateOptions](#rotateoptions9) | Yes | Rotation parameters to set.| + +**Example** + +```js +var obj : window.RotateOptions; +obj.x = 1.0; +obj.y = 1.0; +obj.z = 45.0; +obj.pivotX = 0.5; +obj.pivotY = 0.5; +windowClass.rotate(obj); +``` + +### translate9+ + +translate(translateOptions: TranslateOptions): void + +Sets the translation parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | -------------------------------------- | ---- | ---------- | +| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters to set.| + +**Example** + +```js +var obj : window.TranslateOptions; +obj.x = 100.0; +obj.y = 0.0; +obj.z = 0.0; +windowClass.translate(obj); +``` + +### getTransitionController9+ + + getTransitionController(): TransitionController + +Obtains the transition animation controller. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------- | ---------------- | +| [TransitionController](#transitioncontroller9) | Transition animation controller.| + +**Example** + +```js +let controller = windowClass.getTransitionController(); // Obtain the transition animation controller. +controller.animationForHidden = (context : window.TransitionContext) => { + let toWindow = context.toWindow + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation mode. + }, () => { + var obj : window.TranslateOptions; + obj.x = 100.0; + obj.y = 0.0; + obj.z = 0.0; + toWindow.translate(obj); // Set the transition animation. + console.info('toWindow translate end'); + } + ) + context.completeTransition(true) + console.info('complete transition end'); +} +windowClass.showWithAnimation((err, data) => { + if (err.code) { + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); +}) +``` + ## WindowStageEventType9+ Describes the lifecycle of a window stage. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2712,7 +3470,7 @@ getMainWindow(callback: AsyncCallback<Window>): void Obtains the main window of this window stage. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2747,7 +3505,7 @@ getMainWindow(): Promise<Window> Obtains the main window of this window stage. This API uses a promise to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2781,7 +3539,7 @@ createSubWindow(name: string, callback: AsyncCallback<Window>): void Creates a subwindow for this window stage. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2818,7 +3576,7 @@ createSubWindow(name: string): Promise<Window> Creates a subwindow for this window stage. This API uses a promise to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2858,7 +3616,7 @@ getSubWindow(callback: AsyncCallback<Array<Window>>): void Obtains all the subwindows of this window stage. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2893,7 +3651,7 @@ getSubWindow(): Promise<Array<Window>> Obtains all the subwindows of this window stage. This API uses a promise to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2927,7 +3685,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void Loads content from a page associated with a local storage to the main window in this window stage. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2936,7 +3694,7 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | LocalStorage | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -2944,7 +3702,7 @@ This API can be used only in the stage model. ```ts import Ability from '@ohos.application.Ability'; class myAbility extends Ability { - storage : LocalStorage + storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); this.storage.setOrCreate("storageSimpleProp",121); @@ -2966,7 +3724,7 @@ loadContent(path: string, storage?: LocalStorage): Promise<void> Loads content from a page associated with a local storage to the main window in this window stage. This API uses a promise to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -2975,7 +3733,7 @@ This API can be used only in the stage model. | Name | Type | Mandatory| Description | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | LocalStorage | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| **Return value** @@ -2988,7 +3746,7 @@ This API can be used only in the stage model. ```ts import Ability from '@ohos.application.Ability'; class myAbility extends Ability { - storage : LocalStorage + storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); this.storage.setOrCreate("storageSimpleProp",121); @@ -3011,7 +3769,7 @@ loadContent(path: string, callback: AsyncCallback<void>): void Loads content from a page to this window stage. This API uses an asynchronous callback to return the result. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3046,7 +3804,7 @@ on(eventType: 'windowStageEvent', callback: Callback<WindowStageEventType> Enables listening for window stage lifecycle changes. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3077,7 +3835,7 @@ off(eventType: 'windowStageEvent', callback?: Callback<WindowStageEventType&g Disables listening for window stage lifecycle changes. -This API can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3106,9 +3864,9 @@ disableWindowDecor(): void Disables window decorators. -This type can be used only in the stage model. +**Model restriction**: This API can be used only in the stage model. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3130,7 +3888,9 @@ setShowOnLockScreen(showOnLockScreen: boolean): void Sets whether to display the window of the application on the lock screen. -This API can be used only in the stage model. +**System API**: This is a system API. + +**Model restriction**: This API can be used only in the stage model. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -3151,3 +3911,145 @@ class myAbility extends Ability { } } ``` +## TransitionContext9+ + +Provides the context for the transition animation. + +**System API**: This is a system API. + +### toWindow9+ + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Readable| Writable| Description | +| -------- | ----------------- | ---- | ---- | ---------------- | +| toWindow | [Window](#window) | Yes | Yes | Target window to display the animation.| + +### completeTransition9+ + +completeTransition(isCompleted: boolean): void + +Completes the transition. This API must be called after [animateTo()](../arkui-ts/ts-explicit-animation.md) is executed. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | ------------------------------------------------------------ | +| isCompleted | boolean | Yes | Whether the transition is complete. The value `true` means that the transition is complete, and `false` means the opposite.| + +**Example** + +```js +let controller = windowClass.getTransitionController(); +controller.animationForShown = (context : window.TransitionContext) => { + let toWindow = context.toWindow + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation mode. + }, () => { + var obj : window.TranslateOptions; + obj.x = 100.0; + obj.y = 0.0; + obj.z = 0.0; + toWindow.translate(obj); + console.info('toWindow translate end'); + } + ) + context.completeTransition(true) + console.info('complete transition end'); +} +``` + +## TransitionController9+ + +Implements the transition animation controller. + +**System API**: This is a system API. + +### animationForShown9+ + +animationForShown(context: TransitionContext): void + +Customizes the animation when the window is shown. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| + +**Example** + +```js +let controller = windowClass.getTransitionController(); +controller.animationForShown = (context : window.TransitionContext) => { + let toWindow = context.toWindow + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation mode. + }, () => { + var obj : window.TranslateOptions; + obj.x = 100.0; + obj.y = 0.0; + obj.z = 0.0; + toWindow.translate(obj); + console.info('toWindow translate end'); + } + ) + context.completeTransition(true) + console.info('complete transition end'); +} +``` + +### animationForHidden9+ + +animationForHidden(context: TransitionContext): void + +Customizes the animation when the window is hidden. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------------- | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| + +**Example** + +```js +let controller = windowClass.getTransitionController(); +controller.animationForHidden = (context : window.TransitionContext) => { + let toWindow = context.toWindow + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation mode. + }, () => { + var obj : window.TranslateOptions; + obj.x = 100.0; + obj.y = 0.0; + obj.z = 0.0; + toWindow.translate(obj); + console.info('toWindow translate end'); + } + ) + context.completeTransition(true) + console.info('complete transition end'); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..a81bb5c76c64a092ea77afb14db231040adf77ac --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md @@ -0,0 +1,375 @@ +# Window Animation Management +The **WindowAnimationManager** module provides APIs to listen for application start/exit events and window minimization/maximization events and associate animations with these events. + +> **NOTE** +> +> This component is supported since API version 9. Updates 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 windowAnimationManager from '@ohos.animation.windowAnimationManager' +``` + +## windowAnimationManager.setController + +setController(controller: WindowAnimationController): void + +Sets a window animation controller. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| controller | [WindowAnimationController](#windowanimationcontroller) | Yes| Window animation controller to set.| + +**Example** + +```js +var controller = { + onStartAppFromLauncher(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromLauncher', startingWindowTarget); + }, + onStartAppFromRecent(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromRecent', startingWindowTarget); + }, + onStartAppFromOther(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromOther', startingWindowTarget); + }, + onAppTransition(fromWindowTarget: WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + }, + onMinimizeWindow(minimizingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + }, + onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + }, + onScreenUnlock(finishCallback: WindowAnimationFinishedCallback): void { + } +} + +windowAnimationManager.setController(controller) +``` + +## windowAnimationManager.minimizeWindowWithAnimation + +minimizeWindowWithAnimation(windowTarget: WindowAnimationTarget, callback: AsyncCallback<WindowAnimationFinishedCallback>): void + +Minimizes the window that displays the animation. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes| Target window to minimize.| +| callback | AsyncCallback<[WindowAnimationFinishedCallback](#windowanimationfinishedcallback)> | Yes| Callback invoked when the animation is finished.| + +**Example** + +```js +var target: WindowAnimationTarget = undefined; +var controller = { + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { + target = fullScreenWindowTarget; + }, +} + +windowAnimationManager.setController(controller) + +var finishedCallback = null; +windowAnimationManager.minimizeWindowWithAnimation(target, (err, data) => { + if (err.code) { + console.error('Failed to minimize the window target. Cause: ' + JSON.stringify(err)); + return; + } + + finishedCallback = data; +}); + +finishedCallback.onAnimationFinish(); +``` + +## windowAnimationManager.minimizeWindowWithAnimation + +minimizeWindowWithAnimation(windowTarget: WindowAnimationTarget): Promise<WindowAnimationFinishedCallback> + +Minimizes the window that displays the animation. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes| Target window to display the animation.| + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[WindowAnimationFinishedCallback](#windowanimationfinishedcallback)> | Promise used to return a call when the animation is finished.| + + +**Example** + +```js +var target: WindowAnimationTarget = undefined; +var controller = { + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { + target = fullScreenWindowTarget; + }, +} + +windowAnimationManager.setController(controller) + +let promise = windowAnimationManager.minimizeWindowWithAnimation(target); +promise.then((data) => { + data.onAnimationFinish(); +}).catch((err)=>{ + console.error('Failed to minimize the window target. Cause: ' + JSON.stringify(err)); + return; +}); +``` + +## WindowAnimationController + +Implements the window animation controller. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +### onStartAppFromLauncher + +onStartAppFromLauncher(startingWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called when an application is started from the home screen. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------ | +| startingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onStartAppFromLauncher(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromLauncher', startingWindowTarget); + } +} +``` + +### onStartAppFromRecent + +onStartAppFromRecent(startingWindowTarget: WindowAnimationTarget,finishCallback:WindowAnimationFinishedCallback): void + +Called when an application is started from the recent task list. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------ | +| startingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onStartAppFromRecent(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromRecent', startingWindowTarget); + } +} +``` + +### onStartAppFromOther + +onStartAppFromOther(startingWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called when an application is started from a place other than the home screen and recent task list. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------ | +| startingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onStartAppFromOther(startingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onStartAppFromOther', startingWindowTarget); + } +} +``` + +### onAppTransition + +onAppTransition(fromWindowTarget: WindowAnimationTarget, toWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called during application transition. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------- | ---- | ---------------- | +| fromWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Window that displays the animation before the transition.| +| toWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Window that displays the animation after the transition.| +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onAppTransition(fromWindowTarget: WindowAnimationTarget, toWindowTarget: WindowAnimationTarget, + finishCallback: WindowAnimationFinishedCallback): void { + console.log('onAppTransition', fromWindowTarget); + } +} +``` + +### onMinimizeWindow + +onMinimizeWindow(minimizingWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called when a window is minimized. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------- | ---- | ---------------- | +| minimizingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onMinimizeWindow(minimizingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onMinimizeWindow', minimizingWindowTarget); + } +} +``` + +### onCloseWindow + +onCloseWindow(closingWindowTarget: WindowAnimationTarget,finishCallback: WindowAnimationFinishedCallback): void + +Called when a window is closed. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------- | ---- | ---------------- | +| closingWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window to display the animation. | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + console.log('onCloseWindow', closingWindowTarget); + } +} +``` + +### onScreenUnlock + +onScreenUnlock(finishCallback: [WindowAnimationFinishedCallback](#windowanimationfinishedcallback)): void + +Called when the screen is unlocked. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------------------------------ | ---- | ------------------ | +| finishCallback | [WindowAnimationFinishedCallback](#windowanimationfinishedcallback) | Yes | Callback invoked when the animation is finished.| + +**Example** + +```js +var controller = { + onScreenUnlock(finishCallback: WindowAnimationFinishedCallback): void { + console.log('onScreenUnlock'.); + } +} +``` + +### onWindowAnimationTargetsUpdate + +onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array<WindowAnimationTarget>): void + +Called when the window that displays the animation is updated. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------- | ---- | ---------------- | +| fullScreenWindowTarget | [WindowAnimationTarget](#windowanimationtarget) | Yes | Target window in full-screen mode.| +| floatingWindowTargets| Array<[WindowAnimationTarget](#windowanimationtarget)> | Yes | Target window in the form of a floating window.| + +**Example** + +```js +var controller = { + onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array): void { + console.log('onWindowAnimationTargetsUpdate'.); + } +} + +windowAnimationManager.setController(controller) +``` + +## WindowAnimationFinishedCallback +Implements a callback that is invoked when the animation is finished. + +### onAnimationFinish + +onAnimationFinish():void + +Called when the animation is finished. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Example** + +```js +var controller = { + onCloseWindow(closingWindowTarget: WindowAnimationTarget, finishCallback: WindowAnimationFinishedCallback): void { + finishCallback.onAnimationFinish(); + } +} +``` + +## WindowAnimationTarget +Implements animation in a window. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Description| +| ------- | ------ | ----------------------- | +| bundleName | string | Bundle name corresponding to the target window.| +| abilityName | string | Ability name corresponding to the target window.| +| windowBounds | [RRect](#rrect) | Actual size of the target window.| +| missionId | number | Mission ID.| + +## RRect +Describes a rounded rectangle. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name | Type | Description| +| ------- | ------ | ----------------------- | +| left | number | Horizontal coordinate of the upper left corner of the target window relative to the screen.| +| top | number | Vertical coordinate of the upper left corner of the target window relative to the screen.| +| width | number | Width of the target window.| +| height | number | Height of the target window.| +| radius | number | Radius of the rounded corner of the target window.| diff --git a/en/application-dev/reference/arkui-js/js-components-basic-picker.md b/en/application-dev/reference/arkui-js/js-components-basic-picker.md index a4f2af80b8fcd1c922fd021adef5cff0d8eb409d..b02f86a0da6ad041fac054cd5faf003c98755bbb 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-picker.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-picker.md @@ -1,722 +1,169 @@ -# picker +# picker -The **** component supports common, date, time, data and time, and multi-column text selectors. +> **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 supports common, date, time, data and time, and multi-column text selectors. -None -## Child Component +## Required Permissions None -## 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

-

type

-

string

-

-

-

No

-

Dynamic modification is not supported. Available values include:

-
  • text: text selector
  • data: date selector
  • time: time selector
  • datetime: date and time selector
  • multi-text: multi-column text selector
-
- -### Text Selector - -When **type** is set to **text**, a text selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

range

-

Array

-

-

-

No

-

Value range of the common selector, for example, ["15", "20", "25"].

-
NOTE:

Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable data: ["15", "20", "25"] in the JavaScript.

-
-

selected

-

string

-

0

-

No

-

Default value of the common selector. The value should be the index of range.

-

value

-

string

-

-

-

No

-

Value of the common selector.

-
- -### Date Selector - -When **type** is set to **date**, a date selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

start

-

<time>

-

1970-1-1

-

No

-

Start date of the date selector, in the format of YYYY-MM-DD.

-

end

-

<time>

-

2100-12-31

-

No

-

End date of the date selector, in the format of YYYY-MM-DD.

-

selected

-

string

-

Current date

-

No

-

Default value of the date selector, in format of YYYY-MM-DD.

-

value

-

string

-

-

-

Yes

-

Value of the date selector.

-

lunar5+

-

boolean

-

false

-

No

-

Whether the pop-up window displays the lunar calendar.

-

lunarswitch

-

boolean

-

false

-

No

-

Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value true means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value false means not to display the lunar calendar switch.

-
NOTE:

When both lunarswitch and lunar are set to true, the switch is selected.

-
-
- -### Time Selector - -When **type** is set to **time**, a time selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

containsecond

-

boolean

-

false

-

No

-

Whether seconds are contained.

-

selected

-

string

-

Current time

-

No

-

Default value of the time selector, in the format of HH:mm. If seconds are contained, the format is HH:mm:ss.

-

value

-

string

-

-

-

No

-

Value of the time selector.

-

hours

-

number

-

241-4

-

-5+

-

No

-

Time format used by the time selector. Available values include:

-
  • 12: displayed in 12-hour format and distinguished by a.m. and p.m.
  • 24: displayed in 24-hour format
    NOTE:

    The default value is the most commonly-used hour format in the current locale. 5+

    -
    -
-
- -### Date and Time Selector - -When **type** is set to **datetime**, a date and time selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

selected

-

string

-

Current date and time

-

No

-

Default value of the date and time selector. The value can be in either of the following formats:

-
  • MM-DD-HH-mm
  • YYYY-MM-DD-HH-mm
-

If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.

-

value

-

string

-

-

-

Yes

-

Value of the date and time selector.

-

hours

-

number

-

241-4

-

-5+

-

No

-

Time format used by the date and time selector. Available values include:

-
  • 12: displayed in 12-hour format and distinguished by a.m. and p.m.
  • 24: displayed in 24-hour format
    NOTE:

    The default value is the most commonly-used hour format in the current locale. 5+

    -
    -
-

lunar5+

-

boolean

-

false

-

No

-

Whether the pop-up window displays the lunar calendar.

-

lunarswitch

-

boolean

-

false

-

No

-

Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value true means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value false means not to display the lunar calendar switch.

-
NOTE:

When both lunarswitch and lunar are set to true, the switch is selected.

-
-
- -### Multi-Column Text Selector - -When **type** is set to **multi-text**, a multi-column text selector is used. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

columns

-

number

-

-

-

Yes

-

Number of columns in the multi-column text selector.

-

range

-

Two-dimensional array

-

-

-

No

-

Items of the multi-column text selector. range is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, [["a","b"], ["c","d"]].

-
NOTE:

Use the data binding mode, for example, range = {{data}}. Declare the corresponding variable data: [["a","b"], ["c","d"]] in the JavaScript.

-
-

selected

-

Array

-

0,0,0,...

-

No

-

Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.

-

value

-

Array

-

-

-

No

-

Value of the multi-column text selector, which is an array consisting of the values of the selected items in each column.

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

-

text-color

-

<color>

-

-

-

No

-

Text color of the selector.

-

font-size

-

<length>

-

-

-

No

-

Font size of the selector.

-

allow-scale

-

boolean

-

true

-

No

-

Whether the font size changes with the system's font size settings.

-
NOTE:

If the config-changes tag of fontSize is configured for abilities in the config.json file, the setting takes effect without application restart.

-
-

letter-spacing

-

<length>

-

0

-

No

-

Letter spacing of the selector. For details, see letter-spacing of the text component.

-

text-decoration

-

string

-

-

-

No

-

Text decoration of the selector. For details, see text-decoration of the text component.

-

font-style

-

string

-

normal

-

No

-

Font style of the selector. For details, see font-style of the text component.

-

font-weight

-

number | string

-

normal

-

No

-

Font weight of the selector. For details, see font-weight of the text component.

-

font-family

-

string

-

sans-serif

-

No

-

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

-

line-height

-

<length>

-

0px

-

No

-

Text line height of the selector.

-

column-height5+

-

<length>

-

-

-

No

-

Height of the selector option list.

-
NOTE:

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

Name

-

Parameter

-

Description

-

change

-

{ newValue: newValue, newSelected: newSelected }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. newSelected is the index.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Date Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ year: year, month: month, day: day }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window.

-
NOTE:

The value of month ranges from 0 (January) to 11 (December). 5+

-
-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Date and Time Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ year: year, month: month, day: day, hour: hour, minute: minute}

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Time Selector - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ hour: hour, minute: minute, [second: second] }

-

Triggered when a value is selected and the OK button is clicked in the displayed pop-up window. If containsecond is set to true, value contains seconds.

-

cancel

-

-

-

Triggered when the cancel button is clicked.

-
- -### Multi-Column Text Selector - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter

-

Description

-

change

-

{ newValue: [newValue1, newValue2, newValue3, …], newSelected:[newSelected1, newSelected2, newSelected3, …] }

-

Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.

-
  • newValue is an array consisting of the values of the selected items.
  • newSelected is an array consisting of the indexes of the selected items. The lengths of newValue and newSelected are the same as the length of range.
-

columnchange

-

{ column: column, newValue: newValue, newSelected: newSelected }

-

Triggered when the value of a column in the multi-column selector changes.

-
  • column indicates the column whose value has changed.
  • newValue indicates the selected value.
  • newSelected indicates the index of the selected value.
-

cancel

-

-

-

Triggered when the cancel button is clicked.

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

Name

-

Parameter

-

Description

-

show

-

-

-

Displays the picker.

-
- -## Example Code -``` +## Child Components + +Not supported + + +## 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 | +| ---- | ------ | ---- | ---- | ---------------------------------------- | +| type | string | - | No | Picker type. Dynamic modification is not supported. The options are as follows:
- **text**: text selector.
- **date**: date selector.
- **time**: time selector.
- **datetime**: date and time selector.
- **multi-text**: multi-column text selector.| + + +### Common Selector + +When **type** is set to **text**, a common selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------ | ---- | ---- | ---------------------------------------- | +| range | Array | - | No | Value range of the common selector, for example, **["15", "20", "25"]**.
Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.| +| selected | string | 0 | No | Default value of the common selector. The value should be the index of **range**.| +| value | string | - | No | Value of the common selector. | + + +### Date Selector + +When **type** is set to **date**, a date selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ------------ | ---------- | ---- | ---------------------------------------- | +| start | <time> | 1970-1-1 | No | Start date of the date selector, in the format of YYYY-MM-DD. | +| end | <time> | 2100-12-31 | No | End date of the date selector, in the format of YYYY-MM-DD. | +| selected | string | Current date | No | Default value of the date selector, in format of YYYY-MM-DD.| +| value | string | - | Yes | Value of the date selector. | +| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | +| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.
When both **lunarswitch** and **lunar** are set to **true**, the switch is selected.| + + +### Time Selector + +When **type** is set to **time**, a time selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------- | ------- | ----------------------------------- | ---- | ---------------------------------------- | +| containsecond | boolean | false | No | Whether seconds are contained. | +| selected | string | Current time | No | Default value of the time selector, in format of HH:mm. If seconds are contained, the format is HH:mm:ss. | +| value | string | - | No | Value of the time selector. | +| hours | number | 241-4
-5+ | No | Time format used by the time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| + + +### Date and Time Selector + +When **type** is set to **datetime**, a date and time selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| ------------------ | ------- | ----------------------------------- | ---- | ---------------------------------------- | +| selected | string | Current date and time | No | Default value of the date and time selector. The value can be in either of the following formats:
- MM-DD-HH-mm
- YYYY-MM-DD-HH-mm
If the year is not set, the current year is used by default. The value you set is the date selected by default in the pop-up window.| +| value | string | - | Yes | Value of the date and time selector. | +| hours | number | 241-4
-5+ | No | Time format used by the date and time selector. Available values are as follows:
- **12**: displayed in 12-hour format and distinguished by a.m. and p.m.
- **24**: displayed in 24-hour format.
Since API version 5, the default value is the most commonly-used hour format in the current locale.| +| lunar5+ | boolean | false | No | Whether the pop-up window displays the lunar calendar. | +| lunarswitch | boolean | false | No | Whether the date selector displays the lunar calendar switch, which is used to switch between the Gregorian calendar and lunar calendar. The value **true** means to display the lunar calendar switch for users to switch between the Gregorian calendar and lunar calendar. The value **false** means not to display the lunar calendar switch.
When both **lunarswitch** and **lunar** are set to **true**, the switch is selected.| + + +### Multi-Column Text Selector + +When **type** is set to **multi-text**, a multi-column text selector is used. + +| Name | Type | Default Value | Mandatory | Description | +| -------- | ------- | --------- | ---- | ---------------------------------------- | +| columns | number | - | Yes | Number of columns in the multi-column text selector. | +| range | Two-dimensional array| - | No | Items of the multi-column text selector. **range** is a two-dimensional array that indicates the number of columns. Each item in the array indicates the data of each column, for example, **[["a", "b"], ["c", "d"]]**.
Use the data binding mode, for example, `range = {{data}}`. Declare the corresponding variable `data: ["15", "20", "25"]` in JavaScript.| +| selected | Array | [0,0,0, ...]| No | Default value of the multi-column text selector, which is an array consisting of the indexes of the selected items in each column.| +| value | Array | - | No | Value of the multi-column text selector, which is an array consisting of the values of the selected items in each column. | + + +## 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 | +| -------------------------- | -------------------------- | ---------- | ---- | ---------------------------------------- | +| text-color | <color> | - | No | Text color of the selector. | +| font-size | <length> | - | No | Font size of the selector. | +| allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| +| letter-spacing | <length> | 0 | No | Letter spacing of the selector. For details, see **letter-spacing** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| text-decoration | string | - | No | Text decoration of the selector. For details, see **text-decoration** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-style | string | normal | No | Font style of the selector. For details, see **font-style** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-weight | number \| string | normal | No | Font weight of the selector. For details, see **font-weight** in the **[\](../arkui-js/js-components-basic-text.md#styles)** component.| +| font-family | string | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| line-height | <length> | 0px | No | Text line height of the selector. | +| column-height5+ | <length> | - | No | Height of the selector option list. | + + +## Events + +In addition to the [universal events](../arkui-js/js-components-common-events.md), the following events are supported. + + +### Common Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { newValue: newValue, newSelected: newSelected } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window. **newSelected** is the index.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Date Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { year: year, month: month, day: day } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.
The value of **month** ranges from **0** (January) to **11** (December) since API version 5.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Date and Time Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------- | +| change | { year: year, month: month, day: day, hour: hour, minute: minute} | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Time Selector + +| Name | Parameter | Description | +| ------ | ---------------------------------------- | ---------------------------------------- | +| change | { hour: hour, minute: minute, [second: second] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window. If **containsecond** is set to true, value contains seconds.| +| cancel | - | Triggered when the cancel button is clicked. | + + +### Multi-Column Text Selector + +| Name | Parameter | Description | +| ------------ | ---------------------------------------- | ---------------------------------------- | +| change | { newValue: [newValue1, newValue2, newValue3, …], newSelected:[newSelected1, newSelected2, newSelected3, …] } | Triggered when an item is selected and the OK button is clicked in the displayed pop-up window.
- **newValue** is an array consisting of the values of the selected items.
- **newSelected** is an array consisting of the indexes of the selected items. The lengths of **newValue** and **newSelected** are the same as the length of **range**.| +| columnchange | { column: column, newValue: newValue, newSelected: newSelected } | Triggered when the value of a column in the multi-column selector changes.
- **column**: column whose value has changed.
- **newValue**: selected value.
- **newSelected**: index of the selected value.| +| cancel | - | Triggered when the cancel button is clicked. | + + +## Methods + +In addition to the [universal methods](../arkui-js/js-components-common-methods.md), the following methods are supported. + +| Name | Parameter | Description | +| ---- | ---- | --------------- | +| show | - | Shows the picker.| + + +## Example + +```html
``` - -``` +```css /* index.css */ .button:active { background-color: #888888;/* After the button is activated, the background color is changed to #888888. */ } ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> Pseudo-classes are not supported for the component and its child components, including , , ,