diff --git a/README.md b/README.md index fd9d361e5923600f3604e91448dc43fb4e3b0d7d..bb06b90f6a7576f160ec64917b6060e9bf8ffea6 100644 --- a/README.md +++ b/README.md @@ -26,4 +26,4 @@ OpenHarmony 2.0 Canary. [Learn more](en/release-notes/openharmony-2-0-canary.md) OpenHarmony_v1.x_release: OpenHarmony v1.1.2 LTS. [Learn more](en/release-notes/OpenHarmony-v1.1.2-LTS.md) -[More versions](https://gitee.com/openharmony/docs/blob/master/en/release-notes/) +[More versions](en/release-notes/) diff --git a/README_zh.md b/README_zh.md index f45168c425bb992aed482cc6aa6da498f8ef9f42..57099631489df618763174889d97ce6846b5d3d6 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,7 +18,9 @@ master:最新开发版本。 -发布OpenHarmony 3.0 LTS版本,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)。 +发布OpenHarmony 3.1 Beta版本,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.1-beta.md)。 + +发布OpenHarmony 3.0 LTS版本,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)。该版本已更新至OpenHarmony 3.0.1 LTS,[了解版本详情](zh-cn/release-notes/OpenHarmony-v3.0.1-LTS.md)。 发布 OpenHarmony v2.2 Beta2版本,[了解版本详情](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)。 diff --git a/docker/standard/CHANGELOG.md b/docker/standard/CHANGELOG.md index 14fe8b29527e9f11deec749e29117beda1820b01..b0dc49b1b65b61076f45792a03f39d037122f690 100644 --- a/docker/standard/CHANGELOG.md +++ b/docker/standard/CHANGELOG.md @@ -1,3 +1,11 @@ + ### 0.0.7(2022/01/11) + +新增安装genext2fs和liblz4-tool。 + + ### 0.0.6(2022/01/04) + +新增安装hb。 + ### 0.0.5(2021/10/28) 新增安装tar、binutils、git-lfs、gnutls-bin、python3.8、python3-pip、cpio。 diff --git a/docker/standard/CHANGELOG_en.md b/docker/standard/CHANGELOG_en.md index 5f9abe4af49b477878ab4caee68a128c45bbe89b..23a128c43f35fdfb11c05c05af5099b4ae6f321d 100644 --- a/docker/standard/CHANGELOG_en.md +++ b/docker/standard/CHANGELOG_en.md @@ -1,3 +1,11 @@ + ### 0.0.7 (2022/01/11) + +Added the installation of genext2fs and liblz4-tool. + + ### 0.0.6 (2022/01/04) + +Added the installation of hb. + ### 0.0.5 (2021/10/28) Added the installation of tar, binutils, git-lfs, gnutls-bin, python3.8, python3-pip, and cpio. diff --git a/docker/standard/Readme-en.md b/docker/standard/Readme-en.md index 36f20d2bc01bd81c685155e9fb973830ee52dc40..b74720651bb24cd48774b6eaaf2884e21f414006 100755 --- a/docker/standard/Readme-en.md +++ b/docker/standard/Readme-en.md @@ -10,11 +10,11 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua 1. Obtain the Docker image. ``` -docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.5 +docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` 2. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: ``` -docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.5 +docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` ##### **Method 2: Using the Dockerfile to Build a Local Docker Image** @@ -30,16 +30,16 @@ cd docs/docker/standard ``` 3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: ``` -docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.5 +docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 ``` ### Building for Standard-System Devices (reference memory ≥ 128 MB) Run the following script to start building for Standard-System Devices (reference memory ≥ 128 MB) ``` -./build.sh --product-name {product_name} +./build.sh --product-name {product_name} --ccache ``` -**{product_name}** indicates the platform supported by the current distribution, for example, Hi3516DV300. +**{product_name}** indicates the platform supported by the current distribution, for example, Hi3516DV300, rk3568. Files generated during compilation are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory. diff --git a/docker/standard/Readme.md b/docker/standard/Readme.md index d13820b59111b736c3777b988453a620fa95a186..2bdb472014805d6ee68af247b3dcffd152fad671 100755 --- a/docker/standard/Readme.md +++ b/docker/standard/Readme.md @@ -10,11 +10,11 @@ OpenHarmony的Docker镜像托管在HuaweiCloud SWR上。开发者可以通过该 1. 获取Docker镜像。 ``` -docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.5 +docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` 2. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 ``` -docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.5 +docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` ##### 方式二:通过Dockerfile 构建本地Docker镜像进行构建 @@ -30,16 +30,16 @@ cd docs/docker/standard ``` 3. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 ``` -docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.5 +docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 ``` ### 编译源码-标准系统类设备(参考内存≥128MB) 通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。 ``` -./build.sh --product-name {product_name} +./build.sh --product-name {product_name} --ccache ``` -{product_name}为当前版本支持的平台。比如:Hi3516DV300等。 +{product_name}为当前版本支持的平台。比如:Hi3516DV300、rk3568等。 编译所生成的文件都归档在out/{device_name}/目录下,结果镜像输出在 out/{device_name}/packages/phone/images/ 目录下。 diff --git a/docker/standard/build.sh b/docker/standard/build.sh index c2b8fb34f8dc9d367298d4755e3446115710c954..7becb89d88f900075950347442c812fc6c734505 100755 --- a/docker/standard/build.sh +++ b/docker/standard/build.sh @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -docker build -t openharmony-docker-standard:0.0.5 . +docker build -t openharmony-docker-standard:0.0.7 . diff --git a/docker/standard/dockerfile b/docker/standard/dockerfile index 65baafa798852b40d7cba68eb5650307456f0eeb..33db49299bf2ecbc6505cf6ab43b2fd181dd7307 100755 --- a/docker/standard/dockerfile +++ b/docker/standard/dockerfile @@ -90,8 +90,13 @@ RUN apt-get update \ python3.8 \ python3-pip \ cpio \ - && rm -rf /bin/sh \ + genext2fs \ + liblz4-tool \ + && rm -rf /bin/sh /usr/bin/python /usr/bin/python3 \ && ln -s /bin/bash /bin/sh \ + && ln -s /usr/bin/python3.8 /usr/bin/python3 \ + && ln -s /usr/bin/python3.8 /usr/bin/python \ + && python3 -m pip install --user ohos-build \ && mkdir -p $PREBUILTS_DIR/prebuilts $HOME_TOOLS RUN wget -P $HOME_TOOLS https://mirrors.huaweicloud.com/nodejs/v12.18.4/node-v12.18.4-linux-x64.tar.gz \ diff --git a/en/OpenHarmony-Overview.md b/en/OpenHarmony-Overview.md index 2e90b1a038c02932edf499a66363f55a594f3e91..6df659c230c4fd691638228177c243b489844422 100644 --- a/en/OpenHarmony-Overview.md +++ b/en/OpenHarmony-Overview.md @@ -344,7 +344,7 @@ The following table describes the subsystems of OpenHarmony. For details about t ## Getting Started -For details, see [https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/Readme-EN.md](https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/Readme-EN.md). +For details, see [device-dev/quick-start/Readme-EN.md](device-dev/quick-start/Readme-EN.md). ## Code Repository Addresses @@ -364,7 +364,7 @@ OpenHarmony archived projects: [https://gitee.com/openharmony-retired](https:// ## Source Code Downloading -For details about how to obtain the source code of OpenHarmony, see [Source Code Acquisition](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/source-code-acquisition.md). +For details about how to obtain the source code of OpenHarmony, see [Source Code Acquisition](https://gitee.com/openharmony/docs/blob/master/en/device-dev/get-code/sourcecode-acquire.md). ## How to Participate diff --git a/en/application-dev/ability/service-ability.md b/en/application-dev/ability/service-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..6b1556354adf1f55e937559831fe359072292345 --- /dev/null +++ b/en/application-dev/ability/service-ability.md @@ -0,0 +1,268 @@ +# Service Ability Development + +## Creating a Service Ability + +1. Create a child class of the **Ability** class and override the following Service ability-related lifecycle callbacks to implement your own logic for processing requests to interact with your Service ability: + + - onStart() + + This callback is invoked for initializing a Service ability when the Service ability is being created. This callback is invoked only once in the entire lifecycle of a Service ability. The **Want** object passed to this callback must be null. + + - onCommand() + + This callback is invoked every time a Service ability is created on a client. You can calculate calling statistics and perform initialization operations in this callback. + + - onConnect() + + This callback is invoked when another ability is connected to the Service ability. It returns an **IRemoteObject**. You can use this callback to generate a channel for the other ability to interact with the Service ability during inter-process communication (IPC). An ability can connect to the same Service ability for multiple times. When the first client is connected to a Service ability, the system calls **onConnect()** to generate an **IRemoteObject** for the Service ability, and the generated **IRemoteObject** will then be cached and used for all clients that are connected to this Service ability without having to call **onConnect()** again. + + - onDisconnect() + + This callback is invoked when another ability is disconnected from the Service ability. + + - onStop() + + This callback is invoked when a Service ability is being destroyed. You should override this callback for your Service ability to clear its resources, such as threads and registered listeners. + + The following code snippet shows how to create a Service ability: + + ```javascript + export default { + onStart(want) { + console.log('SerivceAbility onStart'); + }, + onCommand(want, restart, startId) { + console.log('SerivceAbility onCommand'); + }, + onConnect(want) { + console.log('SerivceAbility OnConnect'); + }, + onDisconnect() { + console.log('SerivceAbility OnDisConnect'); + }, + onStop() { + console.log('SerivceAbility onStop'); + }, + } + ``` + +2. Register a Service ability. + + You must declare your Service ability in the **config.json** file by setting its **type** attribute to **service**. + + ```javascript + { + "module": { + "abilities": [ + { + "name": ".ServiceAbility", + "type": "service", + "visible": true + ... + } + ] + ... + } + ... + } + ``` + + + + +## Starting and Stopping a Service Ability + +The **Ability** class provides the **startAbility()** method for you to start another Service ability by passing a **Want** object. + +To set information about the target Service ability, you can first construct a **Want** object with the **bundleName** and **abilityName** parameters specified. The meanings of the parameters are as follows: + +- **bundleName** indicates the name of the bundle to which the target ability belongs. +- **abilityName** indicates the target ability name. + +The following code snippet shows how to start a Service ability running on the local device: + +```javascript +import featureAbility from '@ohos.ability.featureability'; +var promise = await featureAbility.startAbility( + { + want: + { + bundleName: "com.jstest.serviceability", + abilityName: "com.jstest.serviceability.MainAbility", + }, + } +); +``` + +- Starting a Service ability + + After the preceding code is executed, the **startAbility()** method is called to start the Service ability. + - If the Service ability is not running, the system calls **onStart()** to initialize the Service ability, and then calls **onCommand()** on the Service ability. + - If the Service ability is running, the system directly calls **onCommand()** on the Service ability. + +- Stopping a Service ability + + Once created, the Service ability keeps running in the background. The system does not stop or destroy it unless memory resources must be reclaimed. You can call **terminateAbility()** on a Service ability to stop it or call **stopAbility()** on another ability to stop the specified Service ability. + + + +## 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** interface for the connection. A Service ability allows other abilities to connect to it through **connectAbility()**. + +When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the method. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. + +The following code snippet shows how to implement the callbacks: + +```javascript +var mRemote; +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect Callback') + mRemote = remote; +} + +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect Callback') +} + +function onFailedCallback(code){ + console.log('ConnectAbility onFailed Callback') +} +``` + +The following code snippet shows how to connect to a local Service ability: + +```javascript +import featureAbility from '@ohos.ability.featureability'; +var connId = featureAbility.connectAbility( + { + bundleName: "com.jstest.serviceability", + abilityName: "com.jstest.serviceability.MainAbility", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` + +When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**. + +The following code snippet shows how the Service ability instance returns itself to the calling ability: + +```javascript +import rpc from "@ohos.rpc"; + +var mMyStub; +export default { + onStart(want) { + class MyStub extends rpc.RemoteObject{ + constructor(des) { + if (typeof des === 'string') { + super(des); + } + return null; + } + onRemoteRequest(code, message, reply, option) { + } + } + mMyStub = new MyStub("ServiceAbility-test"); + }, + onCommand(want, restart, startId) { + console.log('SerivceAbility onCommand'); + }, + onConnect(want) { + console.log('SerivceAbility OnConnect'); + return mMyStub; + }, + onDisconnect() { + console.log('SerivceAbility OnDisConnect'); + }, + onStop() { + console.log('SerivceAbility onStop'); + }, +} +``` + +## Connecting to a Remote Service Ability + +If you need to connect a Service ability to a Page ability on another device or to a Service ability in another application on another device, you must first implement the **IAbilityConnection** interface for the connection. A Service ability allows other abilities on another device to connect to it through **connectAbility()**. + +When calling **connectAbility()**, you should pass a **Want** object containing information about the target Service ability and an **IAbilityConnection** object to the method. **IAbilityConnection** provides the following callbacks that you should implement: **onConnect()**, **onDisconnect()**, and **onFailed()**. The **onConnect()** callback is invoked when a Service ability is connected, **onDisconnect()** is invoked when a Service ability is unexpectedly disconnected, and **onFailed()** is invoked when a connection to a Service ability fails. + +The following code snippet shows how to implement the callbacks: + +```javascript +var mRemote; +function onConnectCallback(element, remote){ + console.log('ConnectRemoteAbility onConnect Callback') + mRemote = remote; +} + +function onDisconnectCallback(element){ + console.log('ConnectRemoteAbility onDisconnect Callback') +} + +function onFailedCallback(code){ + console.log('ConnectRemoteAbility onFailed Callback') +} +``` + +The **Want** of the target Service ability must contain the remote **deviceId**, which can be obtained through **deviceManager**. + +The following code snippet shows how to connect to a remote Service ability: + +```javascript +import featureAbility from '@ohos.ability.featureability'; +var connId = featureAbility.connectAbility( + { + deviceId: deviceId, + bundleName: "com.jstest.serviceability", + abilityName: "com.jstest.serviceability.MainAbility", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` + +When a Service ability is connected, the **onConnect()** callback is invoked and returns an **IRemoteObject** defining the proxy used for communicating with the Service ability. OpenHarmony provides a default implementation of the **IRemoteObject** interface. You can inherit **rpc.RemoteObject** to implement your own class of **IRemoteObject**. + +The following code snippet shows how the Service ability instance returns itself to the calling ability: + +```javascript +import rpc from "@ohos.rpc"; + +var mMyStub; +export default { + onStart(want) { + class MyStub extends rpc.RemoteObject{ + constructor(des) { + if (typeof des === 'string') { + super(des); + } + return null; + } + onRemoteRequest(code, message, reply, option) { + } + } + mMyStub = new MyStub("ServiceAbility-test"); + }, + onCommand(want, restart, startId) { + console.log('SerivceAbility onCommand'); + }, + onConnect(want) { + console.log('SerivceAbility OnConnect'); + return mMyStub; + }, + onDisconnect() { + console.log('SerivceAbility OnDisConnect'); + }, + onStop() { + console.log('SerivceAbility onStop'); + }, +} +``` diff --git a/en/application-dev/connectivity/ipc-rpc-overview.md b/en/application-dev/connectivity/ipc-rpc-overview.md index 2c8e177b40f6429157b8fe6b5289a17bef103f2f..938b2f56d8acf4d82e769767a49ab18ce7713d80 100755 --- a/en/application-dev/connectivity/ipc-rpc-overview.md +++ b/en/application-dev/connectivity/ipc-rpc-overview.md @@ -2,13 +2,15 @@ ## Basic Concepts -The inter-process communication \(IPC\) and remote procedure call \(RPC\) mechanisms are used to implement cross-process communication. The difference between them lies in that IPC uses the Binder driver to implement cross-process communication within a device, whereas RPC uses the Intelligent Soft Bus driver to implement cross-process communication across devices. IPC and RPC generally use a client-server model. The service requester \(client\) can obtain the proxy of the service provider \(server\) and use the proxy to read and write data, thus implementing data communication between processes. Generally, the server registers system abilities \(SAs\) with the system ability manager \(SAMgr\), which manages the SAs and provides APIs for the client. To communicate with a specific SA, the client must obtain the proxy of the SA from SAMgr. In this document, Proxy represents the service requester, and Stub represents the service provider. +The inter-process communication \(IPC\) and remote procedure call \(RPC\) mechanisms are used to implement cross-process communication. The difference between them lies in that IPC uses the Binder driver to implement cross-process communication within a device, whereas RPC uses the Intelligent Soft Bus driver to implement cross-process communication across devices. +
IPC and RPC generally use a client-server model. The service requester \(client\) can obtain the proxy of the service provider \(server\) and use the proxy to read and write data, thus implementing data communication between processes. Generally, the server registers system abilities \(SAs\) with the system ability manager \(SAMgr\), which manages the SAs and provides APIs for the client. To communicate with a specific SA, the client must obtain the proxy of the SA from SAMgr. In this document, proxy represents the service requester, and stub represents the service provider. ## Limitations and Constraints -Currently, cross-device RPC communication is not supported. + +- The data transmitted for cross-process communication on a device cannot exceed 1 MB. If more data needs to be transmitted, use the anonymous shared memory. +- The cross-device proxy object cannot be passed to the device hosting the stub object pointed by this proxy object. ## Related Modules Distributed Scheduler subsystem - diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md index 96855a6b6d426ea264ee25fd4447d0df6475f904..fa70738556ec7992c33fd8bcf3e74fbd6145fcb6 100755 --- a/en/application-dev/connectivity/subscribe-remote-state.md +++ b/en/application-dev/connectivity/subscribe-remote-state.md @@ -1,8 +1,6 @@ # Subscribing to State Changes of a Remote Object -IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. You can also unsubscribe from the state changes if they are no longer needed. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **IRemoteObject.DeathRecipient** interface and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object does not die, the proxy object can cancel the subscription when it is no longer required. If the stub object dies, subsequent operations customized by the proxy object will be automatically triggered, and the subscription does not need to be manually canceled. - -Currently, IPC supports death notifications for anonymous objects, but RPC does not. That is, you can only subscribe to death notifications of services that have been registered with SAMgr. +IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. You can also unsubscribe from the state changes if they are no longer needed. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **IRemoteObject.DeathRecipient** interface and the **onRemoteDied** method to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered. **Development Using Native APIs** @@ -25,4 +23,3 @@ sptr deathRecipient (new TestDeathRecipient()); / bool result = proxy->AddDeathRecipient(deathRecipient); // Add the recipient to the proxy. result = proxy->RemoveDeathRecipient(deathRecipient); // Remove the recipient. ``` - diff --git a/en/application-dev/media/audio-renderer.md b/en/application-dev/media/audio-renderer.md new file mode 100644 index 0000000000000000000000000000000000000000..2132f815703779ea03ab62f68caf7fae507db5c8 --- /dev/null +++ b/en/application-dev/media/audio-renderer.md @@ -0,0 +1,270 @@ +# Audio Playback Development Using AudioRenderer + +--- +## ***Note***: + 1. This document applies to JavaScript. + 2. Changes to the AudioRenderer interface have been proposed. + When the updated APIs have been integrated, the document will be revised, and apps must adapt to it. +--- +## **Summary** +This guide will show you how to use AudioRenderer to create an audio player app. +You can use the APIs provided in this document to play audio files in output devices and manage playback tasks. + +## **AudioRenderer Framework** +The AudioRenderer interface is one of the most important components of the audio framework. +### **Audio Rendering:** +The AudioRenderer framework provides APIs for playing audio files and controlling the playback. +### **Audio Interruption:** +When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\ +For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\ +With the sample code below, we'll look at how AudioInterrupt works in detail.\ +
+Please see [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType. + + +## **Usage** +Here's an example of how to use AudioRenderer to play a raw audio file. +1. Use **createAudioRenderer** to create an AudioRenderer instance for the **AudioVolumeType**.\ + This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications. + ``` + const volType = audio.AudioVolumeType.MEDIA; // For music + const audioRenderer = audio.createAudioRenderer(volType); + ``` + +2. Subscribe to audio interruption events using the **on** API.\ + Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\ + In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on. + + In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\ +
+ The following information will be provided by the Interrupt Event Notification: + + 1) **eventType:** Whether the interruption has begun or ended. + + | Value | Description | + | :------------------- | :-------------------------------------------- | + | INTERRUPT_TYPE_BEGIN | Indicates that the interruption has started. | + | INTERRUPT_TYPE_END | Indicates that the interruption has finished. | + + 2) **forceType:** Whether the framework has already taken action or if the app is being suggested to take action. + + | Value | Description | + | :-------------- | :------------------------------------------------------------------ | + | INTERRUPT_FORCE | The audio state has been changed by the framework. | + | INTERRUPT_SHARE | The app can decide whether or not to respond to the InterruptEvent. | + + 3) **hintType:** The kind of action taken or to be taken. + + | Value | Description | + | :-------------------- | :--------------------------- | + | INTERRUPT_HINT_PAUSE | Pausing the playback. | + | INTERRUPT_HINT_RESUME | Resuming the playback. | + | INTERRUPT_HINT_STOP | Stopping the playback. | + | INTERRUPT_HINT_DUCK | Ducking the stream volume. | + | INTERRUPT_HINT_UNDUCK | Unducking the stream volume. | + + 4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\ + For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback. + + | Action | Description | + | :-------------------- | :-------------------------------------------------------------------------------- | + | INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. | + | INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | + | INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. | + + ``` + audioRenderer.on('interrupt', (interruptEvent) => { + console.info('InterruptEvent Received'); + console.info('InterruptType: ' + interruptEvent.eventType); + console.info('InterruptForceType: ' + interruptEvent.forceType); + console.info('AInterruptHint: ' + interruptEvent.hintType); + + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + // Force Pause: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + break; + // Force Stop: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_STOP: + isPlay = false; + break; + // Force Duck: Action was taken by framework, + // just notifying the app that volume has been reduced. + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; + // Force Unduck: Action was taken by framework, + // just notifying the app that volume has been restored. + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + // Share Resume: Action is to be taken by App. + // Resume the force paused stream if required. + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + startRenderer(); + break; + // Share Pause: Stream has been interrupted, + // It can choose to pause or play concurrently. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + pauseRenderer(); + break; + } + } + }); + ``` + +3. Prepare the renderer. Call **SetParams** on the instance. You need to set the renderer parameters based on the audio playback specification. + ``` + async function prepareRenderer() { + // file_example_WAV_2MG.wav + var audioParams = { + format: audio.AudioSampleFormat.SAMPLE_S16LE, + channels: audio.AudioChannel.STEREO, + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_16000, + encoding: audio.AudioEncodingType.ENCODING_PCM, + }; + + let response = await audioRenderer.setParams(audioParams); + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_PREPARED) { + console.info('Prepare renderer failed'); + return; + } + } + ``` +4. Call the **start()** function on the AudioRenderer instance to start/resume the playback task.\ + The renderer state will be STATE _RUNNING once the start is complete. You can then begin writing buffers. + ``` + async function startRenderer() { + var state = audioRenderer.state; + // state should be prepared, paused or stopped. + if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || + state != audio.AudioState.STATE_STOPPED) { + console.info('Renderer is not in a correct state to start'); + return; + } + var started = await audioRenderer.start(); + if (started) { + isPlay = true; + console.info('Renderer started'); + } else { + console.error('Renderer start failed'); + return; + } + } + + ``` +5. Make **write** calls to start rendering the buffers. + Read the audio data to be played into a buffer. Call the write function repeatedly to write data. + ``` + async function writeBuffer(buf) { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING) { + console.error('Renderer is not running, do not write'); + isPlay = false; + return; + } + let writtenbytes = await audioRenderer.write(buf); + + console.info('Actual written bytes: ' + writtenbytes); + if (writtenbytes < 0) { + console.error('Write buffer failed. check the state of renderer'); + } + } + + // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. + const bufferSize = await audioRenderer.getBufferSize(); + const path = '/data/file_example_WAV_2MG.wav'; + let ss = fileio.createStreamSync(path, 'r'); + const totalSize = 2146166; // file_example_WAV_2MG.wav + let rlen = 0; + let discardHeader = new ArrayBuffer(44); + ss.readSync(discardHeader); + rlen += 44; + + var id = setInterval(() => { + if (isPlay || isRelease) { + if (rlen >= totalSize || isRelease) { + ss.closeSync(); + stopRenderer(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss.readSync(buf); + console.info('Total bytes read from file: ' + rlen); + writeBuffer(buf); + } else { + console.info('check after next interval'); + } + } , 30); // interval to be set based on audio file format + ``` + +6. (Optional) Call the **pause()** or **stop()** function on the AudioRenderer instance. +``` + async function pauseRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + var paused = await audioRenderer.pause(); + if (paused) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async function stopRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + var stopped = await audioRenderer.stop(); + if (stopped) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } +} +``` + +7. After the playback task is complete, call the **release()** function on the AudioRenderer instance to release resources.\ + AudioRenderer can use a lot of system resources. As a result, whenever the resources are no longer required, they must be released. To ensure that any system resources allocated to it are appropriately released, you should always call **release()**. +``` + async function releaseRenderer() { + if (state_ == RELEASED || state_ == NEW) { + console.info('Resourced already released'); + return; + } + var released = await audioRenderer.release(); + if (released) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + + } +``` + +## **Importance of State Check:** +You should also keep in mind that an AudioRenderer is state-based. +That is, the AudioRenderer has an internal state that you must always check when calling playback control APIs, because some operations are only acceptable while the renderer is in a given state.\ +The system may throw an error/exception or generate other undefined behaviour if you perform an operation while in the improper state.\ +Before each necessary operation, the example code performs a state check. + +## **Asynchronous Operations:** +Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\ +For each API, the framework provides both callback and promises functions.\ +In the example, promise functions are used for simplicity. [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) +provides reference for both callback and promise. + +## **Other APIs:** +See [**js-apis-audio.md**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize. + diff --git a/en/application-dev/media/sound-manager.md b/en/application-dev/media/sound-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..0aa02458d1ff1bb2cac91c5eec6af667827411a2 --- /dev/null +++ b/en/application-dev/media/sound-manager.md @@ -0,0 +1,166 @@ +# Development Guide for usage of SoundManager + +## **Summary** +This guide will show you how to use SoundManager to save and retrieve the ringtone, alarm and notification uris. +Also the document explains how to use ringtone player APIs to play a ringtone uri. + +## **SoundManager Framework** +The SoundManager interface consists of APIs which are used to save and retrieve ringtone, alarm and notification uris. +Other APIs required for ringtone playback is also provided by SoundManager. All the uris will be saved in persistent memory of the device. + +Please see [**SystemSoundManager**](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md##systemsoundmanager) for the list of APIs supported by SoundManager. + + +## **Usage** +- Here's an example of how to use SoundManager to save and retrieve alarm uri +1. Use **getSystemSoundManager** to get an SoundManager instance.\ + This object can be used to set and get alarm uri + ``` + const systemSoundManager = audio.getSystemSoundManager(); + ``` + +2. Use **setSystemAlarmUri** to save system alarm uri\ + Application should provide the application *context*, the *uri* to be saved while using this API. + + ``` + systemSoundManager.setSystemAlarmUri(context, '/data/media/alarm.wav', (err)=> { + if (err) { + console.error('Failed to setSystemAlarmUri'); + } else { + console.log('Callback invoked to indicate a successful system alarm uri setting.'); + } + }) + ``` + +3. Use **getSystemAlarmUri** to fetch system alarm uri\ + Application should provide the application *context* while using this API. + + ``` + systemSoundManager.getSystemAlarmUri(context, (err, alarmUri)=>{ + if (err) { + console.err('getSystemAlarmUri failed'); + } else { + console.log('getSystemAlarmUri success: ' + alarmUri); + } + }) + ``` + + +- Here's another example of how to use SoundManager for ringtone uri playback +1. Use **getSystemSoundManager** to get an SoundManager instance. + ``` + const systemSoundManager = audio.getSystemSoundManager(); + ``` + +2. Use **setSystemRingtoneUri** to set system ringtone uri\ + Application should provide the application *context*, *uri* to be saved and the [*RingtoneType*](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md#ringtonetype8) while using this API. + + ``` + systemSoundManager.setSystemRingtoneUri(context, '/data/media/ringtone_sim1.wav', + audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err)=> { + if (err) { + console.error('Failed to setSystemRingtoneUri'); + } else { + console.log('Callback invoked to indicate a successful system ringtone uri setting.'); + } + }) + ``` + +3. Use **getSystemRingtonePlayer** to get ringtone player instance\ + Application should provide the application *context* and the [*RingtoneType*](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md#RingtoneType8) while using this api. + + ``` + systemSoundManager.getSystemRingtonePlayer(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err, ringtonePlayer)=>{ + if (err) { + console.err('getSystemRingtonePlayer failed'); + } else { + console.log('getSystemRingtonePlayer success: '); + } + }); + ``` + +4. Use **configure** api to configure the ringtone player + [*RingtoneOptions*](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-audio.md#ringtoneoptions8) should be provided while using this api. + + ``` + let ringtoneOptions = { + volume: 1, + loop: false + }; + + ringtonePlayer.configure(ringtoneOptions, (err)=> { + if (err) { + console.error('Failed to configure ringtone options'); + } else { + console.log('Callback invoked to indicate a successful ringtone options configuration.'); + } + }); + ``` + +5. Use **start** api to start playing the ringtone\ + *Note*: If *loop* was true in configure, the ringtone will continue to play until its stopped explicity. + ``` + ringtonePlayer.start((err)=> { + if (err) { + console.error('Failed to start playing ringtone'); + } else { + console.log('Ringtone start playing successfully.'); + } + }); + ``` + +6. Use **stop** api to stop the ringtone while play is in progress + ``` + ringtonePlayer.stop((err)=> { + if (err) { + console.error('Failed to stop playing ringtone'); + } else { + console.log('Ringtone stop playing successfully.'); + } + }); + ``` + +7. Use **release** api to release the ringtone player resources + ``` + ringtonePlayer.release((err)=> { + if (err) { + console.error('Failed to release ringtone player resource'); + } else { + console.log('Release ringtone player resource successfully.'); + } + }); + ``` + +## **Other APIs** +ringtonePlayer object provides few more apis like; + +1. **state** + This is a readonly variable, which will contain the current state of the ringtone player. + ``` + let playerState = ringtonePlayer.state + ``` + +2. **getTitle** + This api will return the title of the ringtone uri from the file metadata + + ``` + ringtonePlayer.getTitle((err, title)=>{ + if (err) { + console.err('getTitle failed'); + } else { + console.log('getTitle success: ' + title); + } + }); + ``` + +3. **getAudioRendererInfo** + This api will return the audio renderer information + ``` + ringtonePlayer.getAudioRendererInfo((err, rendererInfo)=>{ + if (err) { + console.err('getAudioRendererInfo failed'); + } else { + console.log('getAudioRendererInfo success'); + } + }); + ``` diff --git a/en/application-dev/quick-start/configuring-openharmony-app-signature.md b/en/application-dev/quick-start/configuring-openharmony-app-signature.md index 9c542bea4bd0852f64f996d6eead0ea1e5077510..49abca3fa152bfd836d6be71ede47aa78a77a70b 100644 --- a/en/application-dev/quick-start/configuring-openharmony-app-signature.md +++ b/en/application-dev/quick-start/configuring-openharmony-app-signature.md @@ -1,12 +1,104 @@ # Configuring the OpenHarmony App Signature +- [Generating a Key Store and CSR](#section153146467405) + - [In DevEco Studio](#section1298903211472) + - [In a Command-Line Tool](#section1276462024811) + +- [Generating an App Certificate](#section136609429562) +- [Generating the App Profile](#section2048641015325) +- [Configuring App Signature Information](#section10152423193310) + Before running and debugging the OpenHarmony app on a real device, you need to sign the app. This section describes how to configure the signature of an OpenHarmony app. Operation instructions are the same in _HUAWEI DevEco Studio User Guide_ except this section. For details, see [HUAWEI DevEco Studio User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/tools_overview-0000001053582387). See the following figure for the process of configuring app signature information. ![](figures/en-us_image_0000001113808114.png) ## Generating a Key Store and CSR -OpenHarmony uses digital certificates \(.cer\) and **Profile** files \(.p7b\) to ensure app integrity. Before applying for these files, you need to generate a key store \(.p12\) and a certificate signing request \(.csr\). You can do so in DevEco Studio or a command-line tool. For details, see [Generating a Key Store and CSR](https://developer.harmonyos.com/en/docs/documentation/doc-guides/publish_app-0000001053223745#section9752152162813). +OpenHarmony uses digital certificates \(.cer\) and **Profile** files \(.p7b\) to ensure app integrity. Before applying for these files, you need to generate a key store \(.p12\) and a certificate signing request \(.csr\). You can do so in DevEco Studio or a command-line tool. + +### In DevEco Studio + +1. On the menu bar, choose **Build** \> **Generate Key and CSR**. + + >![](../public_sys-resources/icon-note.gif) **NOTE:** + >If you have a local key, click **Skip** in the **Generate Key** window and use the key to generate a CSR file. + +2. In **Key Store File**, click **Choose Existing** to select an existing key store \(.p12 file that contains a key\) or **New** to create one. The following describes how to create a key store. + + ![](figures/en-us_image_0000001119560738.png) + +3. In the **Create Key Store** dialog box, set the following parameters and click **OK**. + + - **Key Store File**: Select the path for storing the key store. + - **Password**: Set the key store password, which must contain at least 8 characters that include two types of the following: uppercase letters, lowercase letters, digits, and special characters. Do not lose the password as it will be used later in configuring the signature. + - **Confirm Password**: Enter the key store password again. + + ![](figures/en-us_image_0000001152674854.png) + +4. In the **Generate Key** window, set the following parameters and click **Next**. + + - **Alias**: Enter the alias of the key, which is used to identify the key name. Do not lose the alias as it will be used later in configuring the signature. + - **Password**: password of the key, which is automatically filled in and the same as the keystore password. + - **Validity**: Specify the certificate validity period. A validity period of 25 years or longer is recommended to cover the entire lifecycle of your app/service. + - **Certificate**: Enter basic certificate information. + + ![](figures/en-us_image_0000001117639668.png) + +5. In the **Generate CSR** window, select the key and set the storage path of the CSR file. + + ![](figures/en-us_image_0000001117479776.png) + +6. Click **OK**. You can then obtain the generated keystore file \(.p12\) and CSR file \(.csr\) from the storage path. + + ![](figures/en-us_image_0000001163839541.png) + + +### In a Command-Line Tool + +Use the Keytool in the Open JDK to generate a CSR. + +1. Run the Keytool as an administrator. + + ![](figures/en-us_image_0000001248045243.png) + +2. Switch to the directory where the Keytool is located. + + ![](figures/en-us_image_0000001247125297.png) + +3. Run the following command to generate a key store. This example creates a key store named **ide\_demo\_app.p12** and saves it to the root directory of the D drive. + + ``` + keytool -genkeypair -alias "ide_demo_app" -keyalg EC -sigalg SHA256withECDSA -dname "C=CN,O=HUAWEI,OU=HUAWEI IDE,CN=ide_demo_app" -keystore d:\\idedemokey.p12 -storetype pkcs12 -validity 9125 -storepass 123456Abc -keypass 123456Abc + ``` + + Parameters in the key store: + + >![](../public_sys-resources/icon-note.gif) **NOTE:** + >Record the values of **alias**, **storepass**, and **keypass**, which will be used in [Configuring App Signature Information](#section10152423193310). + + - **alias**: alias of the key, which is used to identify the key name. + - **sigalg**: signature algorithm, which is automatically set to **SHA256withECDSA** and cannot be changed. + - **dname**: + - **C**: country/region code, such as **CN**. + - **O**: organization name, such as **HUAWEI**. + - **OU**: organization unit name, such as **HUAWEI IDE**. + - **CN**: your first name and last name. Set this parameter to be the same as **alias**. + + - **validity**: certificate validity period. It is recommended that you set this parameter to **9125** \(25 years\). + - **storepass**: key store password, which must contain at least 8 characters that include two types of the following: uppercase letters, lowercase letters, digits, and special characters. Do not lose the password as it will be used later in configuring the signature. + - **keypass**: password of the key. The value must be the same as that of **storepass**. + +4. Run the following command. After the command is executed, enter the **storepass** to generate a CSR in .csr format. + + ``` + keytool -certreq -alias "ide_demo_app" -keystore d:\\idedemokey.p12 -storetype pkcs12 -file d:\\idedemokey.csr + ``` + + Parameters in the CSR: + + - **alias**: The value must be the same as the alias set in 3. + - **file**: name of the generated CSR. The file name extension is .csr. + ## Generating an App Certificate @@ -32,12 +124,12 @@ Refer to the following descriptions about the parameters in the command: ## Generating the App Profile -The profile contains the package name of the OpenHarmony app, digital certificate information, certificate permissions that can be applied for by the app, and devices that support app debugging \(the device list will be empty if the app type is Release\). Each app package must contain a profile file. +The profile contains the following inforamtion about the OpenHarmony app: bundle name, digital certificate information, certificate permissions that can be applied for by the app, and devices where the app can be debugged \(the device list will be empty if the app type is Release\). Each app package must contain a profile file. Go to the **Sdk\\toolchains\\lib** directory, open the command-line tool, and run the following command. ``` -java -jar provisionsigtool.jar sign --in UnsgnedReleasedProfileTemplate.json --out myApplication_ohos_Provision.p7b --keystore OpenHarmony.p12 --storepass 123456 --alias "OpenHarmony Application Profile Release" --sigAlg SHA256withECDSA --cert OpenHarmonyProfileRelease.pem --validity 365 --developer-id ohosdeveloper --bundle-name package name --permission restricted permission name (optional) --permission restricted permission name (optional) --distribution-certificate myApplication_ohos.cer +java -jar provisionsigtool.jar sign --in UnsgnedReleasedProfileTemplate.json --out myApplication_ohos_Provision.p7b --keystore OpenHarmony.p12 --storepass 123456 --alias "OpenHarmony Application Profile Release" --sigAlg SHA256withECDSA --cert OpenHarmonyProfileRelease.pem --validity 365 --developer-id ohosdeveloper --bundle-name app bundle name --permission restricted permission name (optional) --permission restricted permission name (optional) --distribution-certificate myApplication_ohos.cer ``` Refer to the following descriptions about the parameters in the command: @@ -52,7 +144,7 @@ Refer to the following descriptions about the parameters in the command: - **cert**: path of the certificate of the signature profile. The file is stored in **Sdk\\toolchains\\lib** of the OpenHarmony SDK. This parameter cannot be modified. - **validity**: certificate validity period, which is user-defined. - **developer-id**: developer ID, which is a user-defined character string. -- **bundle-name**: app package name. +- **bundle-name**: app bundle name. - **permission** \(optional\): If permissions are not required, this field can be left empty. You can add multiple restricted permissions in the following way: ohos.permission.READ\_CONTACTS, ohos.permission.WRITE\_CONTACTS. - **distribution-certificate**: certificate generated in [Generating an App Certificate](#section136609429562). diff --git a/en/application-dev/quick-start/configuring-openharmony-sdk.md b/en/application-dev/quick-start/configuring-openharmony-sdk.md index b6dfc0e2ec7c2b7876852428e9574ed75eafd9bb..fa4b76112a1e0055332535e019d9178f8ab4ffe3 100644 --- a/en/application-dev/quick-start/configuring-openharmony-sdk.md +++ b/en/application-dev/quick-start/configuring-openharmony-sdk.md @@ -1,5 +1,13 @@ # Configuring the OpenHarmony SDK +- [Prerequisites](#section164161442154812) +- [Configuring the SDK Information](#section1265592425017) +- [References](#section0384143616409) + - [Setting Up the DevEco Studio Proxy](#section10129720184214) + - [Setting Up the npm Proxy](#section19984059114316) + - [Setting Up the Gradle Proxy](#section164211820465) + + To set up the OpenHarmony app development environment, configure the corresponding SDK information in DevEco Studio first. >![](../public_sys-resources/icon-note.gif) **NOTE:** @@ -22,13 +30,18 @@ DevEco Studio manages SDKs and toolchains using SDK Manager. OpenHarmony contain -

SDK

+

SDK

JS

SDK for JS.

+

eTS

+ +

SDK for Extended TypeScript (eTS).

+ +

SDK Tool

Toolchains

@@ -61,9 +74,6 @@ DevEco Studio manages SDKs and toolchains using SDK Manager. OpenHarmony contain 4. On the **Settings Confirmation** page, click **Next**. When the **License Agreement** dialog box appears, click **Accept**. - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >If the message "Install js dependencies failed." is displayed during SDK download, follow the FAQ about the [JS SDK Installation Failure](https://developer.harmonyos.com/en/docs/documentation/doc-guides/faq-development-environment-0000001168829643#section1311117111474) to troubleshoot. - ![](figures/en-us_image_0000001163472654.png) 5. After the OpenHarmony SDK and tools are downloaded, click **Finish** to access the DevEco Studio welcome page. @@ -79,7 +89,7 @@ Generally, only some enterprise networks rather than personal area networks or h If you are using DevEco Studio for the first time and the **Set up HTTP Proxy** page is displayed, it indicates that your network requires a proxy. In this case, set up the DevEco Studio proxy, npm proxy, and Gradle proxy. -![](figures/en-us_image_0000001123021842.png) +![](figures/en-us_image_0000001166582138.png) ### Setting Up the DevEco Studio Proxy @@ -87,8 +97,8 @@ If you are using DevEco Studio for the first time and the **Set up HTTP Proxy** >![](../public_sys-resources/icon-note.gif) **NOTE:** >If this is not the first time you are using DevEco Studio: - >- On the welcome page, choose **Configure** \(or the ![](figures/en-us_image_0000001122862128.png) icon\) \> **Settings** \> **Appearance & Behavior** \> **System Settings** \> **HTTP Proxy** to access the HTTP proxy settings. \(For macOS, choose **Configure** \> **Preferences** \> **Appearance & Behavior** \> **System Settings** \> **HTTP Proxy**.\) - >- When on a project page, choose **File** \> **Settings** \> **Appearance & Behavior** \> **System Settings** \> **HTTP Proxy** to access the HTTP proxy settings. \(For macOS, choose **DevEco Studio** \> **Preferences** \> **Appearance & Behavior** \> **System Settings** \> ** HTTP Proxy**.\) + >- On the welcome page, choose **Configure** \(or ![](figures/en-us_image_0000001212142015.png)\)** \> Settings \> Appearance & Behavior \> System Settings \> HTTP Proxy** to access the HTTP Proxy settings. \(For macOS, choose **Configure \> Preferences \> Appearance & Behavior \> System Settings \> HTTP Proxy**.\) + >- When on a project page, choose **File \> Settings \> Appearance & Behavior \> System Settings \> HTTP Proxy** to access the HTTP Proxy settings. \(For macOS, choose **DevEco Studio \> Preferences \> Appearance & Behavior \> System Settings \> HTTP Proxy**.\) - **HTTP** parameters: **If you are not sure about the information, contact your network administrator.** - **Host name**: Enter the host name or IP address of the proxy server. @@ -100,9 +110,9 @@ If you are using DevEco Studio for the first time and the **Set up HTTP Proxy** - **Password**: Enter the password used to access the proxy server. - **Remember**: Select this option to remember the password. - ![](figures/en-us_image_0000001123021962.png) + ![](figures/en-us_image_0000001212062065.png) -2. When you have finished, click **Check connection** and enter a URL \(for example, **https://developer.harmonyos.com**\) to check the network connectivity. If the message "Connection successful" is displayed, it indicates that the proxy was set up successfully. +2. When you have finished, click **Check connection** and enter a URL to check the network connectivity. If the message "Connection successful" is displayed, it indicates that the proxy was set up successfully. 3. Click **Next: Configure npm** to set up the npm proxy. For details, see [Setting Up the npm Proxy](#section19984059114316). ### Setting Up the npm Proxy @@ -153,13 +163,13 @@ If your proxy server requires the user name and password for authentication, set 4. When you are done, follow the instructions in [Configuring the SDK Information](#section1265592425017). -### Setting up the Gradle Proxy +### Setting Up the Gradle Proxy 1. Open **This PC**, and enter **%userprofile%** in the address box to access the user profile. \(For macOS, choose **Go** \> **Home**.\) - ![](figures/en-us_image_0000001123024482.png) + ![](figures/en-us_image_0000001166740700.png) -2. Create a **.gradle.** folder if there is none. +2. Create a **.gradle** folder if there is none. >![](../public_sys-resources/icon-note.gif) **NOTE:** >Before creating a **.gradle** folder in macOS, set the system to show hidden files. diff --git a/en/application-dev/quick-start/deveco-studio-overview.md b/en/application-dev/quick-start/deveco-studio-overview.md index ea003805d6a97a9f4c9cfdf646c00beafa741626..b3b27928b539baebc573322dab9c3d20a26442d4 100644 --- a/en/application-dev/quick-start/deveco-studio-overview.md +++ b/en/application-dev/quick-start/deveco-studio-overview.md @@ -1,5 +1,9 @@ # Overview +- [About the Document](#section189422248491) +- [Restrictions](#section65191625782) +- [DevEco Studio Evolution Roadmap](#section187875207166) + ## About the Document DevEco Studio is an integrated development environment \(IDE\) of HarmonyOS apps. As HarmonyOS is developed based on OpenHarmony, DevEco Studio can also be used to develop OpenHarmony apps. @@ -7,15 +11,15 @@ DevEco Studio is an integrated development environment \(IDE\) of HarmonyOS apps The process of developing an OpenHarmony app using DevEco Studio is the same as that of developing a HarmonyOS app. This document describes the differences between OpenHarmony and HarmonyOS app development. - **Environment setup**: You need to manually install the OpenHarmony SDK for the OpenHarmony app development. For details, see [Configuring the OpenHarmony SDK](configuring-openharmony-sdk.md). -- **OpenHarmony project import**: To develop an OpenHarmony app, you can only import a sample project to start with. For details, see [Importing a Sample to Create a Project](import-sample-to-create-project.md). +- **Creating an OpenHarmony project**: Create a project by using the project wizard or by importing a sample project. For details, see [Using the Project Wizard to Create a Project](use-wizard-to-create-project.md). - **Signature configuration for debugging**: To run an OpenHarmony app on a real device, you need to sign the app first. For instructions, see [Configuring the OpenHarmony App Signature](configuring-openharmony-app-signature.md). -- **App running on a real device**: To run your app on a real device, you need to use the hdc tool to push the HAP package of the OpenHarmony to the real device for installation. For details, see [Installing and Running Your OpenHarmony App](installing-openharmony-app.md). +- **App running on a real device**: Push the OpenHarmony HAP package to the real device for installation. For details, see [Installing and Running Your OpenHarmony App](installing-openharmony-app.md). For details about how to use DevEco Studio, see [HUAWEI DevEco Studio User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/tools_overview-0000001053582387). ## Restrictions -- OpenHarmony supports only app development in JS. +- OpenHarmony supports only app development in eTS and JS. - Developing OpenHarmony apps in DevEco Studio is supported on Windows. DevEco Studio serves as a development tool for both OpenHarmony and HarmonyOS apps. Refer to the following table for descriptions about the functions not supported for OpenHarmony. @@ -29,14 +33,7 @@ DevEco Studio serves as a development tool for both OpenHarmony and HarmonyOS ap -

Creating modules

- -

- -

X

- - -

Service widgets

+

Service widgets

@@ -64,7 +61,7 @@ DevEco Studio serves as a development tool for both OpenHarmony and HarmonyOS ap

X

-

Using DevEco Studio for debugging, log viewing, and optimization

+

Using DevEco Studio for log viewing and optimization

diff --git a/en/application-dev/quick-start/deveco-studio-release-notes.md b/en/application-dev/quick-start/deveco-studio-release-notes.md index 0338e0e751383a28e5bae7c6a8892bc03a8fc0c2..267eadfc90914db13d9edd4dc2391f0ba0dea243 100644 --- a/en/application-dev/quick-start/deveco-studio-release-notes.md +++ b/en/application-dev/quick-start/deveco-studio-release-notes.md @@ -1,5 +1,79 @@ # Version Change History +- [V3.0 Beta2 \(2021-12-31\)](#section18825185716537) + - [Version Compatibility](#section8155205312218) + - [Version Change History](#section1655415918226) + +- [V3.0 Beta1 \(2021-09-29\)](#section21092033115018) + +## V3.0 Beta2 \(2021-12-31\) + +### Version Compatibility + +DevEco Studio 3.0 Beta2 is compatible with the module versions listed below. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Module

+

Version

+

Description

+

Gradle

+

7.3 (7.2 at minimum)

+

DevEco Studio has Gradle 7.3 preinstalled. No separate installation is required.

+

JDK

+

11.0.x

+

DevEco Studio has JDK 11 preinstalled. No separate installation is required.

+

OpenHarmony SDK

+

3.1.0.0 (API Version 8 Beta)

+

This version is compatible with SDKs of earlier versions.

+

Toolchinas

+

3.1.0.0

+

Update them to the latest version.

+

hap plug-in

+

3.0.5.2

+

decctest plug-in

+

1.2.7.2

+
+ +### Version Change History + + + + +

New Features

+
  • Introduced the Chinese UI. By default, the UI is displayed in English. To enable the Chinese UI, go to Settings, choose Plugins > installed, and select Chinese (Simplified). Then, restart DevEco Studio for the settings to take effect.
  • Introduced support for OpenHarmony apps and services, with various debugging features, from breakpoint management and variable observation to stepping.
+

+

Enhanced Features

+
  • Updated the OpenHarmony SDK to 3.1.0.0, whose API version is API 8 Beta and corresponding compilation and building plugin is 3.0.5.2.
  • Added an ability template that supports low-code development: [Standard]Empty Ability.
  • Added eTS component preview: allows previewing of eTS components; requires compileSdkVersion 8 or later.
  • Added eTS livee preview: allows viewing of the attribute changes in real time as you make them; requires compileSdkVersion 8 or later.
+
+ ## V3.0 Beta1 \(2021-09-29\) diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121904.png b/en/application-dev/quick-start/figures/en-us_image_0000001117479776.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121904.png rename to en/application-dev/quick-start/figures/en-us_image_0000001117479776.png diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121903.png b/en/application-dev/quick-start/figures/en-us_image_0000001117639668.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121903.png rename to en/application-dev/quick-start/figures/en-us_image_0000001117639668.png diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121901.png b/en/application-dev/quick-start/figures/en-us_image_0000001119560738.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121901.png rename to en/application-dev/quick-start/figures/en-us_image_0000001119560738.png diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121902.png b/en/application-dev/quick-start/figures/en-us_image_0000001152674854.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121902.png rename to en/application-dev/quick-start/figures/en-us_image_0000001152674854.png diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121905.png b/en/application-dev/quick-start/figures/en-us_image_0000001163839541.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121905.png rename to en/application-dev/quick-start/figures/en-us_image_0000001163839541.png diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001166582138.png b/en/application-dev/quick-start/figures/en-us_image_0000001166582138.png new file mode 100644 index 0000000000000000000000000000000000000000..36dc2d05ca4eb23505a73cb0d1606afd3bf844d8 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001166582138.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001166740700.png b/en/application-dev/quick-start/figures/en-us_image_0000001166740700.png new file mode 100644 index 0000000000000000000000000000000000000000..cedbb0ed07d4249c736f2b358593141f2f4cdc8e Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001166740700.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001196050928.png b/en/application-dev/quick-start/figures/en-us_image_0000001196050928.png new file mode 100644 index 0000000000000000000000000000000000000000..dd75ea8e2b874aae201ecab3254fac3a7bce8fbc Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001196050928.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001212062065.png b/en/application-dev/quick-start/figures/en-us_image_0000001212062065.png new file mode 100644 index 0000000000000000000000000000000000000000..708b49814e270289c6d1c96520aa6d90ba0edb9c Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001212062065.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001212142015.png b/en/application-dev/quick-start/figures/en-us_image_0000001212142015.png new file mode 100644 index 0000000000000000000000000000000000000000..74b66efabbbbbea4752f0296985486369a0cdc74 Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001212142015.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001239855207.png b/en/application-dev/quick-start/figures/en-us_image_0000001239855207.png new file mode 100644 index 0000000000000000000000000000000000000000..83ef94f222a2cc30f036057908960badedd4aeca Binary files /dev/null and b/en/application-dev/quick-start/figures/en-us_image_0000001239855207.png differ diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121907.png b/en/application-dev/quick-start/figures/en-us_image_0000001247125297.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121907.png rename to en/application-dev/quick-start/figures/en-us_image_0000001247125297.png diff --git a/zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121906.png b/en/application-dev/quick-start/figures/en-us_image_0000001248045243.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/zh-cn_image_0000002021121906.png rename to en/application-dev/quick-start/figures/en-us_image_0000001248045243.png diff --git a/en/application-dev/quick-start/installing-openharmony-app.md b/en/application-dev/quick-start/installing-openharmony-app.md index 8fe627f9560280d6b544cd49f8678d0fa74ba94f..7811ca957ef9fe77fcb928216c1eaf92e2830d99 100644 --- a/en/application-dev/quick-start/installing-openharmony-app.md +++ b/en/application-dev/quick-start/installing-openharmony-app.md @@ -1,41 +1,34 @@ # Installing and Running Your OpenHarmony App -To install your OpenHarmony app, use the hdc tool to manually run the corresponding commands. +You can install your OpenHarmony app in either of the following methods: -You can manually obtain the hdc tool from the open-source repository. Use the tool to send the compiled HAP package to the device and run the corresponding hdc commands to install the app. +- DevEco Studio: Connect your device where the app is stored to DevEco Studio, and then click ![](figures/en-us_image_0000001239855207.png) to install the app. +- hdc: Run commands to install the app. -The hdc commands are as follows: + You can manually obtain the hdc tool from the open-source repository. Then, run the tool commands to install an HAP file on the device. -- File sending + The tool commands are as follows: - **file send _localpath remotepath_** + - App installation - Example: + **install \[-r/-d/-g\] _package_** - ``` - hdc_std file send E:\hwadmin.hap /data/local/tmp/hwadmin.hap - ``` + Example: -- App installation + ``` + hdc_std install E:\hwadmin.hap + ``` - **install \[-r/-d/-g\] _package_** + - Log capturing - Example: + **hilog** - ``` - hdc_std install hwadmin.hap - ``` + Example: -- Log capturing + ``` + hdc_std hilog + ``` - **hilog** + For details about how to use hdc and the command format, see [hdc\_std Usage Guidelines](https://gitee.com/openharmony/docs/blob/master/en/device-dev/subsystems/oem_subsys_toolchain_hdc_guide.md). - Example: - - ``` - hdc_std hilog - ``` - - -For details about how to use the hdc tool and the command format, see the open-source repository **docs/en/device-dev/subsystems/hdc-usage-guidelines.md**. diff --git a/en/application-dev/quick-start/public_sys-resources/icon-caution.gif b/en/application-dev/quick-start/public_sys-resources/icon-caution.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/quick-start/public_sys-resources/icon-caution.gif differ diff --git a/en/application-dev/quick-start/public_sys-resources/icon-danger.gif b/en/application-dev/quick-start/public_sys-resources/icon-danger.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/quick-start/public_sys-resources/icon-danger.gif differ diff --git a/en/application-dev/quick-start/public_sys-resources/icon-note.gif b/en/application-dev/quick-start/public_sys-resources/icon-note.gif new file mode 100644 index 0000000000000000000000000000000000000000..6314297e45c1de184204098efd4814d6dc8b1cda Binary files /dev/null and b/en/application-dev/quick-start/public_sys-resources/icon-note.gif differ diff --git a/en/application-dev/quick-start/public_sys-resources/icon-notice.gif b/en/application-dev/quick-start/public_sys-resources/icon-notice.gif new file mode 100644 index 0000000000000000000000000000000000000000..86024f61b691400bea99e5b1f506d9d9aef36e27 Binary files /dev/null and b/en/application-dev/quick-start/public_sys-resources/icon-notice.gif differ diff --git a/en/application-dev/quick-start/public_sys-resources/icon-tip.gif b/en/application-dev/quick-start/public_sys-resources/icon-tip.gif new file mode 100644 index 0000000000000000000000000000000000000000..93aa72053b510e456b149f36a0972703ea9999b7 Binary files /dev/null and b/en/application-dev/quick-start/public_sys-resources/icon-tip.gif differ diff --git a/en/application-dev/quick-start/public_sys-resources/icon-warning.gif b/en/application-dev/quick-start/public_sys-resources/icon-warning.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/quick-start/public_sys-resources/icon-warning.gif differ diff --git a/en/application-dev/quick-start/use-wizard-to-create-project.md b/en/application-dev/quick-start/use-wizard-to-create-project.md index 52c52a9af31967a6e77b760fae9f7dd56f5929b6..ad79e3e8cb207af84457352188a15ce4c4ea898b 100644 --- a/en/application-dev/quick-start/use-wizard-to-create-project.md +++ b/en/application-dev/quick-start/use-wizard-to-create-project.md @@ -1,5 +1,8 @@ # Using the Project Wizard to Create a Project +- [Prerequisites](#section13642104391619) +- [Procedure](#section132671712101714) + If you are using DevEco Studio 2.2 Beta1 or later, you can use the project wizard to create a project. If you are using DevEco Studio 2.1 Release, create a project by following instructions in [Importing a Sample to Create a Project](import-sample-to-create-project.md). ## Prerequisites @@ -17,8 +20,8 @@ The OpenHarmony SDK has been installed. For details, see [Configuring the OpenH ![](figures/en-us_image_0000001162463400.png) 3. Click **Next** and configure the project. - - **Project Name**: customized project name. - - **Project Type**: project type , which can be an [atomic service](https://developer.harmonyos.com/en/docs/documentation/doc-guides/atomic-service-definition-0000001090840664) or an ordinary app that requires download before use. + - **Project name**: customized project name. + - **Project type**: project type, which can be an [atomic service](https://developer.harmonyos.com/en/docs/documentation/doc-guides/atomic-service-definition-0000001090840664) or an ordinary app that requires download before use. >![](../public_sys-resources/icon-note.gif) **NOTE:** >If you're creating an atomic service: @@ -27,17 +30,18 @@ The OpenHarmony SDK has been installed. For details, see [Configuring the OpenH >- If the value of the **installationFree** field of the entry module is set to **true**, the value of the **installationFree** field of all the related HAP modules is **true** by default. If the** installationFree field** of the entry module is set to **false**, the **installationFree** field of all the related HAP modules can be set to **true** or **false**. >- When compiling and building an app, make sure that the size of each HAP package does not exceed 10 MB. - - **Package Name**: software package name. By default, this name will also be used as your app ID. Assign a unique package name because your app must have a unique ID to be released. - - **Save Location**: local path for storing the project file. - - **Compatible API Version**: earliest SDK version compatible with your app. + - **Bundle name**: bundle name. By default, this name will also be used as your app ID. Your app must have a unique ID to be released. If **Project type** is set to **Atomic service**, the **Bundle name** must end with **.hmservice**. + - **Save location**: local path for storing the project file. + - **Development mode**: development mode. The **Super Visual** option is available if the project template supports low-code development. + - **Language**: supported programming language. + - **Compatible API version**: earliest SDK version compatible with your app. >![](../public_sys-resources/icon-note.gif) **NOTE:** - >If **compileSdkVersion 7** or later is configured for the OpenHarmony project, the corresponding module will be compiled using the Ark Compiler by default. To change the compilation mode to non-Ark compilation, add the **arkEnable false** field to the **ohos** closure in the module-level **build.gradle** file. + >If **compileSdkVersion 7** or later is configured for the OpenHarmony project, the corresponding module will be compiled using ArkCompiler by default. To use a compiler other than ArkCompiler, add the **arkEnable false** field to the **ohos** closure in the module-level **build.gradle** file. - - **Language**: supported programming language. - **Device Type**: device type supported by the project template. - ![](figures/en-us_image_0000001208210505.png) + ![](figures/en-us_image_0000001196050928.png) 4. Click **Finish**. DevEco Studio will automatically generate the sample code and resources that match your project type. Wait until the project is created. diff --git a/en/application-dev/reference/Readme-EN.md b/en/application-dev/reference/Readme-EN.md index 2f6b6ab2d850444294bb8a274ed76b06409d9ebb..0730fd77fd56fef492927c964e97ff47bc733610 100644 --- a/en/application-dev/reference/Readme-EN.md +++ b/en/application-dev/reference/Readme-EN.md @@ -2,6 +2,6 @@ - [JavaScript-based Web-like Development Paradigm](arkui-js/Readme-EN.md) - [TypeScript-based Declarative Development Paradigm](arkui-ts/Readme-EN.md) -- [APIs](apis/apis.md) +- [APIs](apis/Readme-EN.md) \ No newline at end of file diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 591571711b2440ed4aba0f29e4bee2652dd6a114..a8c67d7a907654e92085fc4a20fd56938c5e8f3d 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,17 +1,65 @@ # APIs -- [Console Logs](console-logs.md) -- [HiAppEvent](hiappevent.md) -- [Page Routing](page-routing.md) -- [Pop-up Window](pop-up-window.md) -- [Timer](timer.md) -- [Audio Management](js-apis-audio.md) -- [Audio Playback](audio-playback.md) -- [Device Information](device-information.md) -- [System Attribute](system-attribute.md) -- [Battery and Charging](battery-and-charging.md) -- [Screen Brightness](screen-brightness.md) -- [Globalization](globalization.md) -- [Resource Management](resource-management.md) -- [Updater](updater.md) +- Ability Framework + - [FeatureAbility Module](js-apis-featureAbility.md) + - [ParticleAbility Module](js-apis-particleAbility.md) + - [DataAbilityHelper Module](js-apis-dataAbilityHelper.md) + - [DataUriUtils Module](js-apis-DataUriUtils.md) + - [Context Module](js-apis-Context.md) +- Event Notification + - [CommonEvent Module](js-apis-commonEvent.md) + - [Notification Module](js-apis-notification.md) +- Resource Management + - [Resource Manager](js-apis-resource-manager.md) + - [Internationalization \(intl\) ](js-apis-intl.md) + - [Internationalization \(i18n\) ](js-apis-i18n.md) +- Media + - [Audio Management](js-apis-audio.md) + - [Media Playback and Recording](js-apis-media.md) +- Data Management + - [File Management](js-apis-fileio.md) + - [Lightweight Storage](js-apis-data-storage.md) + - [Distributed Data Management](js-apis-distributed-data.md) + - [Relational Database](js-apis-data-rdb.md) + - [Result Set](js-apis-data-resultset.md) + - [DataAbilityPredicates](js-apis-data-ability.md) +- Account Management + - [Distributed Account Management](js-apis-distributed-account.md) +- Telephony Service + - [Call](js-apis-call.md) + - [SMS](js-apis-sms.md) + - [SIM Management](js-apis-sim.md) + - [Radio](js-apis-radio.md) +- Network and Connectivity + - [WLAN](js-apis-wifi.md) +- Device Management + - [Sensors](js-apis-sensor.md) + - [Vibration](js-apis-vibrator.md) + - [Brightness](js-apis-brightness.md) + - [Battery Info](js-apis-battery-info.md) + - [Power Management](js-apis-power.md) + - [Running Lock](js-apis-runninglock.md) + - [Device Info](js-apis-device-info.md) + - [systemParameter](js-apis-system-parameter.md) + - [Device Management](js-apis-device-manager.md) + - [Window](js-apis-window.md) + - [Display](js-apis-display.md) + - [Update](js-apis-update.md) +- Basic Features + - [Application Context](js-apis-basic-features-app-context.md) + - [Console Logs](js-apis-basic-features-logs.md) + - [Page Routing](js-apis-basic-features-routes.md) + - [Pop-up Window](js-apis-basic-features-pop-up.md) + - [Application Configuration](js-apis-basic-features-configuration.md) + - [Timer](js-apis-basic-features-timer.md) + - [Setting the System Time](js-apis-system-time.md) + - [Animation](js-apis-basic-features-animator.md) + - [HiAppEvent](js-apis-hiappevent.md) + - [Performance Tracing](js-apis-bytrace.md) + - [Fault Logger](js-apis-faultLogger.md) +- Language Base Class Library + - [Obtaining Process Information](js-apis-process.md) + - [URL String Parsing](js-apis-url.md) + - [String Encoding and Decoding](js-apis-util.md) + - [Worker Startup](js-apis-worker.md) diff --git a/en/application-dev/reference/apis/apis.md b/en/application-dev/reference/apis/apis.md deleted file mode 100644 index c6e3221230b879b2f0dea7cffb27aa1b834914de..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/apis.md +++ /dev/null @@ -1,31 +0,0 @@ -# APIs - -- **[Console Logs](console-logs.md)** - -- **[HiAppEvent](hiappevent.md)** - -- **[Page Routing](page-routing.md)** - -- **[Pop-up Window](pop-up-window.md)** - -- **[Timer](timer.md)** - -- **[Audio Management](js-apis-audio.md)** - -- **[Audio Playback](audio-playback.md)** - -- **[Device Information](device-information.md)** - -- **[System Attribute](system-attribute.md)** - -- **[Battery and Charging](battery-and-charging.md)** - -- **[Screen Brightness](screen-brightness.md)** - -- **[Globalization](globalization.md)** - -- **[Resource Management](resource-management.md)** - -- **[Updater](updater.md)** - - diff --git a/en/application-dev/reference/apis/audio-playback.md b/en/application-dev/reference/apis/audio-playback.md deleted file mode 100644 index d15b3ff256a964a3cb1a70d901d2394012628b42..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/audio-playback.md +++ /dev/null @@ -1,452 +0,0 @@ -# Audio Playback - -## Modules to Import - -``` -import audio from '@ohos.multimedia.media'; -``` - -## Required Permissions - -None - -## Methods - -## createAudioPlayer\(\) - -Creates an **AudioPlayer** instance to control audio playback. - -**Return Values** - - - - - - - - - - -

Type

-

Description

-

AudioPlayer

-

Returns the AudioPlayer instance if the operation is successful; returns null otherwise.

-
- -**Example** - -``` -var audioplayer = audio.createAudioPlayer(); -``` - -## Appendixes - -## AudioPlayer - -Represents an audio player. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable

-

Writable

-

Description

-

src

-

string

-

Yes

-

Yes

-

URI of the audio resources

-

loop

-

boolean

-

Yes

-

Yes

-

Whether to loop audio playback

-

currentTime

-

number

-

Yes

-

No

-

Current playback position

-

duration

-

number

-

Yes

-

No

-

Playback duration

-

state

-

AudioState

-

Yes

-

No

-

Playback status

-
- -### play\(\) - -Starts audio playback. - -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.info('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -}; - -audioplayer.on('play', (err, action) => { - if (err) { - console.info('Error returned in the play() callback.'); - return; - } - console.info('Succeeded in playing the audio.'); -}; -audioplayer.src = 'common/mydream.mp3'; -``` - -### pause\(\) - -Pauses audio playback. - -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.info('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -} -audioplayer.on('play', (err, action) => { - if (err) { - console.info('Error returned in the play() callback.'); - return; - } - console.info('Start to pause audio playback.'); - audioplayer.pause(); -}; -audioplayer.on('pause', (err, action) => { - if (err) { - console.info('Error returned in the pause() callback.'); - return; - } - console.info('Succeeded in pausing audio playback.'); -}; -audioplayer.src = 'common/mydream.mp3'; -``` - -### stop\(\) - -Stops audio playback. - -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.info('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -}; -audioplayer.on('play', (err, action) => { - if (err) { - console.info('Error returned in the play() callback.'); - return; - } - console.info('Start to pause audio playback.'); - audioplayer.pause(); -}; -audioplayer.on('stop', (err, action) => { - if (err) { - console.info('Error returned in the stop() callback.'); - return; - } - console.info('Succeeded in stopping audio playback.'); -}; -audioplayer.src = 'common/mydream.mp3'; -``` - -### seek\(number\) - -Goes to a specified playback position. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

timeMs

-

number

-

Yes

-

Target playback position

-
- -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.info('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -}; -audioplayer.on('play', (err, action) => { - if (err) { - console.info('Error returned in the play() callback.'); - return; - } - console.info('Succeeded in playing the audio.') -}; -audioplayer.on('timeUpdate', (seekTime, action) => { - console.info('Seek time returned in the seek() callback: ' + seekTime); - var newTime = audioplayer.currenTime; - if(newTime == 30000) { - console.info('Seek succeeded. New time: ' + newTime); - } else { - console.info('Seek failed.'); - } -}; -audioplayer.src = 'common/mydream.mp3'; -audioplayer.seek(30000); -``` - -### setVolume\(number\) - -Sets the volume. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

vol

-

number

-

Yes

-

Volume to set. The value ranges from 0 to 1.

-
- -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.error('Error returned in the prepare() callback.'); - return; - } - console.info('Start to play the audio.'); - audioplayer.play(); -}; -audioplayer.on('play', (err, action) => { - if (err) { - console.error('Error returned in the play() callback.'); - return; - } - console.info('Succeeded in playing the audio.') -}; -audioplayer.on('volumeChange', (err, action) => { - if (err) { - console.error('Error returned in the setVolume() callback.'); - return; - } - console.info('Playback volume changed.'); -}; -audioplayer.src = 'common/mydream.mp3'; -audioplayer.setVolume(0.5); -``` - -### reset\(\)7+ - -Switches the audio resource to be played. - -**Example** - -``` -audioplayer.on('dataload', (err, action) => { - if (err) { - console.error('Error returned in the prepare() callback.'); - return; - } - console.info('Start to reset audio playback.'); - audioplayer.reset(); -}; -audioplayer.on('reset', (err, action) => { - if (err) { - console.error('Error returned in the reset() callback.'); - return; - } - console.info('Reset succeeded.'); -}; -audioplayer.src = 'common/mydream.mp3'; -``` - -### release\(\) - -Releases audio resources. - -**Example** - -``` -audioplay.release(); -``` - -### Events - -### play - -Triggered when **play\(\)** is called - -### pause - -Triggered when **pause\(\)** is called - -### stop - -Triggered when **stop\(\)** is called - -### dataLoad - -Triggered when audio data is loaded - -### timeUpdate - -Triggered when the playback position changes - -### volumeChange - -Triggered when playback volume changes - -### finish - -Triggered when playback is finished - -### error - -Triggered when a playback error occurs - - - - - - - - - - - - -

Name

-

Type

-

Description

-

callback

-

ErrorCallback

-

Callback function for handling this event

-
- -## AudioState - -Describes playback status. - - - - - - - - - - - - - - - - - - - -

Name

-

Description

-

idle

-

Audio playback is idle.

-

playing

-

The audio is being played.

-

paused

-

Audio playback is paused.

-

stopped

-

Audio playback is stopped.

-
- diff --git a/en/application-dev/reference/apis/battery-and-charging.md b/en/application-dev/reference/apis/battery-and-charging.md deleted file mode 100644 index 4b19c60bfbec66451ad1f72489c5536f59b489c4..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/battery-and-charging.md +++ /dev/null @@ -1,245 +0,0 @@ -# Battery and Charging - -## Modules to Import - -``` -import batteryInfo from '@ohos.batteryinfo.d.ts' -``` - -## BatteryInfo - -Describes battery information. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Readable/Writable

-

Type

-

Description

-

batterySOC

-

Read-only

-

number

-

Battery state of charge (SoC) of the current device

-

chargingStatus

-

Read-only

-

BatteryChargeState

-

Battery charging status of the current device

-

healthStatus

-

Read-only

-

BatteryHealthState

-

Battery health state of the current device

-

pluggedType

-

Read-only

-

BatteryPluggedType

-

Charger type of the current device

-

voltage

-

Read-only

-

number

-

Battery voltage of the current device

-

technology

-

Read-only

-

string

-

Battery technology of the current device

-

batteryTemperature

-

Read-only

-

number

-

Battery temperature of the current device

-
- -- Example - - ``` - import batteryInfo from '@ohos.batteryInfo'; - var batterySoc = batteryInfo.batterySOC; - ``` - - -## Enums - -## BatteryPluggedType - -Enumerates charger types. - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

NONE

-

0

-

Unknown type

-

AC

-

1

-

AC charger

-

USB

-

2

-

USB charger

-

WIRELESS

-

3

-

Wireless charger

-
- -## BatteryChargeState - -Enumerates battery charging states. - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

NONE

-

0

-

Unknown state

-

ENABLE

-

1

-

The battery is being charged.

-

DISABLE

-

2

-

The battery is not being charged.

-

FULL

-

3

-

The battery is fully charged.

-
- -## BatteryHealthState - -Enumerates battery health states. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

UNKNOWN

-

0

-

Unknown state

-

GOOD

-

1

-

The battery is in healthy state.

-

OVERHEAT

-

2

-

The battery is overheated.

-

OVERVOLTAGE

-

3

-

The battery voltage is over high.

-

COLD

-

4

-

The battery temperature is low.

-

DEAD

-

5

-

The battery is dead.

-
- diff --git a/en/application-dev/reference/apis/console-logs.md b/en/application-dev/reference/apis/console-logs.md deleted file mode 100644 index a8d9e8f9bf571e773805586225469f0596eb0599..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/console-logs.md +++ /dev/null @@ -1,54 +0,0 @@ -# Console Logs - -## Module to Import - -No module is required. - -## Permission List - -None - -## Log Category - -Prints a log using **console.debug|log|info|warn|error\(message\)**. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to print

-
- -- Example - - ``` - var versionCode = 1; - console.info('Hello World. The current version code is ' + versionCode); - ``` - - Switch to the **HiLog** window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to **Info**, and enter **Hello World** in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. - - ![](figures/log.png) - - > **NOTE:** - >The **console.log\(\)** function prints logs at the debug level. - - diff --git a/en/application-dev/reference/apis/device-information.md b/en/application-dev/reference/apis/device-information.md deleted file mode 100644 index fde4e698c126ab45f86a5e7313cbec6a941295a0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/device-information.md +++ /dev/null @@ -1,350 +0,0 @@ -# Device Information - -## Modules to Import - -``` -import deviceinfo from '@ohos.deviceinfo' -``` - -## Required Permissions - -None - -## Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable

-

Writable

-

Description

-

deviceType

-

string

-

Yes

-

No

-

Device type

-

manufacture

-

string

-

Yes

-

No

-

Device manufacturer

-

brand

-

string

-

Yes

-

No

-

Device brand

-

marketName

-

string

-

Yes

-

No

-

External product series

-

productSeries

-

string

-

Yes

-

No

-

Product series

-

productModel

-

string

-

Yes

-

No

-

Product model

-

softwareModel

-

string

-

Yes

-

No

-

Software model

-

hardwareModel

-

string

-

Yes

-

No

-

Hardware model

-

hardwareProfile

-

string

-

Yes

-

No

-

Hardware profile

-

serial

-

string

-

Yes

-

No

-

Device serial number

-

bootloaderVersion

-

string

-

Yes

-

No

-

Bootloader version

-

abiList

-

string

-

Yes

-

No

-

Application binary interface (Abi) list

-

securityPatchTag

-

string

-

Yes

-

No

-

Security patch tag

-

displayVersion

-

string

-

Yes

-

No

-

Product version

-

incrementalVersion

-

string

-

Yes

-

No

-

Incremental version

-

osReleaseType

-

string

-

Yes

-

No

-

Release type. The options are as follows:

-
  • Canary: Preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
  • Beta: Release open to all developers. This release does not promise API stability and may require tolerance of instability.
  • Release: Official release open to all developers. This release promises that all APIs are stable.
-

osFullName

-

string

-

Yes

-

No

-

OS version

-

majorVersion

-

number

-

Yes

-

No

-

Major version, incrementing along with OS version updates

-

seniorVersion

-

number

-

Yes

-

No

-

Senior version, incrementing along with architecture and feature updates

-

featureVersion

-

number

-

Yes

-

No

-

Feature version

-

buildVersion

-

number

-

Yes

-

No

-

Build version

-

sdkApiVersion

-

number

-

Yes

-

No

-

SDK API version

-

firstApiVersion

-

number

-

Yes

-

No

-

First API version

-

versionId

-

string

-

Yes

-

No

-

Version ID

-

buildType

-

string

-

Yes

-

No

-

Build type

-

buildUser

-

string

-

Yes

-

No

-

Build user

-

buildHost

-

string

-

Yes

-

No

-

Build host

-

buildTime

-

string

-

Yes

-

No

-

Build time

-

buildRootHash

-

string

-

Yes

-

No

-

Build root hash

-
- diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png b/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png new file mode 100644 index 0000000000000000000000000000000000000000..2128f0852380b2895198ab725a2f9d299c480d84 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001164217678.png differ diff --git a/en/application-dev/reference/apis/figures/icon-note.gif b/en/application-dev/reference/apis/figures/icon-note.gif new file mode 100644 index 0000000000000000000000000000000000000000..6314297e45c1de184204098efd4814d6dc8b1cda Binary files /dev/null and b/en/application-dev/reference/apis/figures/icon-note.gif differ diff --git a/en/application-dev/reference/apis/globalization.md b/en/application-dev/reference/apis/globalization.md deleted file mode 100644 index e6640de0bc9868462efd74dee803a2c7783b3ba3..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/globalization.md +++ /dev/null @@ -1,211 +0,0 @@ -# Globalization - - -## Imported Modules - -``` -import Intl from '@ohos.intl'; -``` - -## Permissions - -None. - -## Class - -## Locale - -Provides APIs for obtaining locale information. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Readable

-

Writable

-

Description

-

language

-

string

-

Yes

-

No

-

Indicates the language of the locale.

-

script

-

string

-

Yes

-

No

-

Indicates the script of the locale.

-

region

-

string

-

Yes

-

No

-

Indicates the region of the locale.

-

baseName

-

string

-

Yes

-

No

-

Indicates the basic locale information, which is returned as a substring of a complete locale string.

-
- -### Locale - -A constructor used to create a **Locale** object. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

locale

-

string

-

Yes

-

Indicates a character string containing the locale information, including the language and optionally the script and region.

-
- -**Example** - -``` -var enLatnGB = new Intl.Locale("en-Latn-GB"); -var enGB = new Intl.Locale("en-GB"); -var en = new Intl.Locale("en"); -``` - -## DateTimeFormat - -Provides the API for formatting date strings. - -### DateTimeFormat - -A constructor used to create a **DateTimeFormat** object. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

locale

-

string

-

Yes

-

Indicates a character string containing the locale information, including the language and optionally the script and region, for the DateTimeFormat object.

-
- -**Example** - -``` -var dateFmt = new Intl.DateTimeFormat("en-Latn-GB"); -``` - -### format - -Obtains the formatted date strings. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

date

-

Date

-

Yes

-

Indicates the Date object to be formatted.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

string

-

Indicates a date string formatted based on the specified locale.

-
- -**Example** - -``` -var date = new Date(1995, 11, 25, 3, 14, 0); -var datefmt = new Intl.DateTimeFormat("en-Latn-GB"); -var result = datefmt.format(date); // The formatted date string is Dec 25, 1995. -``` - diff --git a/en/application-dev/reference/apis/hiappevent.md b/en/application-dev/reference/apis/hiappevent.md deleted file mode 100644 index b762c810169941d54186ee5daef78652d2d7ddd0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/hiappevent.md +++ /dev/null @@ -1,358 +0,0 @@ -# HiAppEvent - -## Modules to Import - -``` -import hiappevent from '@ohos.hiappevent'; -``` - -## Required Permissions - -None. - -## Functions - -## write\(string, EventType, any..., AsyncCallback\) - -Writes event information to the event file of the current day. This function supports variable parameters and uses an asynchronous callback to return the result. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

eventName

-

string

-

Yes

-

Indicates the app event name.

-

eventType

-

EventType

-

Yes

-

Indicates the app event type.

-

params

-

any...

-

No

-

Indicates an array of parameters of the app event. Enter the name and value of each parameter in sequence. A parameter name must be a string, and a parameter value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

-

callback

-

AsyncCallback<number>

-

No

-

Indicates the callback function, which can be used to process the received return value.

-
  • Value 0 indicates that the event parameter verification is successful, and the event will be written to the event file asynchronously.
  • A value greater than 0 indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
  • A value less than 0 indicates that the event parameter verification fails, and the event will not be written to the event file asynchronously.
-
- -**Example** - -``` -hiappevent.write("testEvent", hiappevent.EventType.FAULT, "intData", 100, "strData", "strValue", (err, value) => { - if (err) { - // Event writing failed: The event contains invalid parameters or the event parameter verification fails. - console.error(`failed to write event because ${err}`); - return; - } - - // Event writing succeeded. - console.log(`success to write event: ${value}`); -}); -``` - -## write\(string, EventType, any...\) - -Writes event information to the event file of the current day. This function supports variable parameters and uses an asynchronous promise to return the result. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

eventName

-

string

-

Yes

-

Indicates the app event name.

-

eventType

-

EventType

-

Yes

-

Indicates the app event type.

-

params

-

any...

-

No

-

Indicates an array of parameters of the app event. Enter the name and value of each parameter in sequence. A parameter name must be a string, and a parameter value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<void>

-

Indicates the promise used to return the execution result.

-
- -**Example** - -``` -hiappevent.write("testEvent", hiappevent.EventType.FAULT, "intData", 100, "strData", "strValue") - .then((value) => { - // Event writing succeeded. - console.log(`success to write event: ${value}`); - }).catch((err) => { - // Event writing failed: The event contains invalid parameters or the event parameter verification fails. - console.error(`failed to write event because ${err}`); - }); -``` - -## writeJson\(string, EventType, object, AsyncCallback\) - -Writes event information to the event file of the current day. This function supports JSON parameters and uses an asynchronous callback to return the result. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

eventName

-

string

-

Yes

-

Indicates the app event name.

-

eventType

-

EventType

-

Yes

-

Indicates the app event type.

-

jsonParam

-

object

-

Yes

-

Indicates an array of JSON parameters of the app event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

-

callback

-

AsyncCallback<number>

-

No

-

Indicates the callback function, which can be used to process the received return value.

-
  • Value 0 indicates that the event parameter verification is successful, and the event will be written to the event file asynchronously.
  • A value greater than 0 indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
  • A value less than 0 indicates that the event parameter verification fails, and the event will not be written to the event file asynchronously.
-
- -**Example** - -``` -hiappevent.writeJson("testEvent", hiappevent.EventType.FAULT, {"intData":100, "strData":"strValue"}, (err, value) => { - if (err) { - // Event writing failed: The event contains invalid parameters or the event parameter verification fails. - console.error(`failed to write event because ${err}`); - return; - } - - // Event writing succeeded. - console.log(`success to write event: ${value}`); -}); -``` - -## writeJson\(string, EventType, object\) - -Writes event information to the event file of the current day. This function supports JSON parameters and uses an asynchronous promise to return the result. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

eventName

-

string

-

Yes

-

Indicates the app event name.

-

eventType

-

EventType

-

Yes

-

Indicates the app event type.

-

jsonParam

-

object

-

Yes

-

Indicates an array of JSON parameters of the app event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<void>

-

Indicates the promise used to return the execution result.

-
- -**Example** - -``` -hiappevent.writeJson("testEvent", hiappevent.EventType.FAULT, {"intData":100, "strData":"strValue"}) - .then((value) => { - // Event writing succeeded. - console.log(`success to write event: ${value}`); - }).catch((err) => { - // Event writing failed: The event contains invalid parameters or the event parameter verification fails. - console.error(`failed to write event because ${err}`); - }); -``` - -## Enums - -## EventType - -Enumerates event types. - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

FAULT

-

1

-

Fault event

-

STATISTIC

-

2

-

Statistical event

-

SECURITY

-

3

-

Security event

-

BEHAVIOR

-

4

-

System behavior event

-
- diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md new file mode 100644 index 0000000000000000000000000000000000000000..e2b51f2e3cdf0468fe08a8913d4630b80c28269a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -0,0 +1,559 @@ +# Context Module + +## Applicable Devices + +| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device| +| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ | +| Context.getOrCreateLocalDir(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.getOrCreateLocalDir() | Yes| Yes| Yes| Yes| No| No| +| Context.verifyPermission(permission: string, options: PermissionOptions, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.verifyPermission(permission: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.verifyPermission(permission: string, options?: PermissionOptions) | Yes| Yes| Yes| Yes| No| No| +| Context.requestPermissionsFromUser(permissions: Array\, requestCode: number, resultCallback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.getApplicationInfo(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.getApplicationInfo() | Yes| Yes| Yes| Yes| No| No| +| Context.getBundleName(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.getBundleName() | Yes| Yes| Yes| Yes| No| No| +| Context.getProcessInfo(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.getProcessInfo() | Yes| Yes| Yes| Yes| No| No| +| Context.getElementName(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.getElementName() | Yes| Yes| Yes| Yes| No| No| +| Context.getProcessName(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.getProcessName() | Yes| Yes| Yes| Yes| No| No| +| Context.getCallingBundle(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| Context.getCallingBundle() | Yes| Yes| Yes| Yes| No| No| + +## Modules to Import + +```js +import featureAbility from '@ohos.ability.featureAbility' +import bundle from '@ohos.bundle' +``` + +The **Context** object is created in a **featureAbility** and returned through its **getContext()** method. Therefore, you must import the **@ohos.ability.featureAbility** package before using the Context module. An example is as follows: + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getOrCreateLocalDir() +``` + +## Context.getOrCreateLocalDir(callback: AsyncCallback) + +- Functionality + + Obtains the local root directory of the application. If this method is called for the first time, a root directory is created. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ---------------------- | ---- | ------------------------ | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the local root directory of the application.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getOrCreateLocalDir((err, data)=>{ + console.info("data=" + data); +}) +``` + + + +## Context.getOrCreateLocalDir() + +- Functionality + + Obtains the local root directory of the application. If this method is called for the first time, a root directory is created. This method uses a promise to return the result. + +- Parameters + + None + +- Return values + + | Type| Description| + | --------------- | -------------------- | + | Promise | Promise used to return the local root directory of the application.| + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getOrCreateLocalDir().then((void) => { + console.info("==========================>getOrCreateLocalDirCallback=======================>"); +}); +``` + +## PermissionOptions + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---- | -------- | ------ | ---- | ------ | +| pid | Read-only| number | No| PID.| +| uid | Read-only| number | No| UID.| + +## Context.verifyPermission(permission: string, options: PermissionOptions, callback: AsyncCallback) + +- Functionality + + Verifies whether a specific PID and UID have the given permission. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ----------------------------------------------- | ---- | ----------------------------------- | +| permission | Read-only| string | Yes| Name of the permission to verify.| +| options | Read-only| [PermissionOptions](#PermissionOptions)| Yes| Permission options.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +import bundle from '@ohos.bundle' +var context = featureAbility.getContext(); +var datainfo = await bundle.getBundleInfo('com.context.test',1); +context.verifyPermission("com.example.permission",datainfo.uid) + +``` + + + +## Context.verifyPermission(permission: string, callback: AsyncCallback) + +- Functionality + + Verifies whether the current PID and UID have the given permission. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ---------------------- | ---- | ----------------------------------- | +| permission | Read-only| string | Yes| Name of the permission to verify.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.verifyPermission("com.example.permission") +``` + + + +## Context.verifyPermission(permission: string, options?: PermissionOptions) + +- Functionality + + Verifies whether a specific PID and UID have the given permission. This method uses a promise to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ----------------------------------------------- | ---- | -------------- | +| permission | Read-only| string | Yes| Name of the permission to verify.| +| options | Read-only| [PermissionOptions](#PermissionOptions)| No| Permission options.| + +- Return values + + | Type| Description| + | --------------- | ------------------------------------------------------------ | + | Promise | Promise used to return the permission verification result. The value **0** indicates that the PID and UID have the given permission, and the value **-1** indicates that the PID and UID do not have the given permission.| + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +var Permission = context.PermissionOptions(1,1); +context.getOrCreateLocalDir('com.context.permission',Permission).then((void) => { + console.info("==========================>verifyPermissionCallback=======================>"); +}); +``` + +## PermissionRequestResult + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----------- | -------- | -------------- | ---- | ------------------ | +| requestCode | Read-only| number | Yes| Request code passed.| +| permissions | Read-only| Array\ | Yes| Permissions passed.| +| authResults | Read-only| Array\ | Yes| Permission request result.| + + + +## Context.requestPermissionsFromUser(permissions: Array, requestCode: number, resultCallback: AsyncCallback<[PermissionRequestResult](#PermissionRequestResult)>) + +- Functionality + + Requests certain permissions from the system. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------- | -------- | ------------------------------------------------------------ | ---- | --------------------------------------------- | +| permissions | Read-only| Array\ | Yes| Permissions to request. This parameter cannot be **null**.| +| requestCode | Read-only| number | Yes| Request code to be passed to **PermissionRequestResult**.| +| resultCallback | Read-only| AsyncCallback\<[PermissionRequestResult](#PermissionRequestResult)> | Yes| Permission request result.| +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getOrCreateLocalDir( + ["com.example.permission1", + "com.example.permission2", + "com.example.permission3", + "com.example.permission4", + "com.example.permission5"], + 1, +) +``` + + + +## Context.getApplicationInfo(callback: AsyncCallback) + +- Functionality + + Obtains information about the current application. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | ------------------------------- | ---- | ---------------------- | + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the application information.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getApplicationInfo() +``` + + + +## Context.getApplicationInfo + +- Functionality + + Obtains information about the current application. This method uses a promise to return the result. + +- Parameters + + None + +- Return values + + | Type| Description| + | ------------------------ | ------------------ | + | Promise | Promise used to return the application information.| + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getApplicationInfo().then((void) => { + console.info("==========================>getApplicationInfoCallback=======================>"); +}); +``` + + + +## Context.getBundleName(callback: AsyncCallback) + +- Functionality + + Obtains the bundle name of the current ability. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | ---------------------- | ---- | --------------------------- | + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the bundle name.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getBundleName() +``` + + + +## Context.getBundleName + +- Functionality + + Obtains the bundle name of the current ability. This method uses a promise to return the result. + +- Parameters + + None + +- Return values + + | Type| Description| + | --------------- | ----------------------- | + | Promise | Promise used to return the bundle name.| + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getBundleName().then((void) => { + console.info("==========================>getBundleNameCallback=======================>"); +}); +``` + + + +## Context.getProcessInfo(callback: AsyncCallback) + +- Functionality + + Obtains information about the current process, including the PID and process name. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | --------------------------- | ---- | ------------------ | + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the process information.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getProcessInfo() +``` + + + +## Context.getProcessInfo + +- Functionality + + Obtains information about the current process, including the PID and process name. This method uses a promise to return the result. + +- Parameters + + None + +- Return values + + | Type| Description| + | -------------------- | -------------- | + | Promise | Promise used to return the process information.| + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getProcessInfo().then((void) => { + console.info("==========================>getProcessInfoCallback=======================>"); +}); +``` + + + +## Context.getElementName(callback: AsyncCallback) + +- Functionality + + Obtains the **ohos.bundle.ElementName** object of the current ability. This method is available only to Page abilities. It uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | --------------------------- | ---- | -------------------------------------------- | + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the **ohos.bundle.ElementName** object.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getElementName() +``` + + + +## Context.getElementName + +- Functionality + + Obtains the **ohos.bundle.ElementName** object of the current ability. This method is available only to Page abilities. It uses a promise to return the result. + +- Parameters + + None + +- Return values + + | Type| Description| + | -------------------- | ---------------------------------------- | + | Promise | Promise used to return the **ohos.bundle.ElementName** object.| + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getElementName().then((void) => { + console.info("==========================>getElementNameCallback=======================>"); +}); +``` + +## **Context.getProcessName(callback: AsyncCallback)** + +- Functionality + + Obtains the name of the current process. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | ---------------------- | ---- | ------------------ | + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the process name.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getProcessName() +``` + + + +## Context.getProcessName + +- Functionality + + Obtains the name of the current process. This method uses a promise to return the result. + +- Parameters + + None + +- Return values + + | Type| Description| + | --------------- | -------------- | + | Promise | Promise used to return the process name.| + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getProcessName().then((void) => { + console.info("==========================>getProcessNameCallback=======================>"); +}); +``` + + + +## Context.getCallingBundle(callback: AsyncCallback) + +- Functionality + + Obtains the bundle name of the calling ability. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | ---------------------- | ---- | ------------------------- | + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the bundle name.| + +- Return values + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getCallingBundle() +``` + + + +## Context.getCallingBundle + +- Functionality + + Obtains the bundle name of the calling ability. This method uses a promise to return the result. + +- Parameters + + None + +- Return values + + | Type| Description| + | --------------- | ------------------------- | + | Promise | Promise used to return the bundle name.| + + + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var context = featureAbility.getContext(); +context.getCallingBundle().then((void) => { + console.info("==========================>getCallingBundleCallback=======================>"); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-DataUriUtils.md b/en/application-dev/reference/apis/js-apis-DataUriUtils.md new file mode 100644 index 0000000000000000000000000000000000000000..494c24532eb52af4ce7dff0083d8b5617034b507 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-DataUriUtils.md @@ -0,0 +1,117 @@ +# DataUriUtils Module + +## Modules to Import + +```js +import dataUriUtils from '@ohos.ability.dataUriUtils'; +``` + +## DataUriUtils.getId + +- Functionality + + Obtains the ID attached to the end of a given URI. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---- | -------- | ------ | ---- | ------------------------- | +| uri | Read-only| string | Yes| URI object from which the ID is to be obtained.| + +- Return values + + Returns the ID obtained from the URI object. + +- Example + +```js +import dataUriUtils from '@ohos.ability.datauriutils' +dataUriUtils.getIdSync("com.example.dataUriUtils/1221") +``` + + + +## DataUriUtils.attachId + +- Functionality + + Attaches an ID to the end of a given URI. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---- | -------- | ------ | ---- | ------------------------- | +| uri | Read-only| string | Yes| URI object to which an ID is to be attached.| +| id | Read-only| number | Yes| ID to be attached.| + +- Return values + + Returns the URI object with the ID attached. + +- Example + +```js +import dataUriUtils from '@ohos.ability.datauriutils' +var idint = 1122; +dataUriUtils.attachId( + "com.example.dataUriUtils" + idint, +) +``` + + + +## DataUriUtils.deleteId + +- Functionality + + Deletes the ID from the end of a given URI. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---- | -------- | ------ | ---- | ------------------------- | + | uri | Read-only| string | Yes| URI object from which the ID is to be deleted.| + +- Return values + + Returns the URI object with the ID deleted. + +- Example + +```js +import dataUriUtils from '@ohos.ability.datauriutils' +dataUriUtils.deleteId("com.example.dataUriUtils/1221") +``` + + + +## DataUriUtils.updateId + +- Functionality + + Updates the ID in a given URI. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---- | -------- | ------ | ---- | ------------------- | + | uri | Read-only| string | Yes| URI object to be updated.| + | id | Read-only| number | Yes| New ID.| + +- Return values + + Returns the URI object with the new ID. + +- Example + +```js +import dataUriUtils from '@ohos.ability.datauriutils' +var idint = 1122; +dataUriUtils.updateId( + "com.example.dataUriUtils" + idint, +) +``` diff --git a/en/application-dev/reference/apis/js-apis-account.md b/en/application-dev/reference/apis/js-apis-account.md new file mode 100644 index 0000000000000000000000000000000000000000..c9544210fb8c7bc53f5a7a39c03615bcca623341 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-account.md @@ -0,0 +1,4 @@ +# Account Management + +- **[Distributed Account Management](js-apis-distributed-account.md)** +- **[Application Account Management](js-apis-appAccount.md)** diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md new file mode 100644 index 0000000000000000000000000000000000000000..bb60e379f614a18c90ce42bb596a1cc0da36260e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -0,0 +1,882 @@ +# Application Account Management + +> ![icon-note.gif](figures/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import account_appAccount from '@ohos.account.appAccount'; +``` + + +## account_appAccount.createAppAccountManager + +createAppAccountManager(): AppAccountManager; + +Creates an **AppAccountManager** instance. + +- Return value + | Type| Description| + | -------- | -------- | + | AppAccountManager | **AppAccountManager** instance created.| + +- Example + ``` + var appAccountManager = account.createAppAccountManager(); + ``` + +## AppAccountManager + +Provides methods to manage application accounts. + +### addAccount + +addAccount(name: string, callback: AsyncCallback<void>): void; + +Adds an application account to the account management service. This method uses an asynchronous callback to return the result. + +Required permission: none. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ------------------- | ---- | ------------------------------------------ | + | name | string | Yes| Name of the application account to add.| + | callback | AsyncCallback<void> | Yes| Callback invoked when the application account is added.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("WangWu", (err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + +### addAccount + +addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void; + +Adds an application account and its additional information to the account management service. This method uses an asynchronous callback to return the result. + +Required permission: none. + +- Parameters + + | Name| Type| Mandatory| Description| + | --------- | ------------------- | ---- | ------------------------------------------------------------ | + | name | string | Yes| Name of the application account to add.| + | extraInfo | string | Yes| Additional information (for example, token) of the application account to add. The additional information cannot contain sensitive information about the application account.| + | callback | AsyncCallback<void> | Yes| Callback invoked when the application account and its additional information are added.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("LiSi", "token101", (err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + + + +### addAccount + +addAccount(name: string, extraInfo?: string): Promise<void>; + +Adds an application account and its additional information to the account management service. This method uses a promise to return the result asynchronously. + +Required permission: none. + +- Parameters + + | Name| Type| Mandatory| Description| + | --------- | ------ | ---- | ------------------------------------------------------------ | + | name | string | Yes| Name of the application account to add.| + | extraInfo | string | Yes| Additional information of the application account to add. The additional information cannot contain sensitive information about the application account.| + +- Return value + + | Type| Description| + | ------------- | ---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("LiSi", "token101").then(()=> { + console.log('addAccount Success'); + }).catch((err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + +### deleteAccount + +deleteAccount(name: string, callback: AsyncCallback<void>): void; + +Deletes an application account from the account management service. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ------------------- | ---- | ---------------------------------- | + | name | string | Yes| Name of the application account to delete.| + | callback | AsyncCallback<void> | Yes| Callback invoked when the application account is deleted.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteAccount("ZhaoLiu", (err) => { + console.log("deleteAccount err: " + JSON.stringify(err)); + }); + ``` + +### deleteAccount + +deleteAccount(name: string): Promise<void>; + +Deletes an application account from the account management service. This method uses a promise to return the result asynchronously. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | ------------------------ | + | name | string | Yes| Name of the application account to delete.| + +- Return value + + | Type| Description| + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteAccount("ZhaoLiu").then(() => { + console.log('deleteAccount Success'); + }).catch((err) => { + console.log("deleteAccount err: " + JSON.stringify(err)); + }); + ``` + +### disableAppAccess + +disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void; + +Disables the specified third-party application account from accessing the third-party application with the given bundle name. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | ---------- | ------------------- | ---- | ------------------------------------------------------------ | + | name | string | Yes| Name of the third-party application account.| + | bundleName | string | Yes| Bundle name of the third-party application.| + | callback | AsyncCallback<void> | Yes| Callback invoked when the third-party application account is disabled from accessing the third-party application with the given bundle name.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.disableAppAccess("ZhangSan", "com.huawei.ohos.accountjsdemo", (err) => { + console.log("disableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### disableAppAccess + +disableAppAccess(name: string, bundleName: string): Promise<void>; + +Disables the specified third-party application account from accessing the third-party application with the given bundle name. This method uses a promise to return the result asynchronously. + +- Parameters + + | Name| Type| Mandatory| Description| + | ---------- | ------ | ---- | ---------------------------------- | + | name | string | Yes| Name of the third-party application account.| + | bundleName | string | Yes| Bundle name of a third-party application.| + +- Return value + + | Type| Description| + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.disableAppAccess("ZhangSan", "com.huawei.ohos.accountjsdemo").then(() => { + console.log('disableAppAccess Success'); + }).catch((err) => { + console.log("disableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### enableAppAccess + +enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void; + +Enables the specified third-party application account to access the third-party application with the given bundle name. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | ---------- | ------------------- | ---- | ------------------------------------------------------------ | + | name | string | Yes| Application account name.| + | bundleName | string | Yes| Bundle name of the third-party application.| + | callback | AsyncCallback<void> | Yes| Callback invoked when the third-party application account is enabled to access the third-party application with the given bundle name.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.huawei.ohos.accountjsdemo", (err) => { + console.log("enableAppAccess: " + JSON.stringify(err)); + }); + ``` + +### enableAppAccess + +enableAppAccess(name: string, bundleName: string): Promise<void>; + +Enables the specified third-party application account to access the third-party application with the given bundle name. This method uses a promise to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | ---------- | ------ | ---- | ------------------ | + | name | string | Yes| Application account name.| + | bundleName | string | Yes| Bundle name of the third-party application.| + +- Return value + + | Type| Description| + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + app_account_instance.enableAppAccess("ZhangSan", "com.huawei.ohos.accountjsdemo").then(() => { + console.log('enableAppAccess Success'); + }).catch((err) => { + console.log("enableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### checkAppAccountSyncEnable + +checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void; + +Checks whether the specified application account allows application data synchronization. This method uses an asynchronous callback to return the result. + +The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required. This permission is intended for system applications only. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ---------------------- | ---- | -------------------------------------------- | + | name | string | Yes| Application account name.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked to specify whether the application account allows application data synchronization.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { + console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + console.log('checkAppAccountSyncEnable result: ' + result); + }); + ``` + +### checkAppAccountSyncEnable + +checkAppAccountSyncEnable(name: string): Promise<boolean>; + +Checks whether the specified application account allows application data synchronization. This method uses a promise to return the result asynchronously. + +The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required. This permission is intended for system applications only. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | -------------- | + | name | string | Yes| Application account name.| + +- Return value + + | Type| Description| + | :--------------- | :---------------------------------- | + | Promise<boolean> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { + console.log('checkAppAccountSyncEnable, result: ' + data); + }).catch((err) => { + console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAccountCredential + +setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void; + +Sets a credential for an application account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------------- | ------------------- | ---- | ---------------------------- | + | name | string | Yes| Application account name.| + | credentialType | string | Yes| Type of the credential to set.| + | credential | string | Yes| Credential to set.| + | callback | AsyncCallback<void> | Yes| Callback invoked when a credential is set for the specified application account.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { + console.log("setAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### setAccountCredential + +setAccountCredential(name: string, credentialType: string, credential: string): Promise<void>; + +Sets a credential for an application account. This method uses a promise to return the result asynchronously. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------------- | ------ | ---- | -------------------- | + | name | string | Yes| Application account name.| + | credentialType | string | Yes| Type of the credential to set.| + | credential | string | Yes| Credential to set.| + +- Return value + + | Type| Description| + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { + console.log('setAccountCredential Success'); + }).catch((err) => { + console.log("setAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### setAccountExtraInfo + +setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void; + +Sets additional information for an application account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | --------- | ------------------- | ---- | -------------------------------- | + | name | string | Yes| Application account name.| + | extraInfo | string | Yes| Additional information to set.| + | callback | AsyncCallback<void> | Yes| Callback invoked when additional information is set for the specified application account.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { + console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### setAccountExtraInfo + +setAccountExtraInfo(name: string, extraInfo: string): Promise<void>; + +Sets additional information for an application account. This method uses a promise to return the result asynchronously. + +- Parameters + + | Name| Type| Mandatory| Description| + | --------- | ------ | ---- | ------------------ | + | name | string | Yes| Application account name.| + | extraInfo | string | Yes| Additional information to set.| + +- Return value + + | Type| Description| + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { + console.log('setAccountExtraInfo Success'); + }).catch((err) => { + console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### setAppAccountSyncEnable + +setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void; + +Sets whether to enable application data synchronization for an application account. This method uses an asynchronous callback to return the result. + +The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required. This permission is intended for system applications only. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ------------------- | ---- | -------------------------------------------------- | + | name | string | Yes| Application account name.| + | isEnable | boolean | Yes| Specifies whether to enable application data synchronization.| + | callback | AsyncCallback<void> | Yes| Callback invoked when application data synchronization is enabled or disabled for the application account.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { + console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAppAccountSyncEnable + +setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void>; + +Sets whether to enable application data synchronization for an application account. This method uses a promise to return the result asynchronously. + +The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required. This permission is intended for system applications only. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ------- | ---- | ---------------------- | + | name | string | Yes| Application account name.| + | isEnable | boolean | Yes| Specifies whether to enable application data synchronization.| + +- Return value + + | Type| Description| + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { + console.log('setAppAccountSyncEnable Success'); + }).catch((err) => { + console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAssociatedData + +setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void; + +Sets data to be associated with an application account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ------------------- | ---- | ---------------------------------- | + | name | string | Yes| Application account name.| + | key | string | Yes| Key of the data to set. The private key can be customized.| + | value | string | Yes| Value of the data to be set.| + | callback | AsyncCallback<void> | Yes| Callback invoked when the data associated with the specified application account is set.| + +- Example + + ``` + app_account_instance.setAssociatedData("ZhangSan", "k001", "v001", (err) => { + console.log("setAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### setAssociatedData + +setAssociatedData(name: string, key: string, value: string): Promise<void>; + +Sets data to be associated with an application account. This method uses a promise to return the result asynchronously. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | ---------------------------------- | + | name | string | Yes| Application account name.| + | key | string | Yes| Key of the data to set. The private key can be customized.| + | value | string | Yes| Value of the data to be set.| + +- Return value + + | Type| Description| + | :------------ | :---------------------------------- | + | Promise<void> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { + console.log('setAssociatedData Success'); + }).catch((err) => { + console.log("setAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### getAccountCredential + +getAccountCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void; + +Obtains the credential of an application account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------------- | --------------------- | ---- | ---------------------------- | + | name | string | Yes| Application account name.| + | credentialType | string | Yes| Type of the credential to obtain.| + | callback | AsyncCallback<string> | Yes| Callback invoked to return the credential of the specified application account.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { + console.log("getAccountCredential err: " + JSON.stringify(err)); + console.log('getAccountCredential result: ' + result); + }); + ``` + +### getAccountCredential + +getAccountCredential(name: string, credentialType: string): Promise<string>; + +Obtains the credential of an application account. This method uses a promise to return the result asynchronously. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------------- | ------ | ---- | -------------------- | + | name | string | Yes| Application account name.| + | credentialType | string | Yes| Type of the credential to obtain.| + +- Return value + + | Type| Description| + | :-------------- | :---------------------------------- | + | Promise<string> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { + console.log('getAccountCredential, result: ' + data); + }).catch((err) => { + console.log("getAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### getAccountExtraInfo + +getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void; + +Obtains additional information of an application account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | --------------------- | ---- | -------------------------------- | + | name | string | Yes| Application account name.| + | callback | AsyncCallback<string> | Yes| Callback invoked to return the additional information of the specified application account.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { + console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + console.log('getAccountExtraInfo result: ' + result); + }); + ``` + +### getAccountExtraInfo + +getAccountExtraInfo(name: string): Promise<string>; + +Obtains additional information of an application account. This method uses a promise to return the result asynchronously. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | -------------- | + | name | string | Yes| Application account name.| + +- Return value + + | Type| Description| + | :-------------- | :---------------------------------- | + | Promise<string> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { + console.log('getAccountExtraInfo, result: ' + data); + }).catch((err) => { + console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### getAssociatedData + +getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void; + +Obtains data associated with an application account. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | --------------------- | ---- | ---------------------------------- | + | name | string | Yes| Application account name.| + | key | string | Yes| Key of the data to be obtained.| + | callback | AsyncCallback<string> | Yes| Callback invoked to return the data associated with the specified application account.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { + console.log("getAssociatedData err: " + JSON.stringify(err)); + console.log('getAssociatedData result: ' + result); + }); + ``` + +### getAssociatedData + +getAssociatedData(name: string, key: string): Promise<string>; + +Obtains data associated with an application account. This method uses a promise to return the result asynchronously. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | ------------------- | + | name | string | Yes| Application account name.| + | key | string | Yes| Key of the data to obtain.| + +- Return value + + | Type| Description| + | :-------------- | :---------------------------------- | + | Promise<string> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { + console.log('getAssociatedData: ' + data); + }).catch((err) => { + console.log("getAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### getAllAccessibleAccounts + +getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void; + +Obtains information about all accessible accounts. This method uses an asynchronous callback to return the result. + +The **ohos.permission.GET_ACCOUNTS_PRIVILEGED** permission is required. This permission is intended for system applications only. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ------------------------------------ | ---- | ---------------- | + | callback | AsyncCallback<Array<AppAccountInfo>> | Yes| Callback invoked to return information about all accessible accounts.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllAccessibleAccounts((err, data)=>{ + console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); + }); + ``` + +### getAllAccessibleAccounts + +getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>>; + +Obtains information about all accessible accounts. This method uses a promise to return the result. + +The **ohos.permission.GET_ACCOUNTS_PRIVILEGED** permission is required. This permission is intended for system applications only. + +- Parameters + + | Type| Description| + | ------------------------------ | ----------------------------------- | + | Promise<Array<AppAccountInfo>> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllAccessibleAccounts().then((data) => { + console.log('getAllAccessibleAccounts: ' + data); + }).catch((err) => { + console.log("getAllAccessibleAccounts err: " + JSON.stringify(err)); + }); + ``` + +### getAllAccounts + +getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void; + +Obtains information about all accounts of the specified account owner. This method uses an asynchronous callback to return the result. + +The **ohos.permission.GET_ACCOUNTS_PRIVILEGED** permission is required. This permission is intended for system applications only. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ------------------------------------ | ---- | ---------------- | + | owner | string | Yes| Owner of a system application account or third-party application account.| + | callback | AsyncCallback<Array<AppAccountInfo>> | Yes| Callback invoked to return information about all accounts of the specified account owner.| + +- Example + + ``` + const appAccountManager = account.createAppAccountManager(); + const selfBundle = "com.example.actsgetallaaccounts"; + appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ + console.debug("getAllAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccounts data:" + JSON.stringify(data)); + }); + ``` + +### getAllAccounts + +getAllAccounts(owner: string): Promise<Array<AppAccountInfo>>; + +Obtains information about all accounts of the specified account owner. This method uses a promise to return the result. + +The **ohos.permission.GET_ACCOUNTS_PRIVILEGED** permission is required. This permission is intended for system applications only. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | ---------- | + | owner | string | Yes| Owner of a system application account or third-party application account.| + +- Parameters + + | Type| Description| + | ------------------------------ | ----------------------------------- | + | Promise<Array<AppAccountInfo>> | Promise used to return the result.| + +- Example + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + const selfBundle = "com.example.actsgetallaaccounts"; + appAccountManager.getAllAccounts(selfBundle).then((data) => { + console.log('getAllAccounts: ' + data); + }).catch((err) => { + console.log("getAllAccounts err: " + JSON.stringify(err)); + }); + ``` + +### on('change') + +on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void; + +Subscribes to the account change event of the specified account owners. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | + | type | 'change' | Yes| Type of the event to subscribe to. The subscriber will receive a notification when the account owner updates the account.| + | owners | Array<string> | Yes| Owners of the account.| + | callback | Callback<Array<AppAccountInfo>> | Yes| Callback invoked to return the account change.| + +- Example + + ``` + const appAccountManager = account.createAppAccountManager(); + function changeOnCallback(data){ + console.debug("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); + } + catch(err){ + console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + } + ``` + +### off('change') + +off(type: 'change', callback?: Callback<void>): void; + +Unsubscribes from the account change event. This method uses an asynchronous callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------------------- | ---- | ------------------------ | + | type | 'change' | Yes| Account change event.| + | callback | Callback<void> | No| Callback used to report the account change.| + +- Example + + ``` + const appAccountManager = account.createAppAccountManager(); + function changeOnCallback(data){ + console.debug("receive change data:" + JSON.stringify(data)); + appAccountManager.off('change', function(){ + console.debug("off finish"); + } + } + try{ + appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); + } + catch(err){ + console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + } + ``` + +## AppAccountInfo + + + +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ------------------ | +| owner | string | Yes| Owner of an application account.| +| name | string | Yes| Name of an application account.| diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index facaa2410ce43a3d3b3858097fc660fe62eb10a4..98d16f8591eed0dd77e1c68a39bdd1c937c4c6d2 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,113 +1,555 @@ -# Audio Management +# Audio +This module provides the following functions: audio management, audio rendering and system sound management. -## Modules to Import + +--- +## ***Note:*** + + Changes to the AudioRenderer interface have been proposed. + When the updated APIs have been integrated, the document will be revised, and apps must adapt to it. + +--- + +## Modules to Import ``` import audio from '@ohos.multimedia.audio'; ``` -## Required Permissions +## Required Permissions None -## getAudioManager\(\): AudioManager +## audioManager + +getAudioManager\(\): AudioManager Obtains an **AudioManager** instance. -**Return values** +**Return value** + + + + + + + + + + +

Type

+

Description

+

AudioManager

+

AudioManager object.

+
+ +**Example** + +``` +var audioManager = audio.getAudioManager(); +``` + + +## audioRenderer + +createAudioRenderer(volumeType: AudioVolumeType): AudioRenderer + +Obtains an **AudioRenderer** instance. + +**Parameters** +| Name | Type | Mandatory | Description | +| :--------- | :-------------- | :-------- | :----------------- | +| volumeType | AudioVolumeType | Yes | Audio stream type. | -| Type | Description | -| -------------- | -------------------------- | -| AudioManager | Audio manager. | +**Return value** +| Type | Description | +| ------------- | --------------------- | +| AudioRenderer | AudioRenderer object. | **Example** ``` -var audioManager = audio.getAudioManager(); +const volType = audio.AudioVolumeType.MEDIA; +const audioRenderer = audio.createAudioRenderer(volType); ``` -## AudioVolumeType -Enumerates audio stream types. +## systemSoundManager -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| RINGTONE | 2 | Audio stream for ringtones. | -| MEDIA | 3 | Audio stream for media purpose. | +getSystemSoundManager(): SystemSoundManager -## DeviceFlag +Obtains a **SystemSoundManager** instance. -Enumerates audio device flags. +**Parameters** -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| OUTPUT_DEVICES_FLAG | 1 | Output device. | -| INPUT_DEVICES_FLAG | 2 | Input device. | -| ALL_DEVICES_FLAG | 3 | All devices. | +None +**Return value** -## DeviceRole +| Type | Description | +| ------------------ | -------------------------- | +| SystemSoundManager | SystemSoundManager object. | -Enumerates audio device roles. +**Example** -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| INPUT_DEVICE | 1 | Input role. | -| OUTPUT_DEVICE | 2 | Output role. | +``` +const systemSoundManager = audio.getSystemSoundManager(); +``` -## DeviceType -Enumerates audio device types. +## AudioVolumeType + +Enumerates audio stream types. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

RINGTONE

+

2

+

Audio stream for ringtones.

+

MEDIA

+

3

+

Audio stream for media purpose.

+
+ + +## DeviceFlag -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| INVALID | 0 | Invalid device. | -| EARPIECE | 1 | Earpiece. | -| SPEAKER | 2 | Speaker. | -| WIRED_HEADSET | 3 | Wired headset. | -| BLUETOOTH_SCO | 7 | Bluetooth device using the synchronous connection oriented (SCO) link. | -| BLUETOOTH_A2DP | 8 | Bluetooth device using the advanced audio distribution profile (A2DP). | -| MIC | 15 | Microphone. | +Enumerates audio device flags. + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

OUTPUT_DEVICES_FLAG

+

1

+

Output device.

+

INPUT_DEVICES_FLAG

+

2

+

Input device.

+

ALL_DEVICES_FLAG

+

3

+

All devices.

+
+ + +## DeviceRole -## ActiveDeviceType7+ +Enumerates audio device roles. -Enumerates active device types. + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

INPUT_DEVICE

+

1

+

Input role.

+

OUTPUT_DEVICE

+

2

+

Output role.

+
+ + +## DeviceType -| Name | Default Value | Description | -| -------------- | ------------- | --------------------------------------------------------------------- | -| SPEAKER | 2 | Speaker. | -| BLUETOOTH_SCO | 7 | Bluetooth device using the SCO link. | +Enumerates audio device types. -## AudioRingMode7+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

INVALID

+

0

+

Invalid device.

+

SPEAKER

+

1

+

Speaker.

+

WIRED_HEADSET

+

2

+

Wired headset.

+

BLUETOOTH_SCO

+

3

+

Bluetooth device using the synchronous connection oriented (SCO) link.

+

BLUETOOTH_A2DP

+

4

+

Bluetooth device using the advanced audio distribution profile (A2DP).

+

MIC

+

5

+

Microphone.

+
+ + +## AudioRingMode7+ Enumerates ringer modes. -| Name | Default Value | Description | -| ------------- | ------------- | --------------------------------------------------------------------- | -| RINGER_MODE_SILENT | 0 | Silence mode. | -| RINGER_MODE_VIBRATE | 1 | Vibration mode. | -| RINGER_MODE_NORMAL | 2 | Normal mode. | + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

RINGER_MODE_SILENT

+

0

+

Silence mode.

+

RINGER_MODE_VIBRATE

+

1

+

Vibration mode.

+

RINGER_MODE_NORMAL

+

2

+

Normal mode.

+
+ + +## AudioSampleFormat8+ +Enumerates the audio sample formats. + +| Name | Default Value | Description | +| :------------ | :------------ | :------------------------------------ | +| INVALID_WIDTH | -1 | Invalid format. | +| SAMPLE_U8 | 1 | Unsigned 8 bit integer. | +| SAMPLE_S16LE | 0 | Signed 16 bit integer, little endian. | +| SAMPLE_S24LE | 1 | Signed 24 bit integer, little endian. | +| SAMPLE_S32LE | 2 | Signed 32 bit integer, little endian. | + + +## AudioChannel8+ +Enumerates the audio channels. + +| Name | Default Value | Description | +| :----- | :------------ | :--------------- | +| MONO | 1 | Channel count 1. | +| STEREO | 2 | Channel count 2. | + + +## AudioSamplingRate8+ +Enumerates the audio sampling rates. + +| Name | Default Value | Description | +| :---------------- | :------------ | :------------------- | +| SAMPLE_RATE_8000 | 8000 | Sampling rate 8000. | +| SAMPLE_RATE_11025 | 11025 | Sampling rate 11025. | +| SAMPLE_RATE_12000 | 12000 | Sampling rate 12000. | +| SAMPLE_RATE_16000 | 16000 | Sampling rate 16000. | +| SAMPLE_RATE_22050 | 22050 | Sampling rate 22050. | +| SAMPLE_RATE_24000 | 24000 | Sampling rate 24000. | +| SAMPLE_RATE_32000 | 32000 | Sampling rate 32000. | +| SAMPLE_RATE_44100 | 44100 | Sampling rate 44100. | +| SAMPLE_RATE_48000 | 48000 | Sampling rate 48000. | +| SAMPLE_RATE_64000 | 64000 | Sampling rate 64000. | +| SAMPLE_RATE_96000 | 96000 | Sampling rate 96000. | + + +## AudioEncodingType8+ +Enumerates the audio encoding types. + +| Name | Default Value | Description | +| :--------------- | :------------ | :---------- | +| ENCODING_PCM | 0 | PCM. | +| ENCODING_INVALID | 1 | Invalid. | + + +## ContentType8+ +Enumerates the content types. + +| Name | Default Value | Description | +| :------------------------ | :------------ | :-------------------- | +| CONTENT_TYPE_UNKNOWN | 0 | Unknown content. | +| CONTENT_TYPE_SPEECH | 1 | Speech content. | +| CONTENT_TYPE_MUSIC | 2 | Music content. | +| CONTENT_TYPE_MOVIE | 3 | Movie content. | +| CONTENT_TYPE_SONIFICATION | 4 | Notification content. | +| CONTENT_TYPE_RINGTONE | 5 | Ringtone content. | + + +## StreamUsage8+ +Enumerates the stream usage. + +| Name | Default Value | Description | +| :--------------------------------- | :------------ | :------------------------------ | +| STREAM_USAGE_UNKNOWN | 0 | Unknown usage. | +| STREAM_USAGE_MEDIA | 1 | Media usage. | +| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Voice communication usage. | +| STREAM_USAGE_NOTIFICATION_RINGTONE | 3 | Notification or ringtone usage. | + + +## AudioState8+ +Enumerates the audio states. + +| Name | Default Value | Description | +| :------------- | :------------ | :------------------------- | +| STATE_INVALID | -1 | Invalid state. | +| STATE_NEW | 0 | Create New instance state. | +| STATE_PREPARED | 1 | Prepared state. | +| STATE_RUNNING | 2 | Running state. | +| STATE_STOPPED | 3 | Stopped state. | +| STATE_RELEASED | 4 | Released state. | +| STATE_PAUSED | 5 | Paused state. | -## AudioManager -Implements audio volume and audio device management. +## AudioRendererRate8+ +Enumerates the audio renderer rates. + +| Name | Default Value | Description | +| :----------------- | :------------ | :----------- | +| RENDER_RATE_NORMAL | 0 | Normal rate. | +| RENDER_RATE_DOUBLE | 1 | Double rate. | +| RENDER_RATE_HALF | 2 | Half rate. | + + +## InterruptType8+ +Enumerates the interrupt types. + +| Name | Default Value | Description | +| :------------------- | :------------ | :----------------------------------- | +| INTERRUPT_TYPE_BEGIN | 1 | Audio playback interruption started. | +| INTERRUPT_TYPE_END | 2 | Audio playback interruption ended. | + + +## InterruptForceType8+ +Enumerates the interrupt force types. + +| Name | Default Value | Description | +| :-------------- | :------------ | :--------------------------------------- | +| INTERRUPT_FORCE | 0 | Forced action taken by system. | +| INTERRUPT_SHARE | 1 | App can choose to take action or ignore. | + + +## InterruptHint8+ +Enumerates the interrupt hints. + +| Name | Default Value | Description | +| :-------------------- | :------------ | :------------------------- | +| INTERRUPT_HINT_NONE | 0 | None. | +| INTERRUPT_HINT_RESUME | 1 | Resume the playback. | +| INTERRUPT_HINT_PAUSE | 2 | Paused/Pause the playback. | +| INTERRUPT_HINT_STOP | 3 | Stopped/Stop the playback. | +| INTERRUPT_HINT_DUCK | 4 | Ducked the playback. | +| INTERRUPT_HINT_UNDUCK | 5 | Unducked the playback. | + + +## RingtoneType8+ +Enumerates the ringtone types. + +| Name | Default Value | Description | +| :--------------------- | :------------ | :-------------- | +| RINGTONE_TYPE_DEFAULT | 0 | Default type. | +| RINGTONE_TYPE_MULTISIM | 1 | Multi-SIM type. | + + +## AudioParameters8+ +Describes audio parameters of playback files. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :----------- | :---------------- | :-------- | :-------------------------------------------- | +| format | AudioSampleFormat | Yes | Sample format of the audio file to be played. | +| channels | AudioChannel | Yes | Channel count of the audio file to be played. | +| samplingRate | AudioSamplingRate | Yes | Sample rate of the audio file to be played. | +| encoding | AudioEncodingType | Yes | Encoding type of the audio file to be played. | +| contentType | ContentType | Yes | Content type. | +| usage | StreamUsage | Yes | Stream usage. | +| deviceRole | DeviceRole | Yes | Device role. | +| deviceType | DeviceType | Yes | Device type. | + + +## AudioRendererInfo8+ +Describes audio renderer information. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------------ | :---------- | :-------- | :-------------------- | +| contentType | ContentType | Yes | Content type. | +| usage | StreamUsage | Yes | Stream usage. | +| rendererFlags | number | Yes | Audio renderer flags. | + + +## InterruptEvent8+ +Describes the interrupt event received by the app when playback is interrupted. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :-------- | :----------------- | :-------- | :-------------------------------------------------------------------------- | +| eventType | InterruptType | Yes | Indicates whether the interruption has started or finished. | +| forceType | InterruptForceType | Yes | Indicates whether the action is taken by system or to be taken by the app. | +| hintType | InterruptHint | Yes | Indicates the kind of action. | + + +## VolumeEvent8+ +Describes the volume event received by the app when the volume is changed. -### setVolume\(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback\): void +**Parameters** + +| Name | Type | Mandatory | Description | +| :--------- | :-------------- | :-------- | :--------------------------------------- | +| volumeType | AudioVolumeType | Yes | Volume type of the current stream. | +| volume | number | Yes | Volume level. | +| updateUi | boolean | Yes | Whether to show the volume change in UI. | -Sets the volume for a stream. This method uses an asynchronous callback to return the execution result. + +## RingtoneOptions8+ +Describes ringtone options. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | +| Name | Type | Mandatory | Description | +| :----- | :------ | :-------- | :--------------- | +| volume | number | Yes | Ringtone volume. | +| loop | boolean | Yes | Loop value. | + + +# AudioManager + +Implements audio volume and audio device management. + +## audioManager.setVolume -**Return values** +setVolume\(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback\): void + +Sets the volume for a stream. This method uses an asynchronous callback to return the result. + +**Parameters** + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

volume

+

number

+

Yes

+

Volume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +**Return value** None @@ -122,23 +564,62 @@ audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err)=>{ console.log('Callback invoked to indicate a successful volume setting.'); }) ``` +## audioManager.setVolume -### setVolume\(volumeType: AudioVolumeType, volume: number\): Promise +setVolume\(volumeType: AudioVolumeType, volume: number\): Promise -Sets the volume for a stream. This method uses a promise to return the execution result. +Sets the volume for a stream. This method uses a promise to return the result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | - -**Return values** - -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

volume

+

number

+

Yes

+

Volume to set. The value range can be obtained by calling getMinVolume and getMaxVolume.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
**Example** @@ -148,18 +629,47 @@ audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(()=> ) ``` -### getVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void +## audioManager.getVolume + +getVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void Obtains the volume of a stream. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the volume. | - -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the volume.

+
+ +**Return value** None @@ -175,21 +685,54 @@ audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### getVolume\(volumeType: AudioVolumeType\): Promise -Obtains the volume of a stream. This method uses a promise to return the query result. +## audioManager.getVolume -**Parameters** +getVolume\(volumeType: AudioVolumeType\): Promise -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | +Obtains the volume of a stream. This method uses a promise to return the query result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the volume. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the volume.

+
**Example** @@ -199,18 +742,48 @@ audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => ) ``` -### getMinVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void + +## audioManager.getMinVolume + +getMinVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void Obtains the minimum volume allowed for a stream. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the minimum volume. | - -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the minimum volume.

+
+ +**Return value** None @@ -226,43 +799,105 @@ audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### getMinVolume\(volumeType: AudioVolumeType\): Promise - -Obtains the minimum volume allowed for a stream. This method uses a promise to return the query result. -**Parameters** +## audioManager.getMinVolume -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | +getMinVolume\(volumeType: AudioVolumeType\): Promise -**Return values** +Obtains the minimum volume allowed for a stream. This method uses a promise to return the query result. -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the minimum volume. | +**Parameters** + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the minimum volume.

+
**Example** ``` audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => - console.log('Promised returned to indicate that the minimum volume is obtained.' + value); + console.log('Promised returned to indicate that the minimum volume is obtained.' + value); ) ``` -### getMaxVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void + +## audioManager.getMaxVolume + +getMaxVolume\(volumeType: AudioVolumeType, callback: AsyncCallback\): void Obtains the maximum volume allowed for a stream. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the maximum volume. | - -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the maximum volume.

+
+ +**Return value** None @@ -278,22 +913,54 @@ audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### getMaxVolume\(volumeType: AudioVolumeType\): Promise - -Obtains the maximum volume allowed for a stream. This method uses a promise to return the query result. -**Parameters** +## audioManager.getMaxVolume -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | +getMaxVolume\(volumeType: AudioVolumeType\): Promise +Obtains the maximum volume allowed for a stream. This method uses a promise to return the query result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the maximum volume. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the maximum volume.

+
**Example** @@ -303,19 +970,56 @@ audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data)=> ) ``` -### mute\(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback\): void7+ +## audioManager.mute -Mutes a stream. This method uses an asynchronous callback to return the execution result. +mute\(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback\): void7+ -**Parameters** +Mutes a stream. This method uses an asynchronous callback to return the result. -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | +**Parameters** -**Return values** + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

mute

+

boolean

+

Yes

+

Mute status to set. The value true means to mute the stream, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +**Return value** None @@ -331,22 +1035,63 @@ audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { }) ``` -### mute\(volumeType: AudioVolumeType, mute: boolean\): Promise7+ -Mutes a stream. This method uses a promise to return the execution result. +## audioManager.mute -**Parameters** +mute\(volumeType: AudioVolumeType, mute: boolean\): Promise7+ -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | +Mutes a stream. This method uses a promise to return the result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

mute

+

boolean

+

Yes

+

Mute status to set. The value true means to mute the stream, and false means the opposite.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
**Example** @@ -356,18 +1101,48 @@ audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => ) ``` -### isMute\(volumeType: AudioVolumeType, callback: AsyncCallback\): void7+ + +## audioManager.isMute + +isMute\(volumeType: AudioVolumeType, callback: AsyncCallback\): void7+ Checks whether a stream is muted. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | - -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.

+
+ +**Return value** None @@ -383,22 +1158,54 @@ audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### isMute\(volumeType: AudioVolumeType\): Promise7+ - -Checks whether a stream is muted. This method uses a promise to return the execution result. -**Parameters** +## audioManager.isMute -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | +isMute\(volumeType: AudioVolumeType\): Promise7+ +Checks whether a stream is muted. This method uses a promise to return the result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the mute status of the stream. The value true means that the stream is muted, and false means the opposite.

+
**Example** @@ -408,18 +1215,48 @@ audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => ) ``` -### isActive\(volumeType: AudioVolumeType, callback: AsyncCallback\): void7+ + +## audioManager.isActive + +isActive\(volumeType: AudioVolumeType, callback: AsyncCallback\): void7+ Checks whether a stream is active. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | -| callback | AsyncCallback | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | - -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.

+
+ +**Return value** None @@ -435,22 +1272,54 @@ audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { }) ``` -### isActive\(volumeType: AudioVolumeType\): Promise7+ - -Checks whether a stream is active. This method uses a promise to return the query result. -**Parameters** +## audioManager.isActive -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| volumeType | AudioVolumeType | Yes | Audio stream type. | +isActive\(volumeType: AudioVolumeType\): Promise7+ -**Return values** +Checks whether a stream is active. This method uses a promise to return the query result. +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

volumeType

+

AudioVolumeType

+

Yes

+

Audio stream type.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the active status of the stream. The value true means that the stream is active, and false means the opposite.

+
**Example** @@ -460,18 +1329,48 @@ audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => ) ``` -### setRingerMode\(mode: AudioRingMode, callback: AsyncCallback\): void7+ -Sets the ringer mode. This method uses an asynchronous callback to return the execution result. +## audioManager.setRingerMode -**Parameters** +setRingerMode\(mode: AudioRingMode, callback: AsyncCallback\): void7+ + +Sets the ringer mode. This method uses an asynchronous callback to return the result. -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| mode | AudioRingMode | Yes | Ringer mode. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | +**Parameters** -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

mode

+

AudioRingMode

+

Yes

+

Ringer mode.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +**Return value** None @@ -487,22 +1386,54 @@ audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { }) ``` -### setRingerMode\(mode: AudioRingMode\): Promise7+ - -Sets the ringer mode. This method uses a promise to return the execution result. -**Parameters** +## audioManager.setRingerMode -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| mode | AudioRingMode | Yes | Ringer mode. | +setRingerMode\(mode: AudioRingMode\): Promise7+ +Sets the ringer mode. This method uses a promise to return the result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

mode

+

AudioRingMode

+

Yes

+

Ringer mode.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
**Example** @@ -512,17 +1443,39 @@ audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => ) ``` -### getRingerMode\(callback: AsyncCallback\): void7+ + +## audioManager.getRingerMode + +getRingerMode\(callback: AsyncCallback\): void7+ Obtains the ringer mode. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| callback | AsyncCallback<AudioRingMode> | Yes | Callback used to return the ringer mode. | - -**Return values** + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<AudioRingMode>

+

Yes

+

Callback used to return the ringer mode.

+
+ +**Return value** None @@ -538,7 +1491,10 @@ audioManager.getRingerMode((err, value) => { }) ``` -### getRingerMode\(\): Promise7+ + +## audioManager.getRingerMode + +getRingerMode\(\): Promise7+ Obtains the ringer mode. This method uses a promise to return the query result. @@ -546,11 +1502,22 @@ Obtains the ringer mode. This method uses a promise to return the query result. None -**Return values** - -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise<AudioRingMode> | Promise used to return the ringer mode. | +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<AudioRingMode>

+

Promise used to return the ringer mode.

+
**Example** @@ -560,19 +1527,57 @@ audioManager.getRingerMode().then((value) => ) ``` -### setAudioParameter\(key: string, value: string, callback: AsyncCallback\): void7+ -Sets an audio parameter. This method uses an asynchronous callback to return the execution result. +## audioManager.setAudioParameter -**Parameters** +setAudioParameter\(key: string, value: string, callback: AsyncCallback\): void7+ + +Sets an audio parameter. This method uses an asynchronous callback to return the result. -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| key | string | Yes | Key of the audio parameter to set. | -| value | string | Yes | Value of the audio parameter to set. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | +**Parameters** -**Return values** + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the audio parameter to set.

+

value

+

string

+

Yes

+

Value of the audio parameter to set.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +**Return value** None @@ -588,22 +1593,63 @@ audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => { }) ``` -### setAudioParameter\(key: string, value: string\): Promise7+ -Sets an audio parameter. This method uses a promise to return the execution result. +## audioManager.setAudioParameter -**Parameters** +setAudioParameter\(key: string, value: string\): Promise7+ -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| key | string | Yes | Key of the audio parameter to set. | -| value | string | Yes | Value of the audio parameter to set. | +Sets an audio parameter. This method uses a promise to return the result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the audio parameter to set.

+

value

+

string

+

Yes

+

Value of the audio parameter to set.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
**Example** @@ -613,18 +1659,48 @@ audioManager.setAudioParameter('PBits per sample', '8 bit').then(() => ) ``` -### getAudioParameter\(key: string, callback: AsyncCallback\): void7+ + +## audioManager.getAudioParameter + +getAudioParameter\(key: string, callback: AsyncCallback\): void7+ Obtains the value of an audio parameter. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| key | string | Yes | Key of the audio parameter whose value is to be obtained. | -| callback | AsyncCallback | Yes | Callback used to return the value of the audio parameter. | - -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the audio parameter whose value is to be obtained.

+

callback

+

AsyncCallback<string>

+

Yes

+

Callback used to return the value of the audio parameter.

+
+ +**Return value** None @@ -640,21 +1716,54 @@ audioManager.getAudioParameter('PBits per sample', (err, value) => { }) ``` -### getAudioParameter\(key: string\): Promise7+ -Obtains the value of an audio parameter. This method uses a promise to return the query result. +## audioManager.getAudioParameter -**Parameters** +getAudioParameter\(key: string\): Promise7+ -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| key | string | Yes | Key of the audio parameter whose value is to be obtained. | +Obtains the value of an audio parameter. This method uses a promise to return the query result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the value of the audio parameter. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the audio parameter whose value is to be obtained.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise used to return the value of the audio parameter.

+
**Example** @@ -664,18 +1773,48 @@ audioManager.getAudioParameter('PBits per sample').then((value) => ) ``` -### getDevices\(deviceFlag: DeviceFlag, callback: AsyncCallback\): void + +## audioManager.getDevices + +getDevices\(deviceFlag: DeviceFlag, callback: AsyncCallback\): void Obtains the audio devices with a specific flag. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceFlag | DeviceFlag | Yes | Audio device flag. | -| callback | AsyncCallback<AudioDeviceDescriptors> | Yes | Callback used to return the device list. | - -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceFlag

+

DeviceFlag

+

Yes

+

Audio device flag.

+

callback

+

AsyncCallback<AudioDeviceDescriptors>

+

Yes

+

Callback used to return the device list.

+
+ +**Return value** None @@ -691,21 +1830,55 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{ }) ``` -### getDevices\(deviceFlag: DeviceFlag\): Promise -Obtains the audio devices with a specific flag. This method uses a promise to return the query result. -**Parameters** +## audioManager.getDevices + +getDevices\(deviceFlag: DeviceFlag\): Promise -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceFlag | DeviceFlag | Yes | Audio device flag. | +Obtains the audio devices with a specific flag. This method uses a promise to return the query result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise<AudioDeviceDescriptors> | Promise used to return the device list. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceFlag

+

DeviceFlag

+

Yes

+

Audio device flag.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<AudioDeviceDescriptors>

+

Promise used to return the device list.

+
**Example** @@ -715,26 +1888,64 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data)=> ) ``` -### setDeviceActive\(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback\): void7+ -Sets a device to the active state. This method uses an asynchronous callback to return the execution result. +## audioManager.setDeviceActive -**Parameters** +setDeviceActive\(deviceType: DeviceType, active: boolean, callback: AsyncCallback\): void7+ + +Sets a device to the active state. This method uses an asynchronous callback to return the result. -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceType | ActiveDeviceType | Yes | Audio device type. | -| active | boolean | Yes | Active status to set. The value **true** means to set the device to the active status, and **false** means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | +**Parameters** -**Return values** + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceType

+

DeviceType

+

Yes

+

Audio device type.

+

active

+

boolean

+

Yes

+

Active status to set. The value true means to set the device to the active status, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +**Return value** None **Example** ``` -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err)=> { +audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true, (err)=> { if (err) { console.error('Failed to set the active status of the device. ${err.message}'); return; @@ -743,50 +1954,122 @@ audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err)=> { }) ``` -### setDeviceActive\(deviceType: ActiveDeviceType, active: boolean\): Promise7+ -Sets a device to the active state. This method uses a promise to return the execution result. -**Parameters** +## audioManager.setDeviceActive -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceType | ActiveDeviceType | Yes | Audio device type. | -| active | boolean | Yes | Active status to set. The value **true** means to set the device to the active status, and **false** means the opposite. | +setDeviceActive\(deviceType: DeviceType, active: boolean\): Promise7+ -**Return values** +Sets a device to the active state. This method uses a promise to return the result. + +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceType

+

DeviceType

+

Yes

+

Audio device type.

+

active

+

boolean

+

Yes

+

Active status to set. The value true means to set the device to the active status, and false means the opposite.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
**Example** ``` -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(()=> +audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true).then(()=> console.log('Promise returned to indicate that the device is set to the active status.'); ) ``` -### isDeviceActive\(deviceType: DeviceType, callback: AsyncCallback\): void7+ + +## audioManager.isDeviceActive + +isDeviceActive\(deviceType: DeviceType, callback: AsyncCallback\): void7+ Checks whether a device is active. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceType | ActiveDeviceType | Yes | Audio device type. | -| callback | AsyncCallback | Yes | Callback used to return the active status of the device. | - -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceType

+

DeviceType

+

Yes

+

Audio device type.

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the active status of the device.

+
+ +**Return value** None **Example** ``` -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { +audioManager.isDeviceActive(audio.DeviceType.SPEAKER, (err, value) => { if (err) { console.error('Failed to obtain the active status of the device. ${err.message}'); return; @@ -795,43 +2078,105 @@ audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { }) ``` -### isDeviceActive\(deviceType: ActiveDeviceType\): Promise7+ - -Checks whether a device is active. This method uses a promise to return the query result. -**Parameters** +## audioManager.isDeviceActive -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| deviceType | ActiveDeviceType | Yes | Audio device type. | +isDeviceActive\(deviceType: DeviceType\): Promise7+ +Checks whether a device is active. This method uses a promise to return the query result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the active status of the device. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceType

+

DeviceType

+

Yes

+

Audio device type.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the active status of the device.

+
**Example** ``` -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => +audioManager.isDeviceActive(audio.DeviceType.SPEAKER).then((value) => console.log('Promise returned to indicate that the active status of the device is obtained.' + value); ) ``` -### setMicrophoneMute\(mute: boolean, callback: AsyncCallback\): void7+ -Mutes or unmutes the microphone. This method uses an asynchronous callback to return the execution result. +## audioManager.setMicrophoneMute -**Parameters** +setMicrophoneMute\(mute: boolean, callback: AsyncCallback\): void7+ + +Mutes or unmutes the microphone. This method uses an asynchronous callback to return the result. -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | -| callback | AsyncCallback | Yes | Callback used to return the execution result. | +**Parameters** -**Return values** + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

mute

+

boolean

+

Yes

+

Mute status to set. The value true means to mute the microphone, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +**Return value** None @@ -847,21 +2192,54 @@ audioManager.setMicrophoneMute(true, (err) => { }) ``` -### setMicrophoneMute\(mute: boolean\): Promise7+ -Mutes or unmutes the microphone. This method uses a promise to return the execution result. +## audioManager.setMicrophoneMute -**Parameters** +setMicrophoneMute\(mute: boolean\): Promise7+ -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | +Mutes or unmutes the microphone. This method uses a promise to return the result. -**Return values** +**Parameters** -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the execution result. | + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

mute

+

boolean

+

Yes

+

Mute status to set. The value true means to mute the microphone, and false means the opposite.

+
+ +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
**Example** @@ -871,17 +2249,39 @@ audioManager.setMicrophoneMute(true).then(() => ) ``` -### isMicrophoneMute\(callback: AsyncCallback\): void7+ + +## audioManager.isMicrophoneMute + +isMicrophoneMute\(callback: AsyncCallback\): void7+ Checks whether the microphone is muted. This method uses an asynchronous callback to return the query result. **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------- | ---------------|------------------------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | - -**Return values** + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

+
+ +**Return value** None @@ -897,7 +2297,10 @@ audioManager.isMicrophoneMute((err, value) => { }) ``` -### isMicrophoneMute\(\): Promise7+ + +## audioManager.isMicrophoneMute + +isMicrophoneMute\(\): Promise7+ Checks whether the microphone is muted. This method uses a promise to return the query result. @@ -905,11 +2308,22 @@ Checks whether the microphone is muted. This method uses a promise to return the None -**Return values** - -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Promise | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | +**Return value** + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the mute status of the microphone. The value true means that the microphone is muted, and false means the opposite.

+
**Example** @@ -919,21 +2333,1673 @@ audioManager.isMicrophoneMute().then((value) => ) ``` -## AudioDeviceDescriptor +## audioManager.on + +on(type: 'volumeChange', callback: Callback): void8+ + +Listens for system volume change events. This method uses a callback to get volume change events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Type of the playback event to listen for. | +| callback | Callback | Yes | Callback used to get the system volume change event. | + +**Return value** + +None + +**Example** + +``` +audioManager.on('volumeChange', (volumeEvent) => { + console.log('VolumeType of stream: ' + volumeEvent.volumeType); + console.log('Volume level: ' + volumeEvent.volume); + console.log('Whether to updateUI: ' + volumeEvent.updateUi); +}) +``` + + +## audioManager.on + +on(type: 'ringerModeChange', callback: Callback): void8+ + +Listens for ringer mode change events. This method uses a callback to get ringer mode changes. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :----------------------- | :-------- | :-------------------------------------------- | +| type | string | Yes | Type of the playback event to listen for. | +| callback | Callback | Yes | Callback used to get the updated ringer mode. | + +**Return value** + +None + +**Example** + +``` +audioManager.on('ringerModeChange', (ringerMode) => { + console.log('Updated ringermode: ' + ringerMode); +}) +``` + +# AudioDeviceDescriptor Describes an audio device. -### Attributes +## AudioDeviceDescriptors + +type AudioDeviceDescriptors = Array\> : void\ +
+Array of AudioDeviceDescriptors, which is read-only. + +## audioDeviceDescriptor.deviceRole + +readonly deviceRole: DeviceRole + +Defines the role of the device. + +| Name | Type | Readable | Writable | Description | +| :--------- | :--------- | :------- | :------- | ------------------ | +| deviceRole | DeviceRole | Yes | No | Audio device role. | + +## audioDeviceDescriptor.deviceType + +readonly deviceType: DeviceType + +Defines the type of the device. + +| Name | Type | Readable | Writable | Description | +| :--------- | :--------- | :------- | :------- | ------------------ | +| deviceType | DeviceType | Yes | No | Audio device type. | + +``` +function deviceProp(audioDeviceDescriptor, index, array) { + deviceRoleValue = audioDeviceDescriptor.deviceRole; + deviceTypeValue = audioDeviceDescriptor.deviceType; +} + +deviceRoleValue = null; +deviceTypeValue = null; +const promise = audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG); +promise.then(async function (audioDeviceDescriptors) { + console.info('getDevices OUTPUT_DEVICES_FLAG'); + audioDeviceDescriptors.forEach(deviceProp); + if (deviceTypeValue != null && deviceRoleValue != null){ + console.info('OUTPUT_DEVICES_FLAG : Pass'); + expect(true).assertTrue(); + } + else{ + console.error('OUTPUT_DEVICES_FLAG : fail'); + expect(false).assertTrue(); + } + }); + await promise; + done(); +}) +``` +# AudioRenderer +Provides audio playback APIs. + + +## audioRenderer.state + +readonly state: AudioState 8+ -| Name | Type | Readable | Writable | Description | -| ------------- | ------------- | ---------------|--------------------------------|------------------------ | -| deviceRole | DeviceRole | Yes | No | Audio device role. | -| deviceType | DeviceType | Yes | No | Audio device type. | +Defines the current render state. + +| Name | Type | Readable | Writable | Description | +| :---- | :--------- | :------- | :------- | :------------------ | +| state | AudioState | Yes | No | Audio render state. | + +**Example** + +``` + var state = audioRenderer.state; +``` + + +## audioRenderer.setParams + +setParams(params: AudioParameters, callback: AsyncCallback): void8+ + +Sets audio parameters for rendering. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :-------------------------------------- | +| params | AudioParameters | Yes | Audio parameters of the file to be set. | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +var audioParams = { + format: audio.AudioSampleFormat.SAMPLE_S16LE, + channels: audio.AudioChannel.STEREO, + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_16000, + encoding: audio.AudioEncodingType.ENCODING_PCM, + }; + +audioRenderer.setParams(audioParams, (err)=>{ + if (err) { + console.error('Failed to set params. ${err.message}'); + return; + } + console.log('Callback invoked to indicate a successful params setting.'); +}) +``` + + +## audioRenderer.setParams + +setParams(params: AudioParameters): Promise8+ + +Sets audio parameters for rendering. This method uses a promise to return the result. + +**Parameters** -## AudioDeviceDescriptors +| Name | Type | Mandatory | Description | +| :----- | :-------------- | :-------- | :-------------------------------------- | +| params | AudioParameters | Yes | Audio parameters of the file to be set. | -| Name | Description | -| ------------- | -------------------------------------------------------- | -| Device attribute array | Array of **AudioDeviceDescriptors**, which is read-only. | +**Return value** +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | +**Example** + +``` +var audioParams = { + format: audio.AudioSampleFormat.SAMPLE_S16LE, + channels: audio.AudioChannel.STEREO, + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_16000, + encoding: audio.AudioEncodingType.ENCODING_PCM, + }; + +await audioRenderer.setParams(audioParams); +``` + + +## audioRenderer.getParams + +getParams(callback: AsyncCallback): void8+ + +Gets audio parameters of the renderer. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------------------ | :-------- | :-------------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the audio parameters. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.getParams((err, audioParams)=>{ + console.log('Renderer GetParams:'); + console.log('Renderer format:' + audioParams.format); + console.log('Renderer samplingRate:' + audioParams.samplingRate); + console.log('Renderer channels:' + audioParams.channels); + console.log('Renderer encoding:' + audioParams.encoding); +}) +``` + + +## audioRenderer.getParams + +getParams(): Promise8+ + +Gets audio parameters of the renderer. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :------------------------ | :------------------------------------------- | +| Promise | Promise used to return the audio parameters. | + +**Example** + +``` +let audioParams = await audioRenderer.getParams(); +console.log('Renderer GetParams:'); +console.log('Renderer format:' + audioParams.format); +console.log('Renderer samplingRate:' + audioParams.samplingRate); +console.log('Renderer channels:' + audioParams.channels); +console.log('Renderer encoding:' + audioParams.encoding); +``` + + +## audioRenderer.start + +start(callback: AsyncCallback): void8+ + +Starts the renderer. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :---------------------- | :-------- | :----------------------------------------------------------------------------- | +| callback | AsyncCallback | Yes | Returns true if the renderer is started successfully; returns false otherwise. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.start((err, started)=>{ + if (started) { + console.log('Renderer started.'); + } else { + console.error('Renderer start rejected.'); + } +}) +``` + + +## audioRenderer.start + +start(): Promise8+ + +Starts the renderer. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :---------------- | :----------------------------------------------------------------------------- | +| Promise | Returns true if the renderer is started successfully; returns false otherwise. | + +**Example** + +``` +var started = await audioRenderer.start(); +if (started) { + console.log('Renderer started'); +} else { + console.error('Renderer start rejected'); +} +``` + + +## audioRenderer.pause + +pause(callback: AsyncCallback): void8+ + +Pauses rendering. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :---------------------- | :-------- | :---------------------------------------------------------------------------- | +| callback | AsyncCallback | Yes | Returns true if the renderer is paused successfully; returns false otherwise. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.pause((err, paused)=>{ + if (paused) { + console.log('Renderer paused.'); + } else { + console.error('Renderer pause failed'); + } +}) +``` + + + +## audioRenderer.pause + +pause(): Promise8+ + +Pauses rendering. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :---------------- | :---------------------------------------------------------------------------- | +| Promise | Returns true if the renderer is paused successfully; returns false otherwise. | + +**Example** + +``` +var paused = await audioRenderer.pause(); +if (paused) { + console.log('Renderer paused'); +} else { + console.error('Renderer pause failed'); +} +``` + + + +## audioRenderer.drain + +drain(callback: AsyncCallback): void8+ + +Drains the playback buffer. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :---------------------- | :-------- | :--------------------------------------------------------------------------- | +| callback | AsyncCallback | Yes | Returns true if the buffer is drained successfully; returns false otherwise. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.drain((err, drained)=>{ + if (drained) { + console.log('Renderer drained.'); + } else { + console.error('Renderer drain failed'); + } +}) +``` + + +## audioRenderer.drain + +drain(): Promise8+ + +Drains the playback buffer. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :---------------- | :--------------------------------------------------------------------------- | +| Promise | Returns true if the buffer is drained successfully; returns false otherwise. | + +**Example** + +``` +var drained = await audioRenderer.drain(); +if (drained) { + console.log('Renderer drained'); +} else { + console.error('Renderer drain failed'); +} +``` + + +## audioRenderer.stop + +stop(callback: AsyncCallback): void8+ + +Stops rendering. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :---------------------- | :-------- | :------------------------------------------------------------------------------ | +| callback | AsyncCallback | Yes | Returns true if the rendering is stopped successfully; returns false otherwise. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.stop((err, stopped)=>{ + if (stopped) { + console.log('Renderer stopped.'); + } else { + console.error('Renderer stop failed'); + } +}) +``` + + +## audioRenderer.stop + +stop(): Promise8+ + +Stops rendering. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :---------------- | :------------------------------------------------------------------------------ | +| Promise | Returns true if the rendering is stopped successfully; returns false otherwise. | + +**Example** + +``` +var stopped = await audioRenderer.stop(); +if (stopped) { + console.log('Renderer stopped'); +} else { + console.error('Renderer stop failed'); +} +``` + + +## audioRenderer.release + +release(callback: AsyncCallback): void8+ + +Releases the renderer. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :---------------------- | :-------- | :------------------------------------------------------------------------------ | +| callback | AsyncCallback | Yes | Returns true if the renderer is released successfully; returns false otherwise. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.release((err, released)=>{ + if (released) { + console.log('Renderer released.'); + } else { + console.error('Renderer release failed'); + } +}) +``` + + + +## audioRenderer.release + +release(): Promise8+ + +Releases the renderer. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :---------------- | :------------------------------------------------------------------------------ | +| Promise | Returns true if the renderer is released successfully; returns false otherwise. | + +**Example** + +``` +var released = await audioRenderer.release(); +if (released) { + console.log('Renderer released'); +} else { + console.error('Renderer release failed'); +} +``` + + + +## audioRenderer.write + +write(buffer: ArrayBuffer, callback: AsyncCallback): void8+ + +Writes the buffer. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :---------------------- | :-------- | :--------------------------------------------------------------------------------------------------- | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback | Yes | Returns the number of bytes written if the operation is successful; returns an error code otherwise. | +| | | | | + +**Return value** + +None + +**Example** + +``` +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf, (err, writtenbytes)=>{ + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.log('Actual written bytes: ' + writtenbytes); + } +}) +``` + + +## audioRenderer.write + +write(buffer: ArrayBuffer): Promise8+ + +Writes the buffer. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :--------------- | :--------------------------------------------------------------------------------------------------- | +| Promise | Returns the number of bytes written if the operation is successful; returns an error code otherwise. | + +**Example** + +``` +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +let writtenbytes = await audioRenderer.write(buf); +if (writtenbytes < 0) { + console.error('write failed.'); +} else { + console.log('Actual written bytes: ' + writtenbytes); +} +``` + + + +## audioRenderer.getAudioTime + +getAudioTime(callback: AsyncCallback): void8+ + +Obtains the timestamp. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the timestamp. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.getAudioTime((err, timestamp)=>{ + console.log('Current timestamp: ' + timestamp); +}) +``` + + +## audioRenderer.getAudioTime + +getAudioTime(): Promise8+ + +Obtains the timestamp. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the timestamp. | + +**Example** + +``` +let timestamp = await audioRenderer.getAudioTime(); +console.log('Current timestamp: ' + timestamp); +``` + + +## audioRenderer.getBufferSize + +getBufferSize(callback: AsyncCallback): void8+ + +Obtains a reasonable minimum buffer size for rendering. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :--------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the buffer size. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.getBufferSize((err, bufferSize)=>{ + if (err) { + console.error('getBufferSize error'); + } +}) +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +``` + + +## audioRenderer.getBufferSize + +getBufferSize(): Promise8+ + +Obtains a reasonable minimum buffer size for rendering. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :--------------- | :-------------------------------------- | +| Promise | Promise used to return the buffer size. | + +**Example** + +``` +var bufferSize = await audioRenderer.getBufferSize(); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +``` + + +## audioRenderer.setRenderRate + +setRenderRate(rate: AudioRendererRate, callback: AsyncCallback): void8+ + +Sets the render rate. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| rate | AudioRendererRate | Yes | Audio render rate. | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err)=> { + if (err) { + console.error('Failed to set params'); + } else { + console.log('Callback invoked to indicate a successful render rate setting.'); + } +}) +``` + + +## audioRenderer.setRenderRate + +setRenderRate(rate: AudioRendererRate): Promise8+ + +Sets the render rate. This method uses a promise to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :---------------- | :-------- | :----------------- | +| rate | AudioRendererRate | Yes | Audio render rate. | + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +``` +await audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL); +``` + + +## audioRenderer.getRenderRate + +getRenderRate(callback: AsyncCallback): void8+ + +Obtains the current render rate. This method uses an asynchronous callback to return the result. + +**Parameters** +| Name | Type | Mandatory | Description | +| :------- | :-------------------------------- | :-------- | :--------------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the audio render rate. | +| | | | | + +**Return value** + +None + +**Example** + +``` +audioRenderer.getRenderRate((err, renderrate)=>{ + console.log('getRenderRate: ' + renderrate); +}) +``` + + +## audioRenderer.getRenderRate + +getRenderRate(): Promise8+ + +Obtains the current render rate. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :-------------------------- | :-------------------------------------------- | +| Promise | Promise used to return the audio render rate. | + +**Example** + +``` +let renderRate = await audioRenderer.getRenderRate(); +console.log('getRenderRate: ' + renderrate); +``` + + +## audioRenderer.on + +on(type: 'interrupt', callback: Callback): void8+ + +Listens for audio interrupt events. This method uses a callback to get interrupt events. The interrupt event is triggered when audio playback is interrupted. + +**Parameters** +| Name | Type | Mandatory | Description | +| :------- | :------------------------ | :-------- | :---------------------------------------------- | +| type | string | Yes | Type of the playback event to listen for. | +| callback | Callback | Yes | Callback used to listen for interrupt callback. | + +**Return value** + +None + +**Example** + +``` +audioRenderer.on('interrupt', (interruptEvent) => { + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.log('Force paused. Stop writing'); + isPlay = false; + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + console.log('Force stopped. Stop writing'); + isPlay = false; + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + console.log('Resume force paused renderer or ignore'); + startRenderer(); + break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.log('Choose to pause or ignore'); + pauseRenderer(); + break; + } + } +}) +``` + + + +## SystemSoundManager + + +## systemSoundManager.setSystemRingtoneUri + +setSystemRingtoneUri(context: Context, uri: string, type: RingtoneType, callback: AsyncCallback): void8+ + +Sets the system ringtone URI. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| context | Context | Yes | Current application context. | +| uri | string | Yes | Ringtone URI to be set. | +| type | RingtoneType | Yes | Ringtone type to be set. | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.setSystemRingtoneUri(null, '/data/media/Ringtonetone.wav', + audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err)=> { + if (err) { + console.error('Failed to setSystemRingtoneUri'); + } else { + console.log('Callback invoked to indicate a successful system ringtone URI setting.'); + } +}) +``` + + +## systemSoundManager.setSystemRingtoneUri + +setSystemRingtoneUri(context: Context, uri: string, type: RingtoneType): Promise8+ + +Sets the system ringtone URI. This method uses a promise to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------ | :----------- | :-------- | :--------------------------- | +| context | Context | Yes | Current application context. | +| uri | string | Yes | Ringtone URI to be set. | +| type | RingtoneType | Yes | Ringtone type to be set. | +| | | | | + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +``` +await systemSoundManager.setSystemRingtoneUri(null, '/data/media/Ringtone.wav', audio.RingtoneType.RINGTONE_TYPE_DEFAULT); +``` + + +## systemSoundManager.getSystemRingtoneUri + +getSystemRingtoneUri(context: Context, type: RingtoneType, callback: AsyncCallback): void8+ + +Obtains the system ringtone URI. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| context | Context | Yes | Current application context. | +| type | RingtoneType | Yes | Ringtone type to be obtained. | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.getSystemRingtoneUri(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err, ringtoneUri)=>{ + if (err) { + console.err('getSystemRingtoneUri failed'); + } else { + console.log('getSystemRingtoneUri success: ' + ringtoneUri); + } +}) +``` + + +## systemSoundManager.getSystemRingtoneUri + +getSystemRingtoneUri(context: Context, type: RingtoneType): Promise8+ + +Obtains the system ringtone URI. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :--------------- | :-------------------------------- | +| Promise | Promise used to the ringtone URI. | + +**Example** + +``` +let ringtoneUri = await systemSoundManager.getSystemRingtoneUri(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT); +if (ringtoneUri == '/data/media/Believer60s.wav') { + console.log('getSystemRingtoneUri success: ' + uri); +} else { + console.log('getSystemRingtoneUri fail: ' + uri); +} +``` + + +## systemSoundManager.getSystemRingtonePlayer + +getSystemRingtonePlayer(context: Context, type: RingtoneType, callback: AsyncCallback): void8+ + +Obtains the ringtone player. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------------------ | :-------- | :---------------------------------------- | +| context | Context | Yes | Current application context. | +| type | RingtoneType | Yes | Ringtone type to be obtained. | +| callback | AsyncCallback) | Yes | Ringtone player maintained in the system. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.getSystemRingtonePlayer(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err, ringtonePlayer)=>{ + if (err) { + console.err('getSystemRingtonePlayer failed'); + } else { + console.log('getSystemRingtonePlayer success: '); + } +}) +``` + + +## systemSoundManager.getSystemRingtonePlayer + +getSystemRingtonePlayer(context: Context, type: RingtoneType): Promise8+ + +Obtains the ringtone player. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :----------------------- | :--------------------------------------- | +| Promise | Promise used return the ringtone player. | + +**Example** + +``` +let ringtonePlayer = await systemSoundManager.getSystemRingtoneUri(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT); +``` + + +## systemSoundManager.setSystemNotificationUri + +setSystemNotificationUri(context: Context, uri: string, callback: AsyncCallback): void8+ + +Sets the system notification URI. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| context | Context | Yes | Current application context. | +| uri | string | Yes | System notification URI to be set. | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.setSystemNotificationUri(null, '/data/media/Notification.wav'), (err)=> { + if (err) { + console.error('Failed to setSystemNotificationUri'); + } else { + console.log('Callback invoked to indicate a successful system notification URI setting.'); + } +}) +``` + + +## systemSoundManager.setSystemNotificationUri + +setSystemNotificationUri(context: Context, uri: string): Promise8+ + +Sets the system notification URI. This method uses a promise to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------ | :------ | :-------- | :--------------------------------- | +| context | Context | Yes | Current application context. | +| uri | string | Yes | System notification URI to be set. | +| | | | | + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +``` +await systemSoundManager.setSystemNotificationUri(null, '/data/media/Notification.wav'); +``` + + +## systemSoundManager.getSystemNotificationUri + +getSystemNotificationUri(context: Context, callback: AsyncCallback): void8+ + +Obtains the system notification URI. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :--------------------------------------------------- | +| context | Context | Yes | Current application context. | +| callback | AsyncCallback | Yes | Callback used to return the system notification URI. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.getSystemNotificationUri(null, (err, notificationUri)=>{ + if (err) { + console.err('getSystemNotificationUri failed'); + } else { + console.log('getSystemNotificationUri success: ' + notificationUri); + } +}) +``` + + +## systemSoundManager.getSystemNotificationUri + +getSystemNotificationUri(context: Context): Promise8+ + +Obtains the system notification URI. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :--------------- | :-------------------------------------------------- | +| Promise | Promise used to return the system notification URI. | + +**Example** + +``` +let notificationUri = await systemSoundManager.getSystemNotificationUri(null); +console.log('getSystemNotificationUri : ' + uri); +``` + + +## systemSoundManager.setSystemAlarmUri + +setSystemAlarmUri(context: Context, uri: string, callback: AsyncCallback): void8+ + +Sets the system alarm URI. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| context | Context | Yes | Current application context. | +| uri | string | Yes | System alarm URI to be set. | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.setSystemAlarmUri(null, '/data/media/Alarm.wav'), (err)=> { + if (err) { + console.error('Failed to setSystemAlarmUri'); + } else { + console.log('Callback invoked to indicate a successful system alarm URI setting.'); + } +}) +``` + + +## systemSoundManager.setSystemAlarmUri + +setSystemAlarmUri(context: Context, uri: string): Promise8+ + +Sets the system alarm URI. This method uses a promise to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------ | :------ | :-------- | :--------------------------- | +| context | Context | Yes | Current application context. | +| uri | string | Yes | System alarm URI to be set. | +| | | | | + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +``` +await systemSoundManager.setSystemAlarmUri(null, '/data/media/Alarm.wav'); +``` + + +## systemSoundManager.getSystemAlarmUri + +getSystemAlarmUri(context: Context, callback: AsyncCallback): void8+ + +Obtains the system alarm URI. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :-------------------------------------------- | +| context | Context | Yes | Current application context. | +| callback | AsyncCallback | Yes | Callback used to return the system alarm URI. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.getSystemAlarmUri(null, (err, alarmUri)=>{ + if (err) { + console.err('getSystemAlarmUri failed'); + } else { + console.log('getSystemAlarmUri success: ' + alarmUri); + } +}) +``` + + +## systemSoundManager.getSystemAlarmUri + +getSystemAlarmUri(context: Context): Promise8+ + +Obtains the system alarm URI. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :--------------- | :------------------------------------------- | +| Promise | Promise used to return the system alarm URI. | + +**Example** + +``` +let alarmUri = await systemSoundManager.getSystemAlarmUri(null); +console.log('getSystemAlarmUri success: ' + alarmUri); +``` + + +# RingtonePlayer + +## ringtonePlayer.state + +readonly state: AudioState 8+ + +Defines the current ringtone player state. + +| Name | Type | Readable | Writable | Description | +| :---- | :--------- | :------- | :------- | :--------------------- | +| state | AudioState | Yes | No | Ringtone player state. | + +**Example** + +``` +systemSoundManager.getSystemRingtonePlayer(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err, ringtonePlayer)=>{ + if (err) { + console.err('getSystemRingtonePlayer failed'); + return; + } else { + console.log('getSystemRingtonePlayer success'); + } +}); + +var state = ringtonePlayer.state; +``` + + +## ringtonePlayer.getTitle + +getTitle(callback: AsyncCallback): void8+ + +Obtains the title of the ringtone. This method uses an asynchronous callback to return the result. + +**Parameters** +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the title of the ringtone. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.getSystemRingtonePlayer(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err, ringtonePlayer)=>{ + if (err) { + console.err('getSystemRingtonePlayer failed'); + return; + } else { + console.log('getSystemRingtonePlayer success'); + } +}); + +ringtonePlayer.getTitle((err, title)=>{ + if (err) { + console.err('getTitle failed'); + } else { + console.log('getTitle success: ' + title); + } +}) +``` + + +## ringtonePlayer.getTitle + +getTitle(): Promise8+ + +Obtains the title of the ringtone. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :--------------- | :------------------------------------------------ | +| Promise | Promise used to return the title of the ringtone. | + +**Example** + +``` +let ringtonePlayer = await systemSoundManager.getSystemRingtoneUri(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT); +let title = await ringtonePlayer.getTitle(); +``` + + +## ringtonePlayer.getAudioRendererInfo + +getAudioRendererInfo(callback: AsyncCallback): void8+ + +Obtains the audio renderer information. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :-------------------------------- | :-------- | :------------------------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the audio renderer information. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.getSystemRingtonePlayer(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err, ringtonePlayer)=>{ + if (err) { + console.err('getSystemRingtonePlayer failed'); + return; + } else { + console.log('getSystemRingtonePlayer success: '); + } +}); + +ringtonePlayer.getAudioRendererInfo((err, rendererInfo)=>{ + if (err) { + console.err('getAudioRendererInfo failed'); + } else { + console.log('getAudioRendererInfo success'); + } +}); +``` + + +## ringtonePlayer.getAudioRendererInfo + +getAudioRendererInfo(): Promise8+ + +Obtains the audio renderer information. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :-------------------------- | :----------------------------------------------------- | +| Promise | Promise used to return the audio renderer information. | + +**Example** + +``` +let ringtonePlayer = await systemSoundManager.getSystemRingtoneUri(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT); +let rendererInfo = await ringtonePlayer.getAudioRendererInfo(); +``` + + +## ringtonePlayer.configure + +configure(options: RingtoneOptions, callback: AsyncCallback): void8+ + +Configures ringtone options. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| options | RingtoneOptions | Yes | Ringtone options. | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +systemSoundManager.getSystemRingtonePlayer(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT, (err, ringtonePlayer)=>{ + if (err) { + console.err('getSystemRingtonePlayer failed'); + return; + } else { + console.log('getSystemRingtonePlayer success: '); + } +}); + +let ringtoneOptions = { + volume: 1, + loop: false +}; + +ringtonePlayer.configure(ringtoneOptions, (err)=> { + if (err) { + console.error('Failed to configure ringtone options'); + } else { + console.log('Callback invoked to indicate a successful ringtone options configuration.'); + } +}) +``` + + +## ringtonePlayer.configure + +configure(options: RingtoneOptions): Promise8+ + +Configures ringtone options. This method uses a promise to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------ | :-------------- | :-------- | :---------------- | +| options | RingtoneOptions | Yes | Ringtone options. | +| | | | | + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +``` +let ringtonePlayer = await systemSoundManager.getSystemRingtoneUri(null, audio.RingtoneType.RINGTONE_TYPE_DEFAULT); +let ringtoneOptions = { + volume: 1, + loop: false +}; + +await ringtonePlayer.configure(ringtoneOptions); +``` + + +## ringtonePlayer.start + +start(callback: AsyncCallback): void8+ + +Starts playing ringtone. This method uses a callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +ringtonePlayer.start((err)=> { + if (err) { + console.error('Failed to start playing ringtone'); + } else { + console.log('Ringtone start playing successfully.'); + } +}) +``` + + +## ringtonePlayer.start + +start(): Promise8+ + +Starts playing ringtone. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +``` +await ringtonePlayer.start(); +``` + + +## ringtonePlayer.stop + +stop(callback: AsyncCallback): void8+ + +Stops playing ringtone. This method uses a callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +ringtonePlayer.stop((err)=> { + if (err) { + console.error('Failed to stop playing ringtone'); + } else { + console.log('Ringtone stop playing successfully.'); + } +}) +``` + + +## ringtonePlayer.stop + +stop(): Promise8+ + +Stops playing ringtone. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +``` +await ringtonePlayer.stop(); +``` + + +## ringtonePlayer.release + +release(callback: AsyncCallback): void8+ + +Releases ringtone player resources. This method uses a callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | +| | | | | + +**Return value** + +None + +**Example** + +``` +ringtonePlayer.release((err)=> { + if (err) { + console.error('Failed to release ringtone player resource'); + } else { + console.log('Release ringtone player resource successfully.'); + } +}) +``` + + +## ringtonePlayer.release + +release(): Promise8+ + +Releases ringtone player resource. This method uses a promise to return the result. + +**Parameters** + +None + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +``` +await ringtonePlayer.release(); +``` diff --git a/en/application-dev/reference/apis/js-apis-basic-features-animator.md b/en/application-dev/reference/apis/js-apis-basic-features-animator.md new file mode 100644 index 0000000000000000000000000000000000000000..b259fe732e26348601c1d7a8e8a5002abe2a8a2b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-animator.md @@ -0,0 +1,479 @@ +# Animation + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +**requestAnimationFrame**: none + +**cancelAnimationFrame**: none + +**createAnimator**: + +``` +import animator from '@ohos.animator'; +``` + +## Required Permissions + +None + +## requestAnimationFrame + +requestAnimationFrame\(handler\[, \[ ...args\]\]\): number + +Requests an animation frame. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

handler

+

Function

+

Yes

+

Handler used to request a frame. When requestAnimationFrame calls the handler, the timestamp is passed to the first parameter to indicate the time when requestAnimationFrame starts to execute the callback.

+

...args

+

Array<any>

+

No

+

Additional parameter, which is passed to the handler as a parameter during function callback.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Request ID.

+
+ +- Example + + ``` + +
+ +
+ ``` + + ``` + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 100%; + } + .btn{ + width: 300px; + margin-top: 40px; + } + ``` + + ``` + /* xxx.js */ + export default { + data: { + requestId: 0, + startTime: 0, + }, + beginAnimation() { + cancelAnimationFrame(this.requestId); + this.requestId = requestAnimationFrame(this.runAnimation); + }, + runAnimation(timestamp) { + if (this.startTime == 0) { + this.startTime = timestamp; + } + var elapsed = timestamp - this.startTime; + if (elapsed < 500) { + console.log('callback handler timestamp: ' + timestamp); + this.requestId = requestAnimationFrame(this.runAnimation); + } + } + } + ``` + + +## cancelAnimationFrame + +cancelAnimationFrame\(requestId: number\): void + +Cancels the animation frame request. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

requestId

+

number

+

Yes

+

ID of the frame request.

+
+ +- Example + + ``` + +
+ + +
+ ``` + + ``` + /* xxx.css */ + .container { + flex-direction: column; + justify-content: center; + align-items: center; + width: 100%; + height: 100%; + } + .btn{ + width: 300px; + margin-top: 40px; + } + ``` + + ``` + /* xxx.js */ + export default { + data: { + requestId: 0, + startTime: 0, + }, + beginAnimation() { + cancelAnimationFrame(this.requestId); + this.requestId = requestAnimationFrame(this.runAnimation); + }, + runAnimation(timestamp) { + if (this.startTime == 0) { + this.startTime = timestamp; + } + var elapsed = timestamp - this.startTime; + if (elapsed < 500) { + console.log('callback handler timestamp: ' + timestamp); + this.requestId = requestAnimationFrame(this.runAnimation); + } + }, + stopAnimation() { + cancelAnimationFrame(this.requestId); + } + } + ``` + + +## createAnimator + +createAnimator\(options\[...\]\): void + +Creates an animation object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

options

+

Object

+

Yes

+

Attributes of the Animator to be created. For details, see the options table.

+
+ +- Description of options + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

duration

+

number

+

No

+

Duration for playing an animation, in milliseconds. The default value is 0.

+

easing

+

string

+

No

+

Animation easing curve. The default value is ease.

+

delay

+

number

+

No

+

Animation delay duration, in milliseconds. The default value is 0, indicating that there is no delay.

+

fill

+

string

+

No

+

Animation start/stop mode. The default value is none. For details, see animation-fill-mode.

+

direction

+

string

+

No

+

Animation playback mode. The default value is normal. For details, see animation-direction.

+

iterations

+

number

+

No

+

Number of times that an animation is played. The default value is 1. If this parameter is set to 0, the animation is not played. If this parameter is set to -1, the animation is played for an unlimited number of times.

+

begin

+

number

+

No

+

Start point of the animation easing. If this parameter is not set, the default value 0 is used.

+

end

+

number

+

No

+

End point of the animation easing. If this parameter is not set, the default value 1 is used.

+
+ +- animator interfaces + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

update

+

options

+

Updates the animation parameters. The input parameters are the same as those of createAnimator.

+

play

+

-

+

Starts an animation.

+

finish

+

-

+

Ends an animation.

+

pause

+

-

+

Pauses an animation.

+

cancel

+

-

+

Cancels an animation.

+

reverse

+

-

+

Reverses an animation.

+
+ + +- **animator** supported events: + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

frame

+

number

+

The frame is requested.

+

cancel

+

-

+

The animation is forcibly canceled.

+

finish

+

-

+

The animation playback is complete.

+

repeat

+

-

+

The animation replays.

+
+ +- Example + + ``` + +
+
+
+
+ ``` + + ``` + // js + export default { + data : { + divWidth: 200, + divHeight: 200, + animator: null + }, + onInit() { + var options = { + duration: 1500, + easing: 'friction', + fill: 'forwards', + iterations: 2, + begin: 200.0, + end: 400.0 + }; + this.animator = animator.createAnimator(options); + }, + Show() { + var options1 = { + duration: 2000, + easing: 'friction', + fill: 'forwards', + iterations: 1, + begin: 200.0, + end: 400.0 + }; + this.animator.update(options1); + var _this = this; + this.animator.onframe = function(value) { + _this.divWidth = value; + _this.divHeight = value; + }; + this.animator.play(); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-app-context.md b/en/application-dev/reference/apis/js-apis-basic-features-app-context.md new file mode 100644 index 0000000000000000000000000000000000000000..01ee2571a8fb5275a2099acbca13458e8a561e32 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-app-context.md @@ -0,0 +1,89 @@ +# Application Context + +## Module to Import + +``` +import app from '@system.app'; +``` + +## Required Permissions + +None + +## app.getInfo + +getInfo\(\): <[AppResponse](#t3e93239d9b134b80957bcdd4acb05291)\> + +Obtains the declared information in the **config.json** file of an application. + +- Return values + + **Table 1** AppResponse + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

appID6+

+

string

+

Bundle name of the application. It uniquely identifies the application.

+

appName

+

string

+

Application name

+

versionName

+

string

+

Application version name

+

versionCode

+

number

+

Application version

+
+ +- Example + + ``` + export default { + getInfo(){ + var info = app.getInfo(); + console.log(JSON.stringify(info)); + } + } + ``` + + +## app.terminate + +terminate\(\): void + +Destroys the current ability. + +- Example + + ``` + export default { + terminate(){ + app.terminate(); + }} + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-configuration.md b/en/application-dev/reference/apis/js-apis-basic-features-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..4980558fae443cc47c6931e30c73d26fc77ef5d0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-configuration.md @@ -0,0 +1,77 @@ +# Application Configuration + +## Module to Import + +``` +import configuration from '@system.configuration'; +``` + +## Required Permissions + +None + +## configuration.getLocale + +getLocale\(\): <[LocaleResponse](#table1544853546)\> + +Obtains the current locale of the application, which is the same as the system locale. + +- Return values + + **Table 1** LocaleResponse + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

language

+

string

+

Current language of the application, for example, zh.

+

countryOrRegion

+

string

+

Country or region, for example, CN.

+

dir

+

string

+

Text layout direction. Available values are as follows:

+
  • ltr: The text direction is from left to right.
  • rtl: The text direction is from right to left.
+

unicodeSetting5+

+

string

+

Unicode key set determined by the locale.

+

For example, {"nu":"arab"} indicates that the current locale uses Arabic numerals.

+

If the current locale does not have a specific key set, an empty set is returned.

+
+ +- Example + + ``` + export default { + getLocale() { + const localeInfo = configuration.getLocale(); + console.info(localeInfo.language); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-logs.md b/en/application-dev/reference/apis/js-apis-basic-features-logs.md new file mode 100644 index 0000000000000000000000000000000000000000..864ce3ecc2e4ff92feebd0079fb597d8d55ee264 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-logs.md @@ -0,0 +1,188 @@ +# Console Logs + +## Module to Import + +No module is required. + +## Required Permissions + +None + +## console.debug + +debug\(message: string\): void + +Prints debug logs. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## console.log + +log\(message: string\): void + +Prints debug logs. + +- Parameter + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## console.info + +info\(message: string\): void + +Prints info-level logs. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## console.warn + +warn\(message: string\): void + +Prints warn-level logs. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## console.error + +error\(message: string\): void + +Prints error-level logs. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to print.

+
+ + +## Example + +``` +export default { + clickConsole(){ + var versionCode = 1; + console.info('Hello World. The current version code is ' + versionCode); + console.log(`versionCode: ${versionCode}`); + // The following is supported since API version 6. + console.log('versionCode:%d.', versionCode); + } +} +``` + +Switch to the **HiLog** window at the bottom of HUAWEI DevEco Studio. Specifically, select the current device and process, set the log level to **Info**, and enter **Hello World** in the search box. Logs that meet the search criteria are displayed, as shown in the following figure. + +![](figures/log.png) + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-pop-up.md b/en/application-dev/reference/apis/js-apis-basic-features-pop-up.md new file mode 100644 index 0000000000000000000000000000000000000000..eefc43e94dd0fcedc89e03850d2b431b6d8dd0b1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-pop-up.md @@ -0,0 +1,322 @@ +# Pop-up Window + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Module to Import + +``` +import prompt from '@system.prompt'; +``` + +## Required Permissions + +None + +## prompt.showToast + +showToast\(Object\): void + +Displays the toast dialog box. + +- Parameter + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Text to display.

+

duration

+

number

+

No

+

Duration of the toast dialog box. The default value is 1500. The recommended value ranges from 1500 ms to 10000 ms.

+
NOTE:

A value less than 1500 is automatically changed to 1500. The maximum value is 10000 ms.

+
+

[bottom]5+

+

<length>

+

No

+

Distance between the dialog border and the bottom of the screen.

+
NOTE:

This parameter is only supported on phones and tablets.

+
+
+ +- Example + + ``` + export default { + showToast() { + prompt.showToast({ + message: 'Message Info', + duration: 2000, + }); + } + } + ``` + + +## prompt.showDialog + +showDialog\(\): void + +Displays the dialog box. + +- Parameter + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

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.

+

success

+

Function

+

No

+

Called when the dialog box is displayed. For the return value, see return values of the success callback.

+

cancel

+

Function

+

No

+

Called when the operation is cancelled.

+

complete

+

Function

+

No

+

Called when the dialog box is closed.

+
+ + Return values of the **success** callback + + + + + + + + + + + + +

Parameter

+

Type

+

Description

+

index

+

number

+

Index of the selected button in the buttons array

+
+ +- Example + + ``` + export default { + showDialog() { + prompt.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button', + color: '#666666', + }, + ], + success: function(data) { + console.log('dialog success callback,click button : ' + data.index); + }, + cancel: function() { + console.log('dialog cancel callback'); + }, + }); + } + } + ``` + + +## prompt.showActionMenu6+ + +showActionMenu\(Object\): void + +Displays the operation menu. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

title

+

string

+

No

+

Title of the text to display.

+

buttons

+

Array

+

Yes

+

Array of buttons in the dialog box. The array structure is {text:'button', color: '#666666'}. One to six buttons are supported. If there are more than six buttons, the pop-up window will not be displayed.

+

success

+

(data: TapIndex) => void

+

No

+

Called when the operation is successful.

+

cancel

+

() => void

+

No

+

Called when the operation fails.

+

complete

+

() => void

+

No

+

Called when the operation is complete.

+
+ + **Table 1** TapIndex + + + + + + + + + + + + +

Name

+

Type

+

Description

+

tapIndex

+

number

+

Index of the selected button in the buttons array, starting from 0.

+
+ +- Example + + ``` + export default { + showActionMenu() { + prompt.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ], + success: function(data) { + console.log('Operation succeeded. Click button: ' + data.tapIndex); + }, + fail: function(data) { + console.log('Operation failed' + data.errMsg); + }, + }); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-routes.md b/en/application-dev/reference/apis/js-apis-basic-features-routes.md new file mode 100644 index 0000000000000000000000000000000000000000..b11f4372be2e27168601d9257285065649be1ad2 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-routes.md @@ -0,0 +1,492 @@ +# Page Routing + +>![](../../public_sys-resources/icon-notice.gif) **NOTICE:** +>Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase. + +## Module to Import + +``` +import router from '@system.router'; +``` + +## Required Permissions + +None. + +## router.push + +push\(Object\): void + +Navigates to a specified page in the application based on the page URL and parameters. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

uri

+

string

+

Yes

+

URI of the destination page, in either of the following formats:

+
  • Absolute path of the page. The value is available in the pages list in the config.json file, for example:
    • pages/index/index
    • pages/detail/detail
    +
  • Particular path. If the URI is a slash (/), the home page is displayed.
+

params

+

Object

+

No

+

Data that needs to be passed to the destination page during navigation. After the destination page is displayed, it can use the passed data, for example, this.data1 (data1 is a key in params). If there is the same key (for example, data1) on the destination page, the passed data1 value will overwrite the original value on the destination page.

+
+ +- Example + + ``` + // Example code for the current page + export default { + pushPage() { + router.push({ + uri: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }); + } + } + // Example code for the routerpage2 page + export default { + data: { + data1: 'default', + data2: { + data3: [1, 2, 3] + } + }, + onInit() { + console.info('showData1:' + this.data1); + console.info('showData3:' + this.data2.data3); + } + } + ``` + + >![](../../public_sys-resources/icon-note.gif) **NOTE:** + >The page routing stack supports a maximum of 32 pages. + + +## router.replace + +replace\(Object\): void + +Replaces the current page with another one in the application and destroys the current page. + +- Parameter + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

uri

+

string

+

Yes

+

URI of the destination page, in either of the following formats:

+
  • Absolute path of the page. The value is available in the pages list in the config.json file, for example:
    • pages/index/index
    • pages/detail/detail
    +
  • Particular path. If the URI is a slash (/), the home page is displayed.
+

params

+

Object

+

No

+

Data that needs to be passed to the destination page during navigation. After the destination page is displayed, it can use the passed data, for example, this.data1 (data1 is a key in params). If there is the same key (for example, data1) on the destination page, the passed data1 value will overwrite the original value on the destination page.

+
+ +- Example + + ``` + // Example code for the current page + export default { + replacePage() { + router.replace({ + uri: 'pages/detail/detail', + params: { + data1: 'message', + }, + }); + } + } + // Example code for the detail page + export default { + data: { + data1: 'default' + }, + onInit() { + console.info('showData1:' + this.data1) + } + } + ``` + + +## router.back + +back\(Object\): void + +Returns to the previous page or a specified page. + +- Parameter + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

uri

+

string

+

No

+

URI of the page to return to. If the specified page does not exist in the page stack, the app does not respond. If this parameter is not set, the app returns to the previous page.

+
+ +- Example + + ``` + // index page + export default { + indexPushPage() { + router.push({ + uri: 'pages/detail/detail', + }); + } + } + + // detail page + export default { + detailPushPage() { + router.push({ + uri: 'pages/mall/mall', + }); + } + } + + // Navigate from the mall page to the detail page through router.back(). + export default { + mallBackPage() { + router.back(); + } + } + // Navigate from the detail page to the index page through router.back(). + export default { + defaultBack() { + router.back(); + } + } + // Return to the detail page through router.back(). + export default { + backToDetail() { + router.back({uri:'pages/detail/detail'}); + } + } + ``` + + >![](../../public_sys-resources/icon-note.gif) **NOTE:** + >In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. + + +## router.clear + +clear\(\): void + +Clears all historical pages and retains only the current page at the top of the stack. + +- Example + + ``` + export default { + clearPage() { + router.clear(); + } + } + ``` + + +## router.getLength + +getLength\(\): string + +Obtains the number of pages in the current stack. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Number of pages in the stack. The maximum value is 32.

+
+ +- Example + + ``` + export default { + getLength() { + var size = router.getLength(); + console.log('pages stack size = ' + size); + } + } + ``` + + +## router.getState + +getState\(\): <[RouterState](#tf9e3eb9ef0aa4d9880f996fe6afa6d1b)\> + +Obtains information about the current page state. + +- Return values + + **Table 1** RouterState + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

index

+

number

+

Index of the current page in the stack.

+
NOTE:

The index starts from 1 from the bottom to the top of the stack.

+
+

name

+

string

+

Name of the current page, that is, the file name.

+

path

+

string

+

Path of the current page.

+
+ +- Example + + ``` + export default { + getState() { + var page = router.getState(); + console.log('current index = ' + page.index); + console.log('current name = ' + page.name); + console.log('current path = ' + page.path); + } + } + ``` + + +## router.enableAlertBeforeBackPage6+ + +enableAlertBeforeBackPage\(Object\): void + +Enables the display of a confirm dialog for returning to the previous page. + +- Parameter + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

string

+

Yes

+

Content of the confirm dialog.

+

success

+

() => void

+

No

+

Called when the operation is successful.

+

fail

+

() => void

+

No

+

Called when the operation fails.

+

complete

+

() => void

+

No

+

Called when the operation is complete.

+
+ +- Example + + ``` + export default { + enableAlertBeforeBackPage() { + router.enableAlertBeforeBackPage({ + message: 'Message Info', + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } + } + ``` + + +## router.disableAlertBeforeBackPage6+ + +disableAlertBeforeBackPage\(Object\): void + +Disables the display of a confirm dialog for returning to the previous page. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

success

+

() => void

+

No

+

Called when the operation is successful.

+

fail

+

() => void

+

No

+

Called when the operation fails.

+

complete

+

() => void

+

No

+

Called when the operation is complete.

+
+ +- Example + + ``` + export default { + disableAlertBeforeBackPage() { + router.disableAlertBeforeBackPage({ + success: function() { + console.log('success'); + }, + fail: function() { + console.log('fail'); + }, + }); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-basic-features-timer.md b/en/application-dev/reference/apis/js-apis-basic-features-timer.md new file mode 100644 index 0000000000000000000000000000000000000000..a7265c4972c52318d2f624939e935e56abdb2e63 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-basic-features-timer.md @@ -0,0 +1,261 @@ +# Timer + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Module to Import + +None + +## Required Permissions + +None + +## setTimeout + +setTimeout\(handler\[,delay\[, ...args\]\]\): number + +Sets a timer for the system to call a function after the timer goes off. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

handler

+

Function

+

Yes

+

Function to be called after the timer goes off.

+

delay

+

number

+

No

+

Number of milliseconds delayed before the execution. If this parameter is left empty, the default value 0 is used, which means that the execution starts immediately or as soon as possible.

+

...args

+

Array<any>

+

No

+

Additional parameter to pass to the handler after the timer goes off.

+
+ +- Return Value + + + + + + + + + + +

Type

+

Description

+

number

+

Timer ID.

+
+ +- Example + + ``` + export default { + setTimeOut() { + var timeoutID = setTimeout(function() { + console.log('delay 1s'); + }, 1000); + } + } + ``` + + +## clearTimeout + +clearTimeout\(timeoutID: number\): void + +Cancels the timer created via **setTimeout\(\)**. + +- Parameter + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timeoutID

+

number

+

Yes

+

ID of the timer to cancel, which is returned by setTimeout()

+
+ +- Example + + ``` + export default { + clearTimeOut() { + var timeoutID = setTimeout(function() { + console.log('do after 1s delay.'); + }, 1000); + clearTimeout(timeoutID); + } + } + ``` + + +## setInterval + +setInterval\(handler\[, delay\[, ...args\]\]\): number + +Sets a repeating timer for the system to repeatedly call a function at a fixed interval. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

handler

+

Function

+

Yes

+

Function to be called repeatedly

+

delay

+

number

+

No

+

Number of milliseconds delayed before the execution

+

...args

+

Array<any>

+

No

+

Additional parameter to pass to the handler after the timer goes off

+
+ +- Return Value + + + + + + + + + + +

Type

+

Description

+

number

+

ID of the repeated timer.

+
+ +- Example + + ``` + export default { + setInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + } + } + ``` + + +## clearInterval + +clearInterval\(intervalID: number\): void + +Cancels the repeating timer set via **setInterval\(\)**. + +- Parameter + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

intervalID

+

number

+

Yes

+

ID of the repeating timer to cancel, which is returned by setInterval().

+
+ +- Example + + ``` + export default { + clearInterval() { + var intervalID = setInterval(function() { + console.log('do very 1s.'); + }, 1000); + clearInterval(intervalID); + } + } + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md new file mode 100644 index 0000000000000000000000000000000000000000..64b8115fac736b6f41a5825b8f5a89bf5ed3e21c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -0,0 +1,273 @@ +# Battery Info + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import batteryInfo from '@ohos.batteryInfo'; +``` + +## Attributes + +Describes battery information. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

batterySOC

+

number

+

Yes

+

No

+

Battery state of charge (SoC) of the current device.

+

chargingStatus

+

BatteryChargeState

+

Yes

+

No

+

Battery charging state of the current device.

+

healthStatus

+

BatteryHealthState

+

Yes

+

No

+

Battery health state of the current device.

+

pluggedType

+

BatteryPluggedType

+

Yes

+

No

+

Charger type of the current device.

+

voltage

+

number

+

Yes

+

No

+

Battery voltage of the current device.

+

technology

+

string

+

Yes

+

No

+

Battery technology of the current device.

+

batteryTemperature

+

number

+

Yes

+

No

+

Battery temperature of the current device.

+

isBatteryPresent7+

+

boolean

+

Yes

+

No

+

Whether the battery is supported or present.

+
+ +- Example + + ``` + import batteryInfo from '@ohos.batteryInfo'; + var batterySoc = batteryInfo.batterySOC; + ``` + + +## BatteryPluggedType + +Enumerates charger types. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

NONE

+

0

+

Unknown type

+

AC

+

1

+

AC charger

+

USB

+

2

+

USB charger

+

WIRELESS

+

3

+

Wireless charger

+
+ +## BatteryChargeState + +Enumerates charging states. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

NONE

+

0

+

Unknown state.

+

ENABLE

+

1

+

The battery is being charged.

+

DISABLE

+

2

+

The battery is not being charged.

+

FULL

+

3

+

The battery is fully charged.

+
+ +## BatteryHealthState + +Enumerates battery health states. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

UNKNOWN

+

0

+

Unknown state.

+

GOOD

+

1

+

The battery is in the healthy state.

+

OVERHEAT

+

2

+

The battery is overheated.

+

OVERVOLTAGE

+

3

+

The battery voltage is over high.

+

COLD

+

4

+

The battery temperature is low.

+

DEAD

+

5

+

The battery is dead.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md new file mode 100644 index 0000000000000000000000000000000000000000..a4c533575f626f9b7c4dffb968da7809e0fe84e8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -0,0 +1,50 @@ +# Brightness + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import brightness from '@ohos.brightness'; +``` + +## brightness.setValue + +setValue\(value: number\) + +Sets the screen brightness. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

number

+

Yes

+

Brightness value, ranging from 0 to 255

+
+ +- Example + + ``` + import brightness from '@ohos.brightness.d.ts'; + brightness.setValue(128); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md new file mode 100644 index 0000000000000000000000000000000000000000..25c7658cd4e43e13bed0a32245877b5a228ee70b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -0,0 +1,198 @@ +# Performance Tracing + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import bytrace from '@ohos.bytrace'; +``` + +## Required Permissions + +None + +## bytrace.startTrace + +startTrace\(name: string, taskId: number, expectedTime?: number\): void + +Starts a trace of a task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the trace task to start.

+

taskId

+

number

+

Yes

+

Task ID.

+

expectedTime

+

number

+

No

+

Expected duration of the trace, in ms.

+
+ + >![](../../public_sys-resources/icon-note.gif) **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 **taskId**s 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 + + ``` + bytrace.startTrace("myTestFunc", 1); + bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is 5 ms. + ``` + + +## bytrace.finishTrace + +finishTrace\(name: string, taskId: number\): void + +Stops a trace task. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the trace task to stop.

+

taskId

+

number

+

Yes

+

Task ID.

+
+ + >![](../../public_sys-resources/icon-note.gif) **NOTE:** + >To stop a trace task, the values of **name** and **taskId** in **finishTrace** must be the same as those in **startTrace**. + +- Example + + ``` + bytrace.finishTrace("myTestFunc", 1); + ``` + + ``` + // Start track tasks with the same name concurrently. + bytrace.startTrace("myTestFunc", 1); + ...... // Service flow + bytrace.startTrace ("myTestFunc", 2); // The second trace task starts while the first task is still running. The first and second tasks have the same name but different task IDs. + ...... // Service flow + bytrace.finishTrace("myTestFunc", 1); + ...... // Service flow + bytrace.finishTrace("myTestFunc", 2); + ``` + + ``` + // Start track tasks with the same name at different times. + bytrace.startTrace("myTestFunc", 1); + ...... // Service flow + bytrace.finishTrace("myTestFunc", 1); // The first trace task ends. + ...... // Service flow + bytrace.startTrace("myTestFunc", 1); // The second trace task starts after the first task ends. The two tasks have the same name and task ID. + ...... // Service flow + bytrace.finishTrace("myTestFunc", 1); + ``` + + +## bytrace.traceByValue + +traceByValue\(name: string, value: number\): void + +Traces the value changes of a variable. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the variable to trace.

+

value

+

number

+

Yes

+

Value of the variable to trace.

+
+ +- Example + + ``` + let traceCount = 3; + bytrace.traceByValue("myTestCount", traceCount); + ...... + traceCount = 5; + bytrace.traceByValue("myTestCount", traceCount); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index 16d5ceb279a670886be407b0f02e0b9a6a0b6e84..14584a1f0e3c2f9c700bb8afb0bee7168b867f24 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -2,9 +2,7 @@ >**Note:** > ->- The APIs of this module are supported since API version 6. -> ->- APIs marked with 7+ are supported since API version 7. +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md new file mode 100644 index 0000000000000000000000000000000000000000..e3f7238a1279728877203071f3e2bfd5b391fa2e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -0,0 +1,871 @@ +# CommonEvent Module + +**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. + +## Applicable Devices + +| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| +| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | +| CommonEvent.publish(event: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| +| CommonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| +| CommonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| +| CommonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Yes| Yes| Yes| Yes| No| +| CommonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| +| CommonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\) | Yes| Yes| Yes| Yes| No| + +## 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_SHUTDOWN | usual.event.SHUTDOWN | N/A| +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | N/A| +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | N/A| +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | N/A| +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | N/A| +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | N/A| +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | N/A| +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | N/A| +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | N/A| +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | N/A| +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | N/A| +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | N/A| +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | N/A| +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | N/A| +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | N/A| +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | N/A| +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | N/A| +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | N/A| +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | N/A| +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | N/A| +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | N/A| +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | N/A| +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | N/A| +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | N/A| +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | N/A| +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | N/A| +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | N/A| +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | N/A| +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | N/A| +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | N/A| +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | N/A| +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | N/A| +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | N/A| +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | N/A| +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | N/A| +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | N/A| +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | N/A| +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | N/A| +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | N/A| +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | N/A| +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | N/A| +| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_USERS | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | N/A| +| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | N/A| +| COMMON_EVENT_HWID_LOGIN | common.event.HWID_LOGIN | N/A| +| COMMON_EVENT_HWID_LOGOUT | common.event.HWID_LOGOUT | N/A| +| COMMON_EVENT_HWID_TOKEN_INVALID | common.event.HWID_TOKEN_INVALID | N/A| +| COMMON_EVENT_HWID_LOGOFF | common.event.HWID_LOGOFF | N/A| +| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | N/A| +| 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 | N/A| +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | N/A| +| 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_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_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | N/A| +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | N/A| +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | N/A| +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | N/A| +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | N/A| +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | N/A| +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | N/A| +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | N/A| +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | N/A| +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | N/A| +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | N/A| +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | N/A| +| COMMON_EVENT_CHARGING | usual.event.CHARGING | N/A| +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | N/A| +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | N/A| +| 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_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | N/A| +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | N/A| +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | N/A| +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | N/A| +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | N/A| +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | N/A| +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | N/A| +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | N/A| +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | N/A| +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | N/A| +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | N/A| +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | N/A| +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | N/A| +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | N/A| +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | N/A| +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | N/A| +| 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_STORAGEor ohos.permission.READ_USER_STORAGE | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.WRITE_USER_STORAGEor ohos.permission.READ_USER_STORAGE | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.WRITE_USER_STORAGEor ohos.permission.READ_USER_STORAGE | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.WRITE_USER_STORAGEor ohos.permission.READ_USER_STORAGE | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | N/A| + +## Modules to Import + +```js +import CommonEvent from '@ohos.commonevent'; +``` + + + +## CommonEvent.publish(event: string, callback: AsyncCallback\): void + +- Functionality + + Publishes a common event. This method uses a callback to return the result. + +* Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | -------------------- | ---- | -------------------- | + | event | Read-only| string | Yes| Name of the common event to publish.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +* Example + +```js +// Callback for common event publication +function PublishCallBack(err) { + console.info("==========================>PublishCallBack=======================>"); + console.info("==========================>err:=======================>", err.code); +} +// Publish a common event. +CommonEvent.publish("publish_event", PublishCallBack); +``` + + + +## CommonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void + +- Functionality + + Publishes a common event with given attributes. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | ---------------------- | ---- | ---------------------- | + | event | Read-only| string | Yes| Name of the common event to publish.| + | options | Read-only| [CommonEventPublishData](#publishData) | Yes| Attributes of the common event to publish.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Example + + +```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 + isOrdered: true; // The common event is an ordered one. +} +// Callback for common event publication +function PublishCallBack(err) { + console.info("==========================>PublishCallBack=======================>"); +} +// Publish a common event. +CommonEvent.publish("publish_event", options, PublishCallBack); +``` + + + +## CommonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void + +- Functionality + + Creates a subscriber. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------- | -------- | ---------------------------------------------------- | ---- | ------------------------ | + | subscribeInfo | Read-only| [CommonEventSubscribeInfo](#SubscribeInfo) | Yes| Subscriber information.| + | callback | Read-only| AsyncCallback\<[CommonEventSubscriber](#Subscriber)> | Yes| Callback used to return the result.| + +- Example + + +```js +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Subscriber information +var subscribeInfo = { + events: ["event"] +}; +// Callback for subscriber creation +function CreateSubscriberCallBack(err, data) { + console.info("==========================>CreateSubscriberCallBack=======================>"); + subscriber = data; +} +// Create a subscriber. +CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +``` + + + +## CommonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ + +- Functionality + + Creates a subscriber. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------- | -------- | ------------------------------------------ | ---- | ------------ | + | subscribeInfo | Read-only| [CommonEventSubscribeInfo](#SubscribeInfo) | Yes| Subscriber information.| + +- Return values + + Promise\<[CommonEventSubscriber](#Subscriber)> + + Returns a subscriber object. + +- Example + +```js +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Subscriber information +var subscribeInfo = { + events: ["event"] +}; +// Create a subscriber. +CommonEvent.createSubscriber(subscribeInfo).then((data) => { + console.info("==========================>createSubscriberPromise=======================>"); + subscriber = data; +}); +``` + + + +## CommonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void + +- Functionality + + Subscribes to common events. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---------- | -------- | --------------------------------------------------- | ---- | ------------------------------ | + | subscriber | Read-only| [CommonEventSubscriber](#Subscriber) | Yes| Subscriber object.| + | callback | Read-only| AsyncCallback\<[CommonEventData](#CommonEventData)> | Yes| Callback used to return the result.| + +- Example + + Unordered common event: + + +```js +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Subscriber information +var subscribeInfo = { + events: ["event"] +}; +// Callback for common event subscription +function SubscribeCallBack(err, data) { + console.info("==========================>SubscribeCallBack=======================>"); +} +// Callback for subscriber creation +function CreateSubscriberCallBack(err, data) { + console.info("==========================>CreateSubscriberCallBack=======================>"); + subscriber = data; + // Subscribe to a common event. + CommonEvent.subscribe(subscriber, SubscribeCallBack); +} +// Create a subscriber. +CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +``` + +​ Ordered common event: + +```js +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Subscriber information +var subscribeInfo = { + events: ["event"] +}; + +// Callback for result code setting of an ordered common event +function SetCodeCallBack(err) { + console.info("==========================>SetCodeCallBack=======================>"); +} +// Callback for result data setting of an ordered common event +function SetDataCallBack(err) { + console.info("==========================>SetDataCallBack=======================>"); +} +// Callback for ordered common event processing +function FinishCommonEventCallBack(err) { + console.info("==========================>FinishCommonEventCallBack=======================>"); +} +// Callback for common event subscription +function SubscribeCallBack(err, data) { + console.info("==========================>SubscribeCallBack=======================>"); + // Set the result code for the ordered common event. + subscriber.setCode(0, SetCodeCallBack); + // Set the result data for the ordered common event. + subscriber.setData("publish_data_changed", SetDataCallBack); + // Complete the processing of the ordered common event. + subscriber.finishCommonEvent(FinishCommonEventCallBack) +} + +// Callback for subscriber creation +function CreateSubscriberCallBack(err, data) { + console.info("==========================>CreateSubscriberCallBack=======================>"); + subscriber = data; + // Subscribe to a common event. + CommonEvent.subscribe(subscriber, SubscribeCallBack); +} + +// Create a subscriber. +CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +``` + +​ + +## CommonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void + +- Functionality + + Unsubscribes from common events. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---------- | -------- | --------------------- | ---- | ---------------------- | + | subscriber | Read-only| CommonEventSubscriber | Yes| Subscriber object.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Example + +```js +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Subscriber information +var subscribeInfo = { + events: ["event"] +}; +// Callback for common event subscription +function SubscribeCallBack(err, data) { + console.info("==========================>SubscribeCallBack=======================>"); +} +// Callback for subscriber creation +function CreateSubscriberCallBack(err, data) { + console.info("==========================>CreateSubscriberCallBack=======================>"); + subscriber = data; + // Subscribe to a common event. + CommonEvent.subscribe(subscriber, SubscribeCallBack); +} +// Callback for common event unsubscription +function UnsubscribeCallBack(err) { + console.info("==========================>UnsubscribeCallBack=======================>"); +} +// Create a subscriber. +CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +// Unsubscribe from the common event. +CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); +``` + +## CommonEventPublishData + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------------------- | -------- | -------------------- | ---- | ---------------------------- | +| bundleName | Read-only| string | No| Bundle name.| +| code | Read-only| number | No| Result code of the common event.| +| data | Read-only| string | No| Custom result data of the common event.| +| subscriberPermissions | Read-only| Array\ | No| Permissions required for subscribers to receive the common event.| +| isOrdered | Read-only| boolean | No| Whether the common event is an ordered one.| +| parameters | Read-only| {[key: string]: any} | No| Additional information about the common event.| + +## CommonEventSubscribeInfo + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------------------- | -------- | -------------- | ---- | ------------------------------------------------------------ | +| events | Read-only| Array\ | Yes| Common events to subscribe to.| +| publisherPermission | Read-only| string | No| Permission required for the publisher.| +| publisherDeviceId | Read-only| string | No| Device ID. The value must be the ID of an existing device on the same network.| +| userId | Read-only| number | No| User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | Read-only| number | No| Subscriber priority. The value ranges from -100 to 1000.| + +## CommonEventData + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | -------------------- | ---- | ------------------------------------------------------ | +| event | Read-only| string | Yes| Name of the common event to subscribe to.| +| bundleName | Read-only| string | No| Bundle name.| +| code | Read-only| number | No| Result code of the common event, which is used to transfer data of the int type.| +| data | Read-only| string | No| Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | Read-only| {[key: string]: any} | No| Additional information about the common event.| + +## CommonEventSubscriber + +### getCode (callback) + +- Functionality + + Obtains the result code of this common event. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ---------------------- | ---- | ------------------ | + | callback | AsyncCallback\ | Yes| Callback used to return the result code.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function getCodeCallback(err, data) { + console.info("==========================>getCodeCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + console.info("==========================>code:=======================>", data); + } + subscriber.getCode(getCodeCallback); + ``` + +### getCode (promise) + +- Functionality + + Obtains the result code of this common event. This method uses a promise to return the result. + +- Return values + + | Type| Description| + | ---------------- | ------------------ | + | Promise\ | A promise used to return the result code.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.getCode().then((data) => { + console.info("==========================>getCodePromise=======================>"); + console.info("==========================>code:=======================>", data); + }); + ``` + +### setCode (callback) + +- Functionality + + Sets the result code for this common event. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------------------- | ---- | -------------------- | + | code | number | Yes| Result code of the common event.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function setCodeCallback(err) { + console.info("==========================>setCodeCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + } + subscriber.setCode(1, setCodeCallback); + ``` + +### setCode (promise) + +- Functionality + + Sets the result code for this common event. This method uses a promise to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | ------------------ | + | code | number | Yes| Result code of the common event.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.setCode(1).then(() => { + console.info("==========================>setCodePromise=======================>"); + }); + ``` + +### getData (callback) + +- Functionality + + Obtains the result data of this common event. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ---------------------- | ---- | ------------------ | + | callback | AsyncCallback\ | Yes| Callback used to return the result data.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function getDataCallback(err, data) { + console.info("==========================>getDataCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + console.info("==========================>data:=======================>", data); + } + subscriber.getData(getDataCallback); + ``` + +### getData (promise) + +- Functionality + + Obtains the result data of this common event. This method uses a promise to return the result. + +- Return values + + | Type| Description| + | ---------------- | ------------------ | + | Promise\ | A promise used to return the result data.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.getData().then((data) => { + console.info("==========================>getDataPromise=======================>"); + console.info("==========================>data:=======================>", data); + }); + ``` + +### setData (callback) + +- Functionality + + Sets the result data for this common event. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------------------- | ---- | -------------------- | + | data | string | Yes| Result data of the common event.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function setDataCallback(err) { + console.info("==========================>setDataCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + } + subscriber.setData("publish_data_changed", setDataCallback); + ``` + +### setData (promise) + +- Functionality + + Sets the result data for this common event. This method uses a promise to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | ------------------ | + | data | string | Yes| Result data of the common event.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.setData("publish_data_changed").then(() => { + console.info("==========================>setDataPromise=======================>"); + }); + ``` + +### setCodeAndData (callback) + +- Functionality + + Sets the result code and result data for this common event. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------------------- | ---- | -------------------- | + | code | number | Yes| Result code of the common event.| + | data | string | Yes| Result data of the common event.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function setCodeDataCallback(err) { + console.info("==========================>setCodeDataCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + } + subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCallback); + ``` + +### setCodeAndData (promise) + +- Functionality + + Sets the result code and result data for this common event. This method uses a promise to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | ------------------ | + | code | number | Yes| Result code of the common event.| + | data | string | Yes| Result data of the common event.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("==========================>setCodeAndData=======================>"); + }); + ``` + +### isOrderedCommonEvent (callback) + +- Functionality + + Checks whether this common event is an ordered one. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ----------------------- | ---- | -------------------------------- | + | callback | AsyncCallback\ | Yes| Returns **true** if the common event is an ordered one; returns **false** otherwise.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function isOrderedCallback(err, data) { + console.info("==========================>isOrderedCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + console.info("==========================>isOrdered:=======================>", data); + } + subscriber.isOrderedCommonEvent(isOrderedCallback); + ``` + +### isOrderedCommonEvent (promise) + +- Functionality + + Checks whether this common event is an ordered one. This method uses a promise to return the result. + +- Return values + + | Type| Description| + | ----------------- | -------------------------------- | + | Promise\ | Returns **true** if the common event is an ordered one; returns **false** otherwise.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.isOrderedCommonEvent().then((data) => { + console.info("==========================>isOrdered:=======================>", data); + }); + ``` + +### abortCommonEvent (callback) + +- Functionality + + Aborts this common event. After the abort, the common event is not sent to the next subscriber. This method takes effect only for ordered common events. It uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ----------------------- | ---- | ------------------ | + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function abortCallback(err) { + console.info("==========================>abortCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + } + subscriber.abortCommonEvent(abortCallback); + ``` + +### abortCommonEvent (promise) + +- Functionality + + Aborts this common event. After the abort, the common event is not sent to the next subscriber. This method takes effect only for ordered common events. It uses a promise to return the result. + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.abortCommonEvent().then(() => { + console.info("==========================>abortCommonEvent:=======================>"); + }); + ``` + +### clearAbortCommonEvent (callback) + +- Functionality + + Clears the aborted state of this common event. This method takes effect only for ordered common events. It uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | -------------------- | ---- | -------------------- | + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function clearAbortCallback(err) { + console.info("==========================>clearAbortCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + } + subscriber.clearAbortCommonEvent(clearAbortCallback); + ``` + +### clearAbortCommonEvent (promise) + +- Functionality + + Clears the aborted state of this common event. This method takes effect only for ordered common events. It uses a promise to return the result. + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.clearAbortCommonEvent().then(() => { + console.info("==========================>clearAbortCommonEvent:=======================>"); + }); + ``` + +### getAbortCommonEvent (callback) + +- Functionality + + Checks whether this common event is in the aborted state. This method takes effect only for ordered common events. It uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ----------------------- | ---- | ---------------------------------- | + | callback | AsyncCallback\ | Yes| Returns **true** if the ordered common event is in the aborted state; returns **false** otherwise.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function getAbortCallback(err, data) { + console.info("==========================>getAbortCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + console.info("==========================>abort:=======================>", data); + } + subscriber.getAbortCommonEvent(getAbortCallback); + ``` + +### getAbortCommonEvent (promise) + +- Functionality + + Checks whether this common event is in the aborted state. This method takes effect only for ordered common events. It uses a promise to return the result. + +- Return values + + | Type| Description| + | ----------------- | ---------------------------------- | + | Promise\ | Returns **true** if the ordered common event is in the aborted state; returns **false** otherwise.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.getAbortCommonEvent().then((data) => { + console.info("==========================>getAbortCommonEvent:=======================>"); + console.info("==========================>abort:=======================>", data); + }); + ``` + +### getSubscribeInfo (callback) + +- Functionality + + Obtains the subscriber information. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | ---------------------------------------- | ---- | -------------------- | + | callback | AsyncCallback\ | Yes| Callback used to return the subscriber information.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + // Callback for result data setting of an ordered common event + function getSubscribeInfoCallback(err, data) { + console.info("==========================>getSubscribeInfoCallback=======================>"); + console.info("==========================>err:=======================>", err.code); + console.info("==========================>priority:=======================>", data.priority); + } + subscriber.getSubscribeInfo(getSubscribeInfoCallback); + ``` + +### getSubscribeInfo (promise) + +- Functionality + + Obtains the subscriber information. This method uses a promise to return the result. + +- Return values + + | Type| Description| + | ---------------------------------- | -------------------- | + | Promise\ | A promise used to return the subscriber information.| + +- Example + + ```js + var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + subscriber.getSubscribeInfo().then((data) => { + console.info("==========================>getSubscribeInfo:=======================>"); + console.info("==========================>priority:=======================>", data.priority); + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..644c99095bc672618b63741551cbc4833e72dde5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -0,0 +1,1698 @@ +# DataAbilityPredicates + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import dataAbility from '@ohos.data.dataAbility' +``` + +## Required Permissions + +None + +## dataAbility.createRdbPredicates + +createRdbPredicates\(name: string, dataAbilityPredicates: DataAbilityPredicates\): rdb.RdbPredicates + +Creates an **RdbPredicates** object based on a **DataAabilityPredicates** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Table name in the RDB store.

+

dataAbilityPredicates

+

DataAbilityPredicates

+

Yes

+

DataAbilityPredicates object.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

rdb.RdbPredicates

+

RdbPredicates object created.

+
+ +- Example + + ``` + let dataAbilityPredicates = new dataAbility.DataAbilityPredicates() + dataAbilityPredicates.equalTo("NAME", "Rose").between("AGE", 16, 30) + let predicates = dataAbility.createRdbPredicates("EMPLOYEE", dataAbilityPredicates) + ``` + + +## DataAbilityPredicates + +Provides predicates for implementing diverse query methods. + +### equalTo + +equalTo\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + ``` + + +### notEqualTo + +notEqualTo\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value not equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notEqualTo("NAME", "lisi") + ``` + + +### beginWrap + +beginWrap\(\): DataAbilityPredicates + +Adds a left parenthesis to this **DataAbilityPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object with a left parenthesis.

+
+ +- Example + + ``` + let predicates = new dataAbilitylity.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### endWrap + +endWrap\(\): DataAbilityPredicates + +Adds a right parenthesis to this **DataAbilityPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object with a right parenthesis.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### or + +or\(\): DataAbilityPredicates + +Adds the OR condition to this **DataAbilityPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object with the OR condition.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") + ``` + + +### and + +and\(\): DataAbilityPredicates + +Adds the AND condition to this **DataAbilityPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates with the AND condition.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) + ``` + + +### contains + +contains\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match a string containing the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.contains("NAME", "os") + ``` + + +### beginsWith + +beginsWith\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match a string that starts with the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.beginsWith("NAME", "os") + ``` + + +### endsWith + +endsWith\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match a string that ends with the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.endsWith("NAME", "se") + ``` + + +### isNull + +isNull\(field: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field whose value is **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.isNull("NAME") + ``` + + +### isNotNull + +isNotNull\(field: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field whose value is not **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.isNotNull("NAME") + ``` + + +### like + +like\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match a string that is similar to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.like("NAME", "%os%") + ``` + + +### glob + +glob\(field: string, value: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the specified string. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.glob("NAME", "?h*g") + ``` + + +### between + +between\(field: string, low: ValueType, high: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value within the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

low

+

ValueType

+

Yes

+

Minimum value to match the DataAbilityPredicates.

+

high

+

ValueType

+

Yes

+

Maximum value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.between("AGE", 10, 50) + ``` + + +### notBetween + +notBetween\(field: string, low: ValueType, high: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value out of the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

low

+

ValueType

+

Yes

+

Minimum value to match the DataAbilityPredicates.

+

high

+

ValueType

+

Yes

+

Maximum value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notBetween("AGE", 10, 50) + ``` + + +### greaterThan + +greaterThan\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value greater than the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.greaterThan("AGE", 18) + ``` + + +### lessThan + +lessThan\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value less than the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.lessThan("AGE", 20) + ``` + + +### greaterThanOrEqualTo + +greaterThanOrEqualTo\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value greater than or equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.greaterThanOrEqualTo("AGE", 18) + ``` + + +### lessThanOrEqualTo + +lessThanOrEqualTo\(field: string, value: ValueType\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **ValueType** and value less than or equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the DataAbilityPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.lessThanOrEqualTo("AGE", 20) + ``` + + +### orderByAsc + +orderByAsc\(field: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the column with values sorted in ascending order. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the column sorted in the specified order.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.orderByAsc("NAME") + ``` + + +### orderByDesc + +orderByDesc\(field: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the column with values sorted in descending order. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the column sorted in the specified order.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.orderByDesc("AGE") + ``` + + +### distinct + +distinct\(\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to filter out duplicate records. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that can filter out duplicate records.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").distinct("NAME") + let resultSet = await rdbStore.query(predicates, ["NAME"]) + ``` + + +### limitAs + +limitAs\(value: number\): DataAbilityPredicates + +Set the **DataAbilityPredicates** that specify the maximum number of records. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

number

+

Yes

+

Maximum number of records in a column.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates that can be used to set the maximum number of records.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").limitAs(3) + ``` + + +### offsetAs + +offsetAs\(rowOffset: number\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to specify the start position of the returned result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rowOffset

+

number

+

Yes

+

Number of rows to offset from the beginning. The value is a positive integer.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that specifies the start position of the returned result.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").offsetAs(3) + ``` + + +### groupBy + +groupBy\(fields: Array\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to group rows that have the same value into summary rows. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fields

+

Array<string>

+

Yes

+

Names of columns grouped for querying data.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that groups rows that have the same value.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.groupBy(["AGE", "NAME"]) + ``` + + +### indexedBy + +indexedBy\(indexName: string\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to specify the index column. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

indexName

+

string

+

Yes

+

Name of the index column.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityRdbPredicates object that specifies the index column.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.indexedBy("SALARY_INDEX") + ``` + + +### in + +in\(field: string, value: Array\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **Array** and value within the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

Array<ValueType>

+

Yes

+

Array of ValueType to match.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.in("AGE", [18, 20]) + ``` + + +### notIn + +notIn\(field: string, value: Array\): DataAbilityPredicates + +Sets the **DataAbilityPredicates** to match the field with data type **Array** and value out of the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

Array<ValueType>

+

Yes

+

Array of ValueType to match.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

DataAbilityPredicates

+

DataAbilityPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") + predicates.notIn("NAME", ["Lisa", "Rose"]) + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md new file mode 100644 index 0000000000000000000000000000000000000000..50977a3f7b800bc670ecb0ff94e1628daf6ef3fe --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -0,0 +1,2641 @@ +# Relational Database + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import dataRdb from '@ohos.data.rdb' +``` + +## Required Permissions + +None + +## dataRdb.getRdbStore + +getRdbStore\(config: StoreConfig, version: number, callback: AsyncCallback\): void + +Obtains a relational database \(RDB\) store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

StoreConfig

+

Yes

+

Configuration of the RDB store.

+

version

+

number

+

Yes

+

RDB store version.

+

callback

+

AsyncCallback<RdbStore>

+

Yes

+

Callback invoked to return the RDB store.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + const STORE_CONFIG = { name: "RdbTest.db" } + 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)" + dataRdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { + rdbStore.executeSql(SQL_CREATE_TABLE) + console.info(TAG + 'create table done.') + }) + ``` + + +## dataRdb.getRdbStore + +getRdbStore\(config: StoreConfig, version: number\): Promise + +Obtains an RDB store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

StoreConfig

+

Yes

+

Configuration of the RDB store.

+

version

+

number

+

Yes

+

RDB store version.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<RdbStore>

+

Promise used to return the RDB store.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + const STORE_CONFIG = { name: "RdbTest.db" } + 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 = dataRdb.getRdbStore(STORE_CONFIG, 1); + promise.then(async (rdbStore) => { + await rdbStore.executeSql(SQL_CREATE_TABLE, null) + }).catch((err) => { + expect(null).assertFail(); + }) + ``` + + +## dataRdb.deleteRdbStore + +deleteRdbStore\(name: string, callback: AsyncCallback\): void + +Deletes an RDB store. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the RDB store to delete.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result. If the RDB store is deleted, true will be returned. Otherwise, false will be returned.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + dataRdb.deleteRdbStore("RdbTest.db", function (err, rdbStore) { + console.info(TAG + 'delete store done.')}) + ``` + + +## dataRdb.deleteRdbStore + +deleteRdbStore\(name: string\): Promise + +Deletes an RDB store. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the RDB store to delete.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result. If the RDB store is deleted, true will be returned. Otherwise, false will be returned.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + let promise = dataRdb.deleteRdbStore("RdbTest.db") + promise.then(()=>{ + console.info(TAG + 'delete store done.') + }) + ``` + + +## RdbPredicates + +Defines predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. + +### constructor + +constructor\(name: string\) + +A constructor used to create an **RdbPredicates** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Database table name.

+
+ +- Example + + ``` + import dataRdb from '@ohos.data.rdb' + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + ``` + + +### equalTo + +equalTo\(field: string, value: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + ``` + + +### notEqualTo + +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. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.notEqualTo("NAME", "lisi") + ``` + + +### beginWrap + +beginWrap\(\): RdbPredicates + +Adds a left parenthesis to the **RdbPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates with a left parenthesis.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### endWrap + +endWrap\(\): RdbPredicates + +Adds a right parenthesis to the **RdbPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates with a right parenthesis.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "lisi") + .beginWrap() + .equalTo("AGE", 18) + .or() + .equalTo("SALARY", 200.5) + .endWrap() + ``` + + +### or + +or\(\): RdbPredicates + +Adds the OR condition to the **RdbPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates with the OR condition.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .or() + .equalTo("NAME", "Rose") + ``` + + +### and + +and\(\): RdbPredicates + +Adds the AND condition to the **RdbPredicates**. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates with the AND condition.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + .and() + .equalTo("SALARY", 200.5) + ``` + + +### contains + +contains\(field: string, value: string\): RdbPredicat + +Sets the **RdbPredicates** to match a string containing the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.contains("NAME", "os") + ``` + + +### beginsWith + +beginsWith\(field: string, value: string\): RdbPredicates + +Sets the **RdbPredicates** to match a string that starts with the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.beginsWith("NAME", "os") + ``` + + +### endsWith + +endsWith\(field: string, value: string\): RdbPredicates + +Sets the **RdbPredicates** to match a string that ends with the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.endsWith("NAME", "se") + ``` + + +### isNull + +isNull\(field: string\): RdbPredicates + +Sets the **RdbPredicates** to match the field whose value is **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.isNull("NAME") + ``` + + +### isNotNull + +isNotNull\(field: string\): RdbPredicates + +Sets the **RdbPredicates** to match the field whose value is not **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.isNotNull("NAME") + ``` + + +### like + +like\(field: string, value: string\): RdbPredicates + +Sets the **RdbPredicates** to match a string that is similar to the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.like("NAME", "%os%") + ``` + + +### glob + +glob\(field: string, value: string\): RdbPredicates + +Sets the **RdbPredicates** to match the specified string. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

string

+

Yes

+

Value to match the RdbPredicates.
Wildcards are supported. The asterisk (*) represents zero, one, or more numbers or characters. The question mark (?) represents a single number or character.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified string.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.glob("NAME", "?h*g") + ``` + + +### between + +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. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

low

+

ValueType

+

Yes

+

Minimum value to match the RdbPredicates.

+

high

+

ValueType

+

Yes

+

Maximum value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.between("AGE", 10, 50) + ``` + + +### notBetween + +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. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

low

+

ValueType

+

Yes

+

Minimum value to match the RdbPredicates.

+

high

+

ValueType

+

Yes

+

Maximum value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.notBetween("AGE", 10, 50) + ``` + + +### greaterThan + +greaterThan\(field: string, value: ValueType\): RdbPredicatesgr + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value greater than the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.greaterThan("AGE", 18) + ``` + + +### lessThan + +lessThan\(field: string, value: ValueType\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **ValueType** and value less than the specified value. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.lessThan("AGE", 20) + ``` + + +### greaterThanOrEqualTo + +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. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.greaterThanOrEqualTo("AGE", 18) + ``` + + +### lessThanOrEqualTo + +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. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

ValueType

+

Yes

+

Value to match the RdbPredicates.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.lessThanOrEqualTo("AGE", 20) + ``` + + +### orderByAsc + +orderByAsc\(field: string\): RdbPredicates + +Sets the **RdbPredicates** to match the column with values sorted in ascending order. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the column with values sorted in the specified order.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.orderByAsc("NAME") + ``` + + +### orderByDesc + +orderByDesc\(field: string\): RdbPredicates + +Sets the **RdbPredicates** to match the column with values sorted in descending order. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the column with values sorted in the specified order.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.orderByDesc("AGE") + ``` + + +### distinct + +distinct\(\): RdbPredicates + +Sets the **RdbPredicates** to filter out duplicate records. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that can filter out duplicate records.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").distinct("NAME") + let resultSet = await rdbStore.query(predicates, ["NAME"]) + ``` + + +### limitAs + +limitAs\(value: number\): RdbPredicates + +Sets the **RdbPredicates** to specify the maximum number of records. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

number

+

Yes

+

Maximum number of records.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that specifies the maximum number of records.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").limitAs(3) + ``` + + +### offsetAs + +offsetAs\(rowOffset: number\): RdbPredicates + +Sets the **RdbPredicates** to specify the start position of the returned result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rowOffset

+

number

+

Yes

+

Number of rows to offset from the beginning. The value is a positive integer.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that specifies the start position of the returned result.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose").offsetAs(3) + ``` + + +### groupBy + +groupBy\(fields: Array\): RdbPredicates + +Sets the **RdbPredicates** to group rows that have the same value into summary rows. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fields

+

Array<string>

+

Yes

+

Names of columns to group.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that groups rows with the same value.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.groupBy(["AGE", "NAME"]) + ``` + + +### indexedBy + +indexedBy\(indexName: string\): RdbPredicates + +Sets the **RdbPredicates** object to specify the index column. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

indexName

+

string

+

Yes

+

Name of the index column.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that specifies the index column.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.indexedBy("SALARY_INDEX") + ``` + + +### in + +in\(field: string, value: Array\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **Array** and value within the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

Array<ValueType>

+

Yes

+

Array of ValueType to match.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.in("AGE", [18, 20]) + ``` + + +### notIn + +notIn\(field: string, value: Array\): RdbPredicates + +Sets the **RdbPredicates** to match the field with data type **Array** and value out of the specified range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Column name in the database table.

+

value

+

Array<ValueType>

+

Yes

+

Array of ValueType to match.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

RdbPredicates

+

RdbPredicates object that matches the specified field.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.notIn("NAME", ["Lisa", "Rose"]) + ``` + + +## RdbStore + +Provides methods to manage an RDB store. + +### insert + +insert\(name: string, values: ValuesBucket, callback: AsyncCallback\):void + +Inserts a row of data into a table. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the target table.

+

values

+

ValuesBucket

+

Yes

+

Row of data to insert.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback invoked to return the result. If the operation is successful, the row ID will be returned. If the operation fails, -1 will be returned.

+
+ +- Example + + ``` + const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), + } + rdbStore.insert("EMPLOYEE", valueBucket, function (err, ret) { + expect(1).assertEqual(ret) + console.log(TAG + "insert first done: " + ret)}) + ``` + + +### insert + +insert\(name: string, values: ValuesBucket\):Promise + +Inserts a row of data into a table. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the target table.

+

values

+

ValuesBucket

+

Yes

+

Row of data to insert.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the result. If the operation is successful, the row ID will be returned. If the operation fails, -1 will be returned.

+
+ +- Example + + ``` + const valueBucket = { + "NAME": "Lisa", + "AGE": 18, + "SALARY": 100.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), + } + let promise = rdbStore.insert("EMPLOYEE", valueBucket) + promise.then(async (ret) => { + await console.log(TAG + "insert first done: " + ret) + }).catch((err) => {}) + ``` + + +### update + +update\(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback\):void + +Updates data in the database based on the specified **RdbPredicates** object. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

values

+

ValuesBucket

+

Yes

+

Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Row of data to insert.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the number of rows updated.

+
+ +- Example + + ``` + const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), + } + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + rdbStore.update(valueBucket, predicates, function (err, ret) { + console.log(TAG + "updated row count: " + changedRows)}) + ``` + + +### update + +update\(values: ValuesBucket, rdbPredicates: RdbPredicates\):Promise + +Updates data in the database based on the specified **RdbPredicates** object. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

values

+

ValuesBucket

+

Yes

+

Data to update. The value specifies the row of data to be updated in the database. The key-value pair is associated with the column name in the target table.

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Row of data to insert.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the number of rows updated.

+
+ +- Example + + ``` + const valueBucket = { + "NAME": "Rose", + "AGE": 22, + "SALARY": 200.5, + "CODES": new Uint8Array([1, 2, 3, 4, 5]), + } + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + let promise = rdbStore.update(valueBucket, predicates) + promise.then(async (ret) => { + await console.log(TAG + "updated row count: " + changedRows) + }).catch((err) => {}) + ``` + + +### delete + +delete\(rdbPredicates: RdbPredicates, callback: AsyncCallback\):void + +Deletes data from the database based on the specified **RdbPredicates** object. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Conditions specified for deleting data.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback invoked to return the number of rows deleted.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + rdbStore.delete(predicates, function (err, rows) { + console.log(TAG + "delete rows: " + rows)}) + ``` + + +### delete + +delete\(rdbPredicates: RdbPredicates\):Promise + +Deletes data from the database based on the specified **RdbPredicates** object. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Conditions specified for deleting data.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the number of rows deleted.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Lisa") + let promise = rdbStore.delete(predicates) + promise.then((rows) => { + console.log(TAG + "delete rows: " + rows) + }).catch((err) => {}) + ``` + + +### query + +query\(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback\):void + +Queries data in the database based on specified conditions. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

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>

+

Yes

+

Callback invoked to return the result. If the operation is successful, a ResultSet object will be returned.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose") + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { + console.log(TAG + "resultSet column names:" + resultSet.columnNames) + console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + ``` + + +### query + +query\(rdbPredicates: RdbPredicates, columns: Array\):Promise + +Queries data in the database based on specified conditions. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

rdbPredicates

+

RdbPredicates

+

Yes

+

Query conditions specified by the RdbPredicates object.

+

columns

+

Array<string>

+

Yes

+

Columns to query. If this parameter is not specified, the query applies to all columns.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<ResultSet>

+

Promise used to return the result. If the operation is successful, a ResultSet object will be returned.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + predicates.equalTo("NAME", "Rose") + let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + promise.then((resultSet) => { + console.log(TAG + "resultSet column names:" + resultSet.columnNames) + console.log(TAG + "resultSet column count:" + resultSet.columnCount)}) + ``` + + +### executeSql + +executeSql\(sql: string, bindArgs: Array, callback: AsyncCallback\):void + +Runs the SQL statement that contains the specified parameters but does not return a value. This method uses a callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

sql

+

string

+

Yes

+

SQL statement to run.

+

bindArgs

+

Array<ValueType>

+

Yes

+

Values of the parameters in the SQL statement.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ + +- Example + + ``` + rdbStore.executeSql("DELETE FROM EMPLOYEE", function () { + console.info(TAG + 'delete done.')}) + ``` + + +### executeSql + +executeSql\(sql: string, bindArgs: Array\):Promise + +Runs the SQL statement that contains the specified parameters but does not return a value. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

sql

+

string

+

Yes

+

SQL statement to run.

+

bindArgs

+

Array<ValueType>

+

Yes

+

Values of the parameters in the SQL statement.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + + ``` + let promise = rdbStore.executeSql("DELETE FROM EMPLOYEE") + promise.then(() => { + console.info(TAG + 'delete done.')}) + ``` + + +## StoreConfig + +Manages the configuration of an RDB store. + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Database file name.

+
+ +## ValueType + +Defines the data types allowed. + + + + + + + + + + + + + + + + +

Name

+

Description

+

number

+

Number.

+

string

+

String.

+

boolean

+

Boolean.

+
+ +## ValuesBucket + +Defines a bucket to store key-value pairs. + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

[key: string]

+

ValueType| Uint8Array | null

+

Yes

+

Key-value pairs stored.

+
diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md new file mode 100644 index 0000000000000000000000000000000000000000..7e72ca266d54f2f9267a4c47f14da2693c81ff4f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -0,0 +1,788 @@ +# Result Set + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Usage + +The **resultSet** object is obtained by using [**RdbStore.query\(\)**](js-apis-data-rdb.md#section6231155031814). + +``` +import dataRdb from '@ohos.data.rdb'; +let predicates = new dataRdb.RdbPredicates("EMPLOYEE") +predicates.equalTo("AGE", 18) +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +promise.then((resultSet) => { + await console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); + await console.log(TAG + "resultSet columnCount:" + resultSet.columnCount);}) +``` + +## Required Permissions + +None + +## ResultSet + +Provides methods to access the result set, which is obtained by querying the relational database \(RDB\) store. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnNames

+

Array<string>

+

Yes

+

Names of all columns in the result set.

+

columnCount

+

number

+

Yes

+

Number of columns in the result set.

+

rowCount

+

number

+

Yes

+

Number of rows in the result set.

+

rowIndex

+

number

+

Yes

+

Index of the current row in the result set.

+

isAtFirstRow

+

boolean

+

Yes

+

Specifies whether the cursor is in the first row of the result set.

+

isAtLastRow

+

boolean

+

Yes

+

Whether the cursor is in the last row of the result set.

+

isEnded

+

boolean

+

Yes

+

Whether the cursor is after the last row of the result set.

+

isStarted

+

boolean

+

Yes

+

Whether the cursor has been moved.

+

isClosed

+

boolean

+

Yes

+

Whether the result set is closed.

+
+ +### getColumnIndex + +getColumnIndex\(columnName: string\): number + +Obtains the column index based on the specified column name. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnName

+

string

+

Yes

+

Name of the column.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Index of the column.

+
+ +- Example + + ``` + resultSet.goToFirstRow() + const id = resultSet.getLong(resultSet.getColumnIndex("ID")) + const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + ``` + + +### getColumnName + +getColumnName\(columnIndex: number\): string + +Obtains the column name based on the specified column index. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the column.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Name of the column.

+
+ +- Example + + ``` + const id = resultSet.getColumnName(0) + const name = resultSet.getColumnName(1) + const age = resultSet.getColumnName(2) + ``` + + +### goTo + +goTo\(offset:number\): boolean + +Moves the cursor to the row based on the specified offset. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

offset

+

number

+

Yes

+

Offset relative to the current position.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goTo(1) + resultSet.close() + resultSet = null + ``` + + +### goToRow + +goToRow\(position: number\): boolean + +Moves the cursor to the specified row in the result set. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

position

+

number

+

Yes

+

Position to which the cursor is to be moved.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToRow(1) + resultSet.close() + resultSet = null + ``` + + +### goToFirstRow + +goToFirstRow\(\): boolean + +Moves the cursor to the first row of the result set. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToFirstRow() + resultSet.close() + resultSet = null; + ``` + + +### goToLastRow + +goToLastRow\(\): boolean + +Moves the cursor to the last row of the result set. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToLastRow() + resultSet.close() + resultSet = null; + ``` + + +### goToNextRow + +goToNextRow\(\): boolean + +Moves the cursor to the next row in the result set. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToNextRow() + resultSet.close() + resultSet = null; + ``` + + +### goToPreviousRow + +goToPreviousRow\(\): boolean + +Moves the cursor to the previous row in the result set. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operation is successful; returns false otherwise.

+
+ +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.goToPreviousRow() + resultSet.close() + resultSet = null + ``` + + +### getBlob + +getBlob\(columnIndex: number\): Uint8Array + +Obtains the value in the specified column in the current row as a byte array. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Uint8Array

+

Value in the specified column as a byte array.

+
+ +- Example + + ``` + const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")) + ``` + + +### getString + +getString\(columnIndex: number\): string + +Obtains the value in the specified column in the current row as a string. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Value in the specified column as a string.

+
+ +- Example + + ``` + const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + ``` + + +### getLong + +getLong\(columnIndex: number\): number + +Obtains the value in the specified column in the current row as a **Long**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Value in the specified column as a Long.

+
+ +- Example + + ``` + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + ``` + + +### getDouble + +getDouble\(columnIndex: number\): number + +Obtains the value in the specified column in the current row as a **double**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Value in the specified column as a double.

+
+ +- Example + + ``` + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + ``` + + +### isColumnNull + +isColumnNull\(columnIndex: number\): boolean + +Checks whether the value in the specified column in the current row is **null**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

columnIndex

+

number

+

Yes

+

Index of the specified column, starting from 0.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the value is null; returns false otherwise.

+
+ +- Example + + ``` + const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")) + ``` + + +### close + +close\(\): void + +Closes the result set. + +- Example + + ``` + let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + resultSet.close() + resultSet = null + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md new file mode 100644 index 0000000000000000000000000000000000000000..e236b61478026960f226f367e4ecf3105c5f9e12 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -0,0 +1,1608 @@ +# Lightweight Storage + +Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value pairs. Keys are of the string type, and values can be of the numeric, string, or Boolean type. + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import dataStorage from '@ohos.data.storage' +``` + +## Required Permissions + +None + +## Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

MAX_KEY_LENGTH

+

string

+

Yes

+

No

+

Maximum length of a key. It is 80 bytes.

+

MAX_VALUE_LENGTH

+

string

+

Yes

+

No

+

Maximum length of a value of the string type. It is 8192 bytes.

+
+ +## dataStorage.getStorageSync + +getStorageSync\(path: string\): Storage + +Reads a specified file and loads the data to the **Storage** instance for data operations in synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Storage

+

Storage instance used for data storage operations

+
+ +- Example: + + ``` + import dataStorage from '@ohos.data.storage' + import featureAbility from '@ohos.ability.featureAbility' + + var context = featureAbility.getContext() + var path = await context.getFilesDir() + let storage = dataStorage.getStorageSync(path + '/mystore') + storage.putSync('startup', 'auto') + storage.flushSync() + ``` + + +## dataStorage.getStorage + +getStorage\(path: string, callback: AsyncCallback\): void + +Reads a specified file and loads the data to the **Storage** instance for data operations. This method uses a callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+

callback

+

AsyncCallback<Storage>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + import dataStorage from '@ohos.data.storage' + import featureAbility from '@ohos.ability.featureAbility' + + var context = featureAbility.getContext() + var path = await context.getFilesDir() + dataStorage.getStorage(path + '/mystore', function (err, storage) { + if (err) { + console.info("Get the storage failed, path: " + path + '/mystore') + return; + } + storage.putSync('startup', 'auto') + storage.flushSync() + }) + ``` + + +## dataStorage.getStorage + +getStorage\(path: string\): Promise + +Reads a specified file and loads the data to the **Storage** instance for data operations. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Storage>

+

Promise used to return the result.

+
+ +- Example: + + ``` + import dataStorage from '@ohos.data.storage' + import featureAbility from '@ohos.ability.featureAbility' + + var context = featureAbility.getContext() + var path = await context.getFilesDir() + let promise = dataStorage.getStorage(path + '/mystore') + promise.then((storage) => { + storage.putSync('startup', 'auto') + storage.flushSync() + }).catch((err) => { + console.info("Get the storage failed, path: " + path + '/mystore') + }) + ``` + + +## dataStorage.deleteStorageSync + +deleteStorageSync\(path: string\): void + +Removes the singleton **Storage** instance of the specified file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified file is deleted, the **Storage** instance cannot be used to perform any data operation. Otherwise, data inconsistency will occur. This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Example: + + ``` + dataStorage.deleteStorageSync(path + '/mystore') + ``` + + +## dataStorage.deleteStorage + +deleteStorage\(path: string, callback: AsyncCallback\) + +Removes the singleton **Storage** instance of the specified file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified file is deleted, the **Storage** instance cannot be used to perform any data operation. Otherwise, data inconsistency will occur. This method uses an asynchronous callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + dataStorage.deleteStorage(path + '/mystore', function (err) { + if (err) { + console.info("Deleted failed with err: " + err) + return + } + console.info("Deleted successfully.") + }) + ``` + + +## dataStorage.deleteStorage + +deleteStorage\(path: string\): Promise + +Removes the singleton **Storage** instance of the specified file from the memory, and deletes the specified file, its backup file, and damaged files. After the specified file is deleted, the **Storage** instance cannot be used to perform any data operation. Otherwise, data inconsistency will occur. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = dataStorage.deleteStorage(path + '/mystore') + promise.then(() => { + console.info("Deleted successfully.") + }).catch((err) => { + console.info("Deleted failed with err: " + err) + }) + ``` + + +## dataStorage.removeStorageFromCacheSync + +removeStorageFromCacheSync\(path: string\): void + +Removes the singleton **Storage** instance of the specified file from the memory. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Example: + + ``` + dataStorage.removeStorageFromCacheSync(path + '/mystore') + ``` + + +## dataStorage.removeStorageFromCache + +removeStorageFromCache\(path: string, callback: AsyncCallback\): void + +Removes the singleton **Storage** instance of the specified file from the memory. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+

callback

+

AsyncCallback<Storage>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + dataStorage.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.") + }) + ``` + + +## dataStorage.removeStorageFromCache + +removeStorageFromCache\(path: string\): Promise + +Removes the singleton **Storage** instance of the specified file from the memory. The removed instance cannot be used for data operations. Otherwise, data inconsistency will occur. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Storage path of the application internal data

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = dataStorage.removeStorageFromCache(path + '/mystore') + promise.then(() => { + console.info("Removed storage from cache successfully.") + }).catch((err) => { + console.info("Removed storage from cache failed with err: " + err) + }) + ``` + + +## Storage + +Provides APIs for obtaining and modifying storage data. + +### getSync + +getSync\(key: string, defValue: ValueType\): ValueType + +Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

defValue

+

ValueType

+

Yes

+

Default value to be returned if the value of the specified key does not exist. The value can be a number, string, or Boolean value.

+
+ +- Return values + + + + + + + + + + +

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: + + ``` + let value = storage.getSync('startup', 'default') + console.info("The value of startup is " + value) + ``` + + +### get + +get\(key: string, defValue: ValueType, callback: AsyncCallback\): void + +Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

defValue

+

ValueType

+

Yes

+

Default value to be returned. The value can be a number, string, or Boolean value.

+

callback

+

AsyncCallback<ValueType>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.get('startup', 'default', function(err, value) { + if (err) { + console.info("Get the value of startup failed with err: " + err) + return + } + console.info("The value of startup is " + value) + }) + ``` + + +### get + +get\(key: string, defValue: ValueType\): Promise + +Obtains the value corresponding to a key. If the value is null or not in the default value format, the default value is returned. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

defValue

+

ValueType

+

Yes

+

Default value to be returned. The value can be a number, string, or Boolean value.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<ValueType>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.get('startup', 'default') + promise.then((value) => { + console.info("The value of startup is " + value) + }).catch((err) => { + console.info("Get the value of startup failed with err: " + err) + }) + ``` + + +### putSync + +putSync\(key: string, value: ValueType\): void + +Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush\(\)** or **flushSync\(\)**. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data to be modified. It cannot be empty.

+

value

+

ValueType

+

Yes

+

New value. The value can be a number, string, or Boolean value.

+
+ +- Example: + + ``` + storage.putSync('startup', 'auto') + ``` + + +### put + +put\(key: string, value: ValueType, callback: AsyncCallback\): void + +Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush\(\)** or **flushSync\(\)**. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data to be modified. It cannot be empty.

+

value

+

ValueType

+

Yes

+

New value. The value can be a number, string, or Boolean value.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + 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.") + }) + ``` + + +### put + +put\(key: string, value: ValueType\): Promise + +Obtains the **Storage** instance corresponding to the specified file, writes data to the **Storage** instance using a **Storage** API, and saves the modification using **flush\(\)** or **flushSync\(\)**. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data to be modified. It cannot be empty.

+

value

+

ValueType

+

Yes

+

New value. The value can be a number, string, or Boolean value.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.put('startup', 'auto') + promise.then(() => { + console.info("Put the value of startup successfully.") + }).catch((err) => { + console.info("Put the value of startup failed with err: " + err) + }) + ``` + + +### hasSync + +hasSync\(key: string\): boolean + +Checks whether the storage object contains data with the specified key. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the storage object contains data with the specified key; returns false otherwise.

+
+ +- Example: + + ``` + let isExist = storage.hasSync('startup') + if (isExist) { + console.info("The key of startup is contained.") + } + ``` + + +### has + +has\(key: string, callback: AsyncCallback\): boolean + +Checks whether the storage object contains data with the specified key. + +This method uses an asynchronous mode. + +- 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 result.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the storage object contains data with the specified key; returns false otherwise.

+
+ +- Example: + + ``` + 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.") + } + }) + ``` + + +### has + +has\(key: string\): Promise + +Checks whether the storage object contains data with the specified key. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.has('startup') + promise.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) + }) + ``` + + +### deleteSync + +deleteSync\(key: string\): void + +Deletes the data with the specified key from this storage object. + +This method uses a synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+
+ +- Example: + + ``` + storage.deleteSync('startup') + ``` + + +### delete + +delete\(key: string, callback: AsyncCallback\): void + +Deletes the data with the specified key from this storage object. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data. It cannot be empty.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.delete('startup', function (err) { + if (err) { + console.info("Delete startup key failed with err: " + err) + return + } + console.info("Deleted startup key successfully.") + }) + ``` + + +### delete + +delete\(key: string\): Promise + +Deletes the data with the specified key from this storage object. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the data.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.delete('startup') + promise.then(() => { + console.info("Deleted startup key successfully.") + }).catch((err) => { + console.info("Delete startup key failed with err: " + err) + }) + ``` + + +### flushSync + +flushSync\(\): void + +Saves the modification of the current object to the current **Storage** instance and synchronizes the modification to the file. + +This method uses a synchronous mode. + +- Example: + + ``` + storage.flushSync() + ``` + + +### flush + +flush\(callback: AsyncCallback\): void + +Saves the modification of the current object to the current **Storage** instance and stores the modification to the file in an asynchronous mode. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.flush(function (err) { + if (err) { + console.info("Flush to file failed with err: " + err) + return + } + console.info("Flushed to file successfully.") + }) + ``` + + +### flush + +flush\(\): Promise + +Saves the modification of the current object to the current **Storage** instance and stores the modification to the file in an asynchronous mode. + +This method uses an asynchronous mode. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.flush() + promise.then(() => { + console.info("Flushed to file successfully.") + }).catch((err) => { + console.info("Flush to file failed with err: " + err) + }) + ``` + + +### clearSync + +clearSync\(\): void + +Clears all data in a storage object. + +This method uses a synchronous mode. + +- Example: + + ``` + storage.clearSync() + ``` + + +### clear + +clear\(callback: AsyncCallback\): void + +Clears all data in a storage object. + +This method uses an asynchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the result.

+
+ +- Example: + + ``` + storage.clear(function (err) { + if (err) { + console.info("Clear to file failed with err: " + err) + return + } + console.info("Cleared to file successfully.") + }) + ``` + + +### clear + +clear\(\): Promise + +Clears all data in a storage object. + +This method uses an asynchronous mode. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example: + + ``` + let promise = storage.clear() + promise.then(() => { + console.info("Cleared to file successfully.") + }).catch((err) => { + console.info("Clear to file failed with err: " + err) + }) + ``` + + +### on \('change'\) + +on\(type: 'change', callback: Callback\): void + +Subscribes to data changes. The **StorageObserver** needs to be implemented. When the value of the key subscribed to is changed, a callback will be invoked after **flush\(\)** or **flushSync\(\)** is executed. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

type

+

string

+

Event type. The value change indicates a data change event.

+

callback

+

Callback<StorageObserver>

+

Callback object.

+
+ +- Example: + + ``` + 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'\) + +off\(type: 'change', callback: Callback\): void + +Unsubscribes from data changes. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

type

+

string

+

Event type. The value change indicates a data change event.

+

callback

+

Callback<StorageObserver>

+

Callback object to be canceled.

+
+ +- Example: + + ``` + var observer = function (key) { + console.info("The key of " + key + " changed.") + } + storage.off('change', observer) + ``` + + +## StorageObserver + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

No

+

Data changed

+
+ diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md new file mode 100644 index 0000000000000000000000000000000000000000..39d8c92342f998da7e18b8731e47a0f9929a5b92 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -0,0 +1,866 @@ +### DataAbilityHelper Module (JavaScript SDK APIs) + +#### Applicable Devices + +| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device| +| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ | +| DataAbilityHelper.openFile(uri: string, mode: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.openFile(uri: string, mode: string) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.on(type: 'dataChange', uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.off(type: 'dataChange', uri: string, callback?: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback>) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.getFileTypes(uri: string, mimeTypeFilter: string) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.getType(uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.getType(uri: string) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.normalizeUri(uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.normalizeUri(uri: string) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.denormalizeUri(uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.denormalizeUri(uri: string) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.notifyChange(uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.notifyChange(uri: string) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.insert(uri: string, valuesBucket: rdb.ValuesBucket) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.batchInsert(uri: string, valuesBuckets: Array, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.batchInsert(uri: string, valuesBuckets: Array) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.delete(uri: string, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| DataAbilityHelper.query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No| + +#### Modules to Import + +``` +import featureAbility from '@ohos.ability.featureAbility' +import ohos_data_ability from '@ohos.data.dataability' +import ohos_data_rdb from '@ohos.data.rdb' +``` + +#### DataAbilityHelper.openFile(uri: string, mode: string, callback: AsyncCallback\) + +- Functionality + + Opens a file with a specified URI. This method uses a callback to return the result. + + +* Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | -------------------- | ---- | ------------------------ | + | uri | Read-only| string | Yes| URI of the file to open.| + | mode | Read-only| string | Yes| Mode for opening the file. The value can be **rwt**.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +* Return values + + Returns a file descriptor. + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +var mode = "rwt"; +DAHelper.openFile( + "dataability:///com.example.DataAbility", + mode, + (err) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.openFile(uri: string, mode: string) + +- Functionality + + Opens a file with a specified URI. This method uses a promise to return the result. + +* Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---- | -------- | ------ | ---- | ------------------------ | + | uri | Read-only| string | Yes| URI of the file to open.| + | mode | Read-only| string | Yes| Mode for opening the file. The value can be **rwt**.| + +* Return values + + Returns a file descriptor. + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +var mode = "rwt"; +DAHelper.openFile( + "dataability:///com.example.DataAbility", + mode).then((void) => { + console.info("==========================>openFileCallback=======================>"); +}); +``` + +#### DataAbilityHelper.on(type: 'dataChange', uri: string, callback: AsyncCallback\) + +- Functionality + + Registers an observer to observe data specified by a given URI. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | -------------------- | ---- | ------------------------ | + | type | Read-only| string | Yes| Type of the event to observe. The value is **dataChange**.| + | uri | Read-only| string | Yes| URI of the data.| + | callback | Read-only| AsyncCallback\ | Yes| Callback invoked when the data is changed.| + +- Return value + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var helper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +function onChangeNotify() { + console.info("==========================>onChangeNotify=======================>"); +}; +helper.on( + "dataChange", + "dataability:///com.example.DataAbility", + onChangeNotify +) +``` + +#### DataAbilityHelper.off(type: 'dataChange', uri: string, callback?: AsyncCallback\) + +- Functionality + + Unregisters the observer used to observe data specified by a given URI. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | -------------------- | ---- | ------------------------ | + | type | Read-only| string | Yes| Type of the event to observe. The value is **dataChange**.| + | uri | Read-only| string | Yes| URI of the data.| + | callback | Read-only| AsyncCallback\ | No| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var helper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +function onChangeNotify() { + console.info("==========================>onChangeNotify=======================>"); +}; +helper.off( + "dataChange", + "dataability:///com.example.DataAbility", +) +helper.off( + "dataChange", + "dataability:///com.example.DataAbility", + onChangeNotify +) +``` + +#### DataAbilityHelper.getType(uri: string, callback: AsyncCallback\) + +- Functionality + + Obtains the MIME type of the data specified by a given URI. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | ---------------------- | ---- | ------------------------ | + | uri | Read-only| string | Yes| URI of the data.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + Returns the MIME type that matches the data specified by the URI. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.getType( + "dataability:///com.example.DataAbility", + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.getType(uri: string) + +- Functionality + + Obtains the MIME type of the data specified by a given URI. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---- | -------- | ------ | ---- | ------------------------ | + | uri | Read-only| string | Yes| URI of the data.| + +- Return value + + Returns the MIME type that matches the data specified by the URI. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.getType( + "dataability:///com.example.DataAbility" + ).then((data) => { + console.info("==========================>getTypeCallback=======================>"); +}); +``` + +#### DataAbilityHelper.getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback>) + +- Functionality + + Obtains the supported MIME types of a specified file. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------------- | -------- | ------------------------------ | ---- | ---------------------------- | + | uri | Read-only| string | Yes| URI of the file.| + | mimeTypeFilter | Read-only| string | Yes| MIME type of the file.| + | callback | Read-only| AsyncCallback\> | Yes| Callback used to return the result.| + +- Return value + + Returns a MIME type array. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.getFileTypes( + "dataability:///com.example.DataAbility", + "image/*", + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.getFileTypes(uri: string, mimeTypeFilter: string) + +- Functionality + + Obtains the supported MIME types of a specified file. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------------- | -------- | ------ | ---- | ---------------------------- | + | uri | Read-only| string | Yes| URI of the file.| + | mimeTypeFilter | Read-only| string | Yes| MIME type of the file.| + +- Return value + + Returns a MIME type array. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.getFileTypes( + "dataability:///com.example.DataAbility", + "image/*" + ).then((data) => { + console.info("==========================>getFileTypesCallback=======================>"); +}); +``` + +#### DataAbilityHelper.normalizeUri(uri: string, callback: AsyncCallback\) + +- Functionality + + Converts the URI that refers to a Data ability into a normalized URI. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | ---------------------- | ---- | ----------------------- | + | uri | Read-only| string | Yes| URI object to normalize.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + Returns the normalized URI object if the Data ability supports URI normalization; returns **null** otherwise. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.normalizeUri( + "dataability:///com.example.DataAbility", + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.normalizeUri(uri: string) + +- Functionality + + Converts the URI that refers to a Data ability into a normalized URI. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---- | -------- | ------ | ---- | ----------------------- | + | uri | Read-only| string | Yes| URI object to normalize.| + +- Return value + + Returns the normalized URI object if the Data ability supports URI normalization; returns **null** otherwise. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.normalizeUri( + "dataability:///com.example.DataAbility", + ).then((data) => { + console.info("==========================>normalizeUriCallback=======================>"); +}); +``` + +#### DataAbilityHelper.denormalizeUri(uri: string, callback: AsyncCallback\) + +- Functionality + + Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: string, callback: AsyncCallback\)** to a denormalized one. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | ---------------------- | ---- | ----------------------- | + | uri | Read-only| string | Yes| URI object to denormalize.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + Returns the denormalized URI object. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.denormalizeUri( + "dataability:///com.example.DataAbility",, + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.denormalizeUri(uri: string) + +- Functionality + + Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: string)** to a denormalized one. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---- | -------- | ------ | ---- | ----------------------- | + | uri | Read-only| string | Yes| URI object to denormalize.| + +- Return value + + Returns the denormalized URI object. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.denormalizeUri( + "dataability:///com.example.DataAbility", + ).then((data) => { + console.info("==========================>denormalizeUriCallback=======================>"); +}); +``` + +#### DataAbilityHelper.notifyChange(uri: string, callback: AsyncCallback\) + +- Functionality + + Notifies the registered observer of a change to the data specified by the URI. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | -------- | -------- | -------------------- | ---- | ------------------------ | + | uri | Read-only| string | Yes| URI of the data.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var helper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +helper.notifyChange( + "dataability:///com.example.DataAbility",, + (err) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.notifyChange(uri: string) + +- Functionality + + Notifies the registered observer of a change to the data specified by the URI. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---- | -------- | ------ | ---- | ------------------------ | + | uri | Read-only| string | Yes| URI of the data.| + +- Return value + + void + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +DAHelper.notifyChange( + "dataability:///com.example.DataAbility", + ).then((void) => { + console.info("==========================>notifyChangeCallback=======================>"); +}); +``` + +#### DataAbilityHelper.insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\) + +- Functionality + + Inserts a single data record into the database. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------ | -------- | ---------------------- | ---- | ------------------------------------------------------ | + | uri | Read-only| string | Yes| URI of the data to insert.| + | valuesBucket | Read-only| rdb.ValuesBucket | Yes| Data record to insert. If this parameter is **null**, a blank row will be inserted.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + Returns the index of the inserted data record. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +const valueBucket = { + "name": "rose", + "age": 22, + "salary": 200.5, + "blobType": u8, +} +DAHelper.insert( + "dataability:///com.example.DataAbility", + valueBucket, + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.insert(uri: string, valuesBucket: rdb.ValuesBucket) + +- Functionality + + Inserts a single data record into the database. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------ | -------- | ---------------- | ---- | ------------------------------------------------------ | + | uri | Read-only| string | Yes| URI of the data to insert.| + | valuesBucket | Read-only| rdb.ValuesBucket | Yes| Data record to insert. If this parameter is **null**, a blank row will be inserted.| + +- Return value + + Returns the index of the inserted data record. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +const valueBucket = { + "name": "rose1", + "age": 221, + "salary": 20.5, + "blobType": u8, +} +DAHelper.insert( + "dataability:///com.example.DataAbility", + valueBucket + ).then((data) => { + console.info("==========================>insertCallback=======================>"); +}); +``` + +#### DataAbilityHelper.batchInsert(uri: string, valuesBuckets: Array, callback: AsyncCallback\) + +- Functionality + + Inserts multiple data records into the database. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------ | -------- | ----------------------- | ---- | ------------------------ | + | uri | Read-only| string | Yes| URI of the data to insert.| + | valuesBucket | Read-only| Array | Yes| Data records to insert.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + Returns the number of inserted data records. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe12", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": u8,}) +DAHelper.batchInsert( + "dataability:///com.example.DataAbility", + cars, + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.batchInsert(uri: string, valuesBuckets: Array) + +- Functionality + + Inserts multiple data records into the database. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------ | -------- | ----------------------- | ---- | ------------------------ | + | uri | Read-only| string | Yes| URI of the data to insert.| + | valuesBucket | Read-only| Array | Yes| Data records to insert.| + +- Return value + + Returns the number of inserted data records. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe12", "age": 21, "salary": 20.5, "blobType": u8,}, + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": u8,}) +DAHelper.batchInsert( + "dataability:///com.example.DataAbility", + cars + ).then((data) => { + console.info("==========================>batchInsertCallback=======================>"); +}); +``` + +#### DataAbilityHelper.delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) + +- Functionality + + Deletes one or more data records from the database. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------ | -------- | --------------------------------- | ---- | ------------------------------------------------ | + | uri | Read-only| string | Yes| URI of the data to delete.| + | valuesBucket | Read-only| dataAbility.DataAbilityPredicates | Yes| Filter criteria. You should define the processing logic when this parameter is **null**.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + Returns the number of deleted data records. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +import ohos_data_ability from '@ohos.data.dataability' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +let da = new ohos_data_ability.DataAbilityPredicates() +DAHelper.delete( + "dataability:///com.example.DataAbility", + da, + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.delete(uri: string, predicates: dataAbility.DataAbilityPredicates) + +- Functionality + + Deletes one or more data records from the database. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------ | -------- | --------------------------------- | ---- | ------------------------------------------------ | + | uri | Read-only| string | Yes| URI of the data to delete.| + | valuesBucket | Read-only| dataAbility.DataAbilityPredicates | Yes| Filter criteria. You should define the processing logic when this parameter is **null**.| + +- Return value + + Returns the number of deleted data records. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +let da = new ohos_data_ability.DataAbilityPredicates() +DAHelper.delete( + "dataability:///com.example.DataAbility", + da + ).then((data) => { + console.info("==========================>deleteCallback=======================>"); +}); +``` + +#### DataAbilityHelper.update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) + +- Functionality + + Updates data records in the database. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------ | -------- | --------------------------------- | ---- | ------------------------------------------------ | + | uri | Read-only| string | Yes| URI of the data to update.| + | valuesBucket | Read-only| rdb.ValuesBucket | Yes| New values.| + | predicates | Read-only| dataAbility.DataAbilityPredicates | Yes| Filter criteria. You should define the processing logic when this parameter is **null**.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + Returns the number of updated data records. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +import ohos_data_ability from '@ohos.data.dataability' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +const va = { + "name": "roe1", + "age": 21, + "salary": 20.5, + "blobType": u8, +} +let da = new ohos_data_ability.DataAbilityPredicates() +DAHelper.update( + "dataability:///com.example.DataAbility", + va, + da, + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + +#### DataAbilityHelper.update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates) + +- Functionality + + Updates data records in the database. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ------------ | -------- | --------------------------------- | ---- | ------------------------------------------------ | + | uri | Read-only| string | Yes| URI of the data to update.| + | valuesBucket | Read-only| rdb.ValuesBucket | Yes| New values.| + | predicates | Read-only| dataAbility.DataAbilityPredicates | Yes| Filter criteria. You should define the processing logic when this parameter is **null**.| + +- Return value + + Returns the number of updated data records. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +import ohos_data_ability from '@ohos.data.dataability' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +const va = { + "name": "roe1", + "age": 21, + "salary": 20.5, + "blobType": u8, +} +let da = new ohos_data_ability.DataAbilityPredicates() +DAHelper.update( + "dataability:///com.example.DataAbility", + va, + da + ).then((data) => { + console.info("==========================>updateCallback=======================>"); +}); +``` + +#### DataAbilityHelper.query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) + +- Functionality + + Queries data in the database. This method uses a callback to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---------- | -------- | --------------------------------- | ---- | ------------------------------------------------ | + | uri | Read-only| string | Yes| URI of the data to query.| + | columns | Read-only| rdb.ValuesBucket | Yes| Columns to query. If this parameter is **null**, all columns will be queried.| + | predicates | Read-only| dataAbility.DataAbilityPredicates | Yes| Filter criteria. You should define the processing logic when this parameter is **null**.| + | callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + Returns the data queried. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +import ohos_data_ability from '@ohos.data.dataability' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +var cars=new Array({"value1"}, {"value2"}, {"value3"}, {"value4"}); +let da = new ohos_data_ability.DataAbilityPredicates() +DAHelper.query( + "dataability:///com.example.DataAbility", + cars, + da, + (err, data) => { + console.info("==========================>Called=======================>"); +}); +``` + + + +#### DataAbilityHelper.query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates) + +- Functionality + + Queries data in the database. This method uses a promise to return the result. + +- Parameters + + | Name| Readable/Writable| Type| Mandatory| Description| + | ---------- | -------- | --------------------------------- | ---- | ------------------------------------------------ | + | uri | Readable and writable| string | Yes| URI of the data to query.| + | columns | Readable and writable| rdb.ValuesBucket | Yes| Columns to query. If this parameter is **null**, all columns will be queried.| + | predicates | Readable and writable| dataAbility.DataAbilityPredicates | Yes| Filter criteria. You should define the processing logic when this parameter is **null**.| + +- Return value + + Returns the data queried. + +- Example + +```js +import featureAbility from '@ohos.ability.featureAbility' +import ohos_data_ability from '@ohos.data.dataability' +var DAHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.DataAbility" +); +var cars=new Array({"value1"}, {"value2"}, {"value3"}, {"value4"}); +let da = new ohos_data_ability.DataAbilityPredicates() +DAHelper.query( + "dataability:///com.example.DataAbility", + cars, + da + ).then((data) => { + console.info("==========================>queryCallback=======================>"); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md new file mode 100644 index 0000000000000000000000000000000000000000..c3f2bb5356a8cd01126493fa92f345e2c1ef76f8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -0,0 +1,350 @@ +# Device Info + +## Modules to Import + +``` +import deviceInfo from '@ohos.deviceInfo' +``` + +## Required Permissions + +None + +## Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

deviceType

+

string

+

Yes

+

No

+

Device type.

+

manufacture

+

string

+

Yes

+

No

+

Device manufacturer.

+

brand

+

string

+

Yes

+

No

+

Device brand.

+

marketName

+

string

+

Yes

+

No

+

External product series.

+

productSeries

+

string

+

Yes

+

No

+

Product series.

+

productModel

+

string

+

Yes

+

No

+

Product model.

+

softwareModel

+

string

+

Yes

+

No

+

Software model.

+

hardwareModel

+

string

+

Yes

+

No

+

Hardware model.

+

hardwareProfile

+

string

+

Yes

+

No

+

Hardware profile.

+

serial

+

string

+

Yes

+

No

+

Device serial number.

+

bootloaderVersion

+

string

+

Yes

+

No

+

Bootloader version.

+

abiList

+

string

+

Yes

+

No

+

Application binary interface (Abi) list.

+

securityPatchTag

+

string

+

Yes

+

No

+

Security patch tag.

+

displayVersion

+

string

+

Yes

+

No

+

Product version.

+

incrementalVersion

+

string

+

Yes

+

No

+

Incremental version.

+

osReleaseType

+

string

+

Yes

+

No

+

Release type. The options are as follows:

+
  • Canary: Preliminary release open only to specific developers. This release does not promise API stability and may require tolerance of instability.
  • Beta: Release open to all developers. This release does not promise API stability and may require tolerance of instability.
  • Release: Official release open to all developers. This release promises that all APIs are stable.
+

osFullName

+

string

+

Yes

+

No

+

OS version.

+

majorVersion

+

number

+

Yes

+

No

+

Major version, incrementing along with OS version updates.

+

seniorVersion

+

number

+

Yes

+

No

+

Senior version, incrementing along with architecture and feature updates.

+

featureVersion

+

number

+

Yes

+

No

+

Feature version.

+

buildVersion

+

number

+

Yes

+

No

+

Build version.

+

sdkApiVersion

+

number

+

Yes

+

No

+

SDK API version.

+

firstApiVersion

+

number

+

Yes

+

No

+

First API version.

+

versionId

+

string

+

Yes

+

No

+

Version ID.

+

buildType

+

string

+

Yes

+

No

+

Build type.

+

buildUser

+

string

+

Yes

+

No

+

Build user.

+

buildHost

+

string

+

Yes

+

No

+

Build host.

+

buildTime

+

string

+

Yes

+

No

+

Build time.

+

buildRootHash

+

string

+

Yes

+

No

+

Build root hash.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..43e248fb82075971c2e32b7fa77003d9ddff5bf3 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -0,0 +1,456 @@ +# Device Management + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import deviceManager from '@ohos.distributedHardware.deviceManager'; +``` + +## deviceManager.createDeviceManager + +createDeviceManager\(bundleName: string, callback: AsyncCallback\): void + +Creates a **DeviceManager** instance. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

bundleName

+

string

+

Yes

+

Bundle name of the application.

+

callback

+

AsyncCallback<DeviceManager>

+

Yes

+

Callback invoked to return the DeviceManager instance created.

+
+ +- Example + + ``` + deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { + if (err) { + console.info("createDeviceManager err:" + JSON.stringify(err)); + return; + } + console.info("createDeviceManager success"); + this.dmInstance = data; + }); + ``` + + +## DeviceStateChangeAction + +Enumerates the device states. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

ONLINE

+

0

+

The device is online.

+

READY

+

1

+

The device is ready, and the device information has been synchronized.

+

OFFLINE

+

2

+

The device is offline.

+

CHANGE

+

3

+

The device information is changed.

+
+ +## DeviceType + +Enumerates device types. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SPEAKER

+

0x0A

+

Smart speaker.

+

PHONE

+

0x0E

+

Phone.

+

TABLET

+

0x11

+

Tablet.

+

WEARABLE

+

0x6D

+

Wearable.

+

TV

+

0x9C

+

Smart TV.

+
+ +## DeviceInfo + +Defines device information. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceId

+

number

+

Yes

+

Unique device identifier.

+

deviceName

+

string

+

Yes

+

Device name.

+

deviceType

+

number

+

Yes

+

Device type.

+
+ +## DeviceManager + +Creates a **DeviceManager** instance to obtain information about trusted devices and local devices. Before calling any method in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**. + +### release + +release\(\): void + +Releases the **DeviceManager** instance that is no longer used. + +- Example + + ``` + dmInstance.release(); + ``` + + +### getTrustedDeviceListSync + +getTrustedDeviceListSync\(\): Array + +Obtains all trusted devices synchronously. + +- Return values + + + + + + + + + + +

Name

+

Description

+

Array<DeviceInfo>

+

List of trusted devices obtained.

+
+ +- Example + + ``` + var deviceInfoList = dmInstance.getTrustedDeviceListSync(); + ``` + + +### on\('deviceStateChange'\) + +on\(type: 'deviceStateChange', callback: Callback<\{ action: DeviceStateChangeAction, device: DeviceInfo \}\>\): void + +Subscribes to changes in the device state. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Event type. The value is deviceStateChange, which indicates a device state change event.

+

callback

+

Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>

+

Yes

+

Callback invoked to return the device information and state.

+
+ + +- Example + + ``` + dmInstance.on('deviceStateChange', (data) => { + console.info("deviceStateChange on:" + JSON.stringify(data)); + } + ); + ``` + + +### off\('deviceStateChange'\) + +off\(type: 'deviceStateChange', callback?: Call back<\{ action: DeviceStateChangeAction, device: DeviceInfo \}\>\): void + +Unsubscribes from changes in the device state. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Event type. The value deviceStateChange indicates an event of device state change.

+

callback

+

Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>

+

Yes

+

Callback used to return the device state changes.

+
+ + +- Example + + ``` + dmInstance.off('deviceStateChange', (data) => { + console.info('deviceStateChange' + JSON.stringify(data)); + } + ); + ``` + + +### on\('serviceDie'\) + +on\(type: 'serviceDie', callback: \(\) =\> void\): void + +Subscribes to dead events of the **DeviceManager** service. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Event type. The value serviceDie indicates an event reported when the DeviceManager service is terminated unexpectedly.

+

callback

+

() => void

+

Yes

+

Callback invoked when a dead event of the DeviceManager service occurs.

+
+ + +- Example + + ``` + dmInstance.on("serviceDie", () => { + console.info("serviceDie on"); + } + ); + ``` + + +### off\('serviceDie'\) + +off\(type: 'serviceDie', callback?: \(\) =\> void\): void + +Unsubscribes from dead events of the **DeviceManager** service. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Event type. The value serviceDie indicates an event reported when the DeviceManager service is terminated unexpectedly.

+

callback

+

() => void

+

No

+

Callback used to return the dead event of the DeviceManager service.

+
+ + +- Example + + ``` + dmInstance.off("serviceDie", () => { + console.info("serviceDie off"); + } + ); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md new file mode 100644 index 0000000000000000000000000000000000000000..5de72ecfb494dbcc6d192b30cff4d5cb290e1f67 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -0,0 +1,436 @@ +# Display + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import display from '@ohos.display'; +``` + +## Required Permissions + +None + +## DisplayState + +Provides the state of a display. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

STATE_UNKNOWN

+

0

+

Unknown.

+

STATE_OFF

+

1

+

The display is shut down.

+

STATE_ON

+

2

+

The display is powered on.

+

STATE_DOZE

+

3

+

The display is in sleep mode.

+

STATE_DOZE_SUSPEND

+

4

+

The display is in sleep mode, and the CPU is suspended.

+

STATE_VR

+

5

+

The display is in VR mode.

+

STATE_ON_SUSPEND

+

6

+

The display is powered on, and the CPU is suspended.

+
+ +## Display + +Describes the attributes of a display. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

id

+

number

+

Yes

+

No

+

ID of the display.

+

name

+

string

+

Yes

+

No

+

Name of the display.

+

alive

+

boolean

+

Yes

+

No

+

Whether the display is alive.

+

state

+

DisplayState

+

Yes

+

No

+

State of the display.

+

refreshRate

+

number

+

Yes

+

No

+

Refresh rate of the display.

+

rotation

+

number

+

Yes

+

No

+

Screen rotation angle of the display.

+

width

+

number

+

Yes

+

No

+

Width of the display, in pixels.

+

height

+

number

+

Yes

+

No

+

Height of the display, in pixels.

+

densityDPI

+

number

+

Yes

+

No

+

Screen density of the display, in DPI.

+

densityPixels

+

number

+

Yes

+

No

+

Screen density of the display, in pixels.

+

scaledDensity

+

number

+

Yes

+

No

+

Scaling factor for fonts displayed on the display.

+

xDPI

+

number

+

Yes

+

No

+

Exact physical dots per inch of the screen in the horizontal direction.

+

yDPI

+

number

+

Yes

+

No

+

Exact physical dots per inch of the screen in the vertical direction.

+
+ +## display.getDefaultDisplay + +getDefaultDisplay\(callback: AsyncCallback\): void; + +Obtains the default display object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Display>

+

Yes

+

Callback used to return the attributes of the default display.

+
+ +- Example + + ``` + var displayClass = null; + display.getDefaultDisplay((err, data) => { + if (err) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + displayClass = data; + }); + ``` + + +## display.getAllDisplay + +getAllDisplay\(callback: AsyncCallback\>\): void; + +Obtains all the display objects. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Array<Display>>

+

Yes

+

Callback used to return the attributes of all displays.

+
+ +- Example + + ``` + display.getAllDisplay((err, data) => { + if (err) { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)) + }); + ``` + + +## display.on\('add'|'remove'|'change'\) + +on\(type: 'add'|'remove'|'change', callback: Callback\): void; + +Enables listening. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type.

+
  • add: listening for whether a display is added
  • remove: listening for whether a display is removed
  • change: listening for whether a display is changed
+

callback

+

Callback<number>

+

Yes

+

Callback used to return the ID of the display.

+
+ +- Example + + ``` + var type = "add"; + var callback = (data) => { + console.info('Listening enabled. Data: ' + JSON.stringify(data)) + } + display.on(type, callback); + ``` + + +## display.off\('add'|'remove'|'change'\) + +off\(type: 'add'|'remove'|'change', callback?: Callback\): void; + +Disables listening. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type.

+
  • add: listening for whether a display is added
  • remove: listening for whether a display is removed
  • change: listening for whether a display is changed
+

callback

+

Callback<number>

+

No

+

Callback used to return the ID of the display.

+
+ +- Example + + ``` + var type = "remove"; + display.off(type); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md new file mode 100644 index 0000000000000000000000000000000000000000..f0eaf4979b085d3376d35bec15450e998d879276 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -0,0 +1,300 @@ +# Distributed Account Management + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import account_distributedAccount from '@ohos.account.distributedAccount'; +``` + +## account\_distributedAccount.getDistributedAccountAbility + +getDistributedAccountAbility\(\): DistributedAccountAbility + +Obtains a **DistributedAccountAbility** instance. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DistributedAccountAbility

+

Instance that provides methods for querying and updating the login state of a distributed account.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + ``` + + +## DistributedAccountAbility + +Provides methods for querying and updating the login state of a distributed account. \(You must obtain a **DistributedAccountAbility** instance first.\) + +### queryOsAccountDistributedInfo + +queryOsAccountDistributedInfo\(callback: AsyncCallback\): void + +Obtains distributed account information. This method uses an asynchronous callback to return the result. + +The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<DistributedInfo>

+

Yes

+

Callback invoked to return the distributed account information.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + accountAbility.queryOsAccountDistributedInfo((err, data) => { + console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }); + ``` + + +### queryOsAccountDistributedInfo + +queryOsAccountDistributedInfo\(\): Promise + +Obtains distributed account information. This method uses a promise to return the result asynchronously. + +The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<DistributedInfo>

+

Promise used to return the result.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + accountAbility.queryOsAccountDistributedInfo().then((data) => { + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }).catch((err) => { + console.log("queryOsAccountDistributedInfoerr: " + JSON.stringify(err)); + }); + ``` + + +### updateOsAccountDistributedInfo + +updateOsAccountDistributedInfo\(accountInfo: DistributedInfo, callback: AsyncCallback\): void + +Updates distributed account information. This method uses an asynchronous callback to return the result. + +The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

accountInfo

+

DistributedInfo

+

Yes

+

Distributed account information.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked when the distributed account information is updated.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { + console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + ``` + + +### updateOsAccountDistributedInfo + +updateOsAccountDistributedInfo\(accountInfo: DistributedInfo\): Promise + +Updates distributed account information. This method uses a promise to return the result asynchronously. + +The **ohos.permission.MANAGE\_LOCAL\_ACCOUNTS** permission is required. This permission is intended for system applications only. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

accountInfo

+

DistributedInfo

+

Yes

+

Distributed account information.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + + ``` + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + accountAbility.updateOsAccountDistributedInfo(accountInfo).then(() => { + console.log('updateOsAccountDistributedInfo Success'); + }).catch((err) => { + console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + ``` + + +## DistributedInfo + +Defines distributed OS account information. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of a distributed account. It must be a non-null string.

+

id

+

string

+

Yes

+

UID of a distributed account. It must be a non-null string.

+

event

+

string

+

Yes

+

Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:

+
  • Ohos.account.event.LOGIN
  • Ohos.account.event.LOGOUT
  • Ohos.account.event.TOKEN_INVALID
  • Ohos.account.event.LOGOFF
+

scalableData

+

object

+

No

+

Extended information about a distributed account. Customized information is passed in key-value pairs.

+

Note: This parameter is reserved and not used in query and update methods.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md new file mode 100644 index 0000000000000000000000000000000000000000..00c4c58a74518ac30199dc98c66f275017fa25a6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -0,0 +1,1490 @@ +# Distributed Data Management + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import distributedData from '@ohos.data.distributedData'; +``` + +## Required Permissions + +None + +## distributedData.createKVManager + +createKVManager\(config: KVManagerConfig, callback: AsyncCallback\): void + +Creates a **KVManager** object to manage key-value \(KV\) stores. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

KVManagerConfig

+

Yes

+

Configuration of the KVManager object, including the bundle name and user information of the caller.

+

callback

+

AsyncCallback<KVManager>

+

Yes

+

Callback invoked to return the KVManager object created.

+
+ +- Example + + ``` + let kvManager; + try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : 0 + } + } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("createKVManager err: " + JSON.stringify(err)); + return; + } + console.log("createKVManager success"); + kvManager = manager; + }); + } catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +## distributedData.createKVManager + +createKVManager\(config: KVManagerConfig\): Promise + +Creates a **KVManager** object to manage KV stores. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

KVManagerConfig

+

Yes

+

Configuration of the KVManager object, including the bundle name and user information of the caller.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<KVManager>

+

Promise used to return the KVManager object created.

+
+ +- Example + + ``` + let kvManager; + try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : 0 + } + } + distributedData.createKVManager(kvManagerConfig).then((manager) => { + console.log("createKVManager success"); + kvManager = manager; + }).catch((err) => { + console.log("createKVManager err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("An unexpected error occurred. Error:" + e); + } + ``` + + +## KVManagerConfig + +Provides configuration of the **KVManager** object, including the bundle name and user information of the caller. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

userInfo

+

UserInfo

+

Yes

+

User information.

+

bundleName

+

string

+

Yes

+

Bundle name.

+
+ +## UserInfo + +Defines user information. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

userId

+

string

+

Yes

+

User ID.

+

userType

+

UserType

+

Yes

+

User type.

+
+ +## UserType + +Defines the user type. + + + + + + + + + + + + +

Name

+

Default 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** to create a **KVManager** object. + +### getKVStore + +getKVStore\(storeId: string, options: Options, callback: AsyncCallback\): void + +Creates and obtains a KV store. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

storeId

+

string

+

Yes

+

Unique identifier of the KV store. The length cannot exceed MAX_STORE_ID_LENGTH.

+

options

+

Options

+

Yes

+

Configuration of the KV store.

+

callback

+

AsyncCallback<T>,

+

<T extends KVStore>

+

Yes

+

Callback invoked to return the KV store created.

+
+ +- Example + + ``` + let kvStore; + try { + const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : 1, + securityLevel : 3, + }; + 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\(storeId: string, options: Options\): Promise + +Creates and obtains a KV store. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

storeId

+

string

+

Yes

+

Unique identifier of the KV store. The length cannot exceed MAX_STORE_ID_LENGTH.

+

options

+

Options

+

Yes

+

Configuration of the KV store.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<T>

+

<T extends KVStore>

+

Promise used to return the KV store created.

+
+ +- Example + + ``` + let kvStore; + try { + const options = { + createIfMissing : true, + encrypt : false, + backup : false, + autoSync : true, + kvStoreType : 1, + securityLevel : 3, + }; + 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); + } + ``` + + +## 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.

+

encrypt

+

boolean

+

No

+

Whether to encrypt database files. By default, database files are not encrypted.

+

backup

+

boolean

+

No

+

Whether to back up database files. By default, database files are backed up.

+

autoSync

+

boolean

+

No

+

Whether database files are automatically synchronized. By default, database files are not automatically synchronized.

+

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.

+

securityLevel

+

SecurityLevel

+

No

+

Security level of the KV store. By default, the security level is not set.

+
+ +## KVStoreType + +Defines the KV store types. + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

DEVICE_COLLABORATION

+

0

+

Device KV store.

+

SINGLE_VERSION

+

1

+

Single KV store.

+

MULTI_VERSION

+

2

+

Multi-version KV store. This type is not supported currently.

+
+ +## SecurityLevel + +Defines the KV store security levels. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default 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.

+

S2

+

3

+

The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database.

+

S3

+

5

+

The KV store security level is high. If data leakage occurs, major impact will be caused on the database.

+

S4

+

6

+

The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database.

+
+ +## Constants + +Defines the KV store constants. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

MAX_KEY_LENGTH

+

1024

+

Maximum length (in bytes) of a key in the KV store.

+

MAX_VALUE_LENGTH

+

4194303

+

Maximum length (in bytes) of a value in the KV store.

+

MAX_KEY_LENGTH_DEVICE

+

896

+

Maximum length of the device coordinate key.

+

MAX_STORE_ID_LENGTH

+

128

+

Maximum length (in bytes) of the KV store ID.

+

MAX_QUERY_LENGTH

+

512000

+

Maximum query length.

+

MAX_BATCH_SIZE

+

128

+

Maximum size of a batch operation.

+
+ +## 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** to create a **KVStore** object. + +### put + +put\(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback\): void + +Adds a key-value pair of the specified type to the KV store. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the key-value pair to add. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

+

value

+

Uint8Array | string | number | boolean

+

Yes

+

Value of the key-value 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.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + 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 + +Adds a key-value pair of the specified type to the KV store. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the key-value pair to add. It cannot be empty, and the length cannot exceed MAX_KEY_LENGTH.

+

value

+

Uint8Array | string | number | boolean

+

Yes

+

Value of the key-value 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.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ + +- Example + + ``` + 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 + +Deletes a KV pair from the KV store. This method uses an asynchronous callback to return the result. + +- 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.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + 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 + +Deletes a KV pair from the KV store. This method uses a promise to return the result. + +- 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.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + + ``` + 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); + } + ``` + + +### on + +on\(event: 'dataChange', type: SubscribeType, observer: Callback\): void + +Subscribes to data changes of the specified type. This method uses a synchronization callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

event

+

'dataChange'

+

Type of the events.

+

type

+

SubscribeType

+

Type of data changes.

+

observer

+

Callback<ChangeNotification>

+

Callback invoked to return the result.

+
+ +- Example + + ``` + kvStore.on('dataChange', 2, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); + }); + ``` + + +### on + +on\(event: 'syncComplete', syncCallback: Callback\>\): void + +Subscribes to notifications of data synchronization completion. This method uses a synchronization callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

event

+

'syncComplete'

+

Type of the events.

+

syncCallback

+

Callback<Array<[string, number]>>

+

Callback invoked to return the result.

+
+ +- Example + + ``` + kvStore.on('syncComplete', function (data) { + console.log("syncComplete callback call data: " + data); + }); + ``` + + +## SubscribeType + +Defines the subscription type. + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SUBSCRIBE_TYPE_LOCAL

+

0

+

Local data changes.

+

SUBSCRIBE_TYPE_REMOTE

+

1

+

Peer data changes.

+

SUBSCRIBE_TYPE_ALL

+

2

+

Local and peer data changes.

+
+ +## ChangeNotification + +Defines the content of data change notifications, including inserted data, updated data, deleted data, and device ID. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

insertEntries

+

Entry[]

+

Yes

+

Yes

+

Data inserted.

+

updateEntries

+

Entry[]

+

Yes

+

Yes

+

Data updated.

+

deleteEntries

+

Entry[]

+

Yes

+

Yes

+

Data deleted.

+

deviceId

+

string

+

Yes

+

Yes

+

UUID of the device.

+
+ +## Entry + +Defines the key-value pairs stored in the database. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

key

+

string

+

Yes

+

Yes

+

Key of the key-value pair stored in the database.

+

value

+

Value

+

Yes

+

Yes

+

Value of the key-value pair stored in the database.

+
+ +## Value + +Defines the value in a key-value pair. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

type

+

ValueType

+

Yes

+

Yes

+

Type of the value.

+

value

+

Uint8Array | string | number | boolean

+

Yes

+

Yes

+

Specific value. A value of the Uint8Array or string type cannot exceed MAX_VALUE_LENGTH.

+
+ +## ValueType + +Defines the types of the value in a key-value pair. + +It can be used only by internal applications. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default 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**. Before calling any method in **SingleKVStore**, you must use **getKVStore** to create a **KVStore** object. + +### get + +get\(key: string, callback: AsyncCallback\): void + +Obtains the value of a specified key. This method uses an asynchronous callback to return the result. + +- 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.

+

callback

+

AsyncCallback<Uint8Array | string | boolean | number>

+

Yes

+

Callback invoked to return the value obtained.

+
+ +- Example + + ``` + 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 + +Obtains the value of a specified key. This method uses a promise to return the result. + +- 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.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Uint8Array | string | boolean | number>

+

Promise used to return the result.

+
+ + +- Example + + ``` + 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); + } + ``` + + +### sync + +sync\(deviceIdList: string\[\], mode: SyncMode, allowedDelayMs?: number\): void + +Triggers synchronization of the KV store, which is in manual synchronization mode. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

deviceIdList

+

string[]

+

Yes

+

List of IDs of the devices in the same networking environment to be synchronized.

+

mode

+

SyncMode

+

Yes

+

Synchronization mode.

+

allowedDelayMs

+

number

+

No

+

Allowed delay time, in ms.

+
+ +- Example + + ``` + kvStore.sync(deviceIds, 1, 1000); + ``` + + +## SyncMode + +Defines the synchronization mode. + + + + + + + + + + + + + + + + + + + + +

Name

+

Default 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-featureAbility.md b/en/application-dev/reference/apis/js-apis-featureAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..88279ca8591d41229d43084cc1cd4dda603dd107 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-featureAbility.md @@ -0,0 +1,714 @@ +# FeatureAbility Module (JavaScript) + +#### Applicable Devices + +| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device| +| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ | +| FeatureAbility.startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.startAbility(parameter: StartAbilityParameter): Promise\ | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.acquireDataAbilityHelper(uri: string): DataAbilityHelper | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.startAbilityForResult(parameter: StartAbilityParameter): Promise\ | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.terminateSelfWithResult(parameter: AbilityResult): Promise\ | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.hasWindowFocus(callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.hasWindowFocus(): Promise\ | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.getWant(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.getWant(): void | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.getContext(): Context | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.terminateSelf(callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.terminateSelf(): Promise\ | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.connectAbility(request: Want, options:ConnectOptions): number | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.disconnectAbility(connection: number, callback:AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| +| FeatureAbility.disconnectAbility(connection: number): Promise\ | Yes| Yes| Yes| Yes| No| No| + +#### Constraints + +APIs of the **FeatureAbility** module can be called only by Page abilities. + +#### Modules to Import + +``` +import featureAbility from '@ohos.ability.featureAbility' +``` + +#### FeatureAbility.startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void + +* Functionality + + Starts an ability. This method uses a callback to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | --------------------- | ---- | ------------------- | +| parameter | Read-only| [StartAbilityParameter](#StartAbilityParameter)| Yes| Ability to start.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + + +- Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +featureAbility.startAbility( + { + want: + { + action: "", + entities: [""], + type: "", + flags: FLAG_AUTH_READ_URI_PERMISSION, + deviceId: "", + bundleName: "com.example.startability", + abilityName: "com.example.startability.MainAbility", + uri: "" + }, + }, + ); +) +``` + + + +#### FeatureAbility.startAbility(parameter: StartAbilityParameter): Promise\ + +* Functionality + + Starts an ability. This method uses a promise to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | ------------------------------------------------------- | ---- | ------------------- | +| parameter | Read-only| [StartAbilityParameter](#StartAbilityParameter)| Yes| Ability to start.| + + +- Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +featureAbility.startAbility( + { + want: + { + action: "action.system.home", + entities: ["entity.system.home"], + type: "MIMETYPE", + flags: FLAG_AUTH_READ_URI_PERMISSION, + deviceId: deviceId, + bundleName: "com.example.startability", + abilityName: "com.example.startability.MainAbility", + uri: "" + }, + } + ).then((void) => { + console.info("==========================>startAbility=======================>"); +}); +``` + + + +#### FeatureAbility.acquireDataAbilityHelper(uri: string): DataAbilityHelper + +* Functionality + + Obtains a **dataAbilityHelper**. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---- | -------- | ------ | ---- | ---------------------- | +| uri | Read-only| string | Yes| URI of the file to open.| + +* Return values + +| Type| Description| +| ----------------- | ------------------------------------------ | +| DataAbilityHelper | A utility class used to help other abilities access the Data ability.| + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +featureAbility.acquireDataAbilityHelper( + "dataability:///com.exmaple.DataAbility" +) +``` + + + +#### FeatureAbility.startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void + +* Functionality + + Starts an ability. This method uses a callback to return the execution result when the ability is destroyed. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | ---------------------- | ---- | ------------------- | +| parameter | Read-only| [StartAbilityParameter](#StartAbilityParameter)| Yes| Ability to start.| +| callback | Read-only| AsyncCallback\<[AbilityResult](#AbilityResult)>| Yes| Callback used to return the result.| + +* Return values + + Returns [AbilityResult](#AbilityResult). + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.startAbilityForResult( + { + want: + { + action: "action.system.home", + entities: ["entity.system.home"], + type: "MIMETYPE", + flags: FLAG_AUTH_READ_URI_PERMISSION, + deviceId: "", + bundleName: "com.example.featureabilitytest", + abilityName: "com.example.featureabilitytest.MainAbility", + uri:"" + }, + }, +) +``` + + + +#### FeatureAbility.startAbilityForResult(parameter: StartAbilityParameter): Promise\ + +* Functionality + + Starts an ability. This method uses a promise to return the execution result when the ability is destroyed. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | ------------------------------------------------------- | ---- | ------------------- | +| parameter | Read-only| [StartAbilityParameter](#StartAbilityParameter)| Yes| Ability to start.| + +* Return values + + Returns [AbilityResult](#AbilityResult). + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.startAbilityForResult( + { + want: + { + action: "action.system.home", + entities: ["entity.system.home"], + type: "MIMETYPE", + flags: FLAG_AUTH_READ_URI_PERMISSION, + deviceId: "", + bundleName: "com.example.featureabilitytest", + abilityName: "com.example.featureabilitytest.MainAbility", + uri:"", + parameters: + { + mykey0: 1111, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "xxxxxxxxxxxxxxxxxxxxxx", + mykey4: [1, 15], + mykey5: [false, true, false], + mykey6: ["aaaaaa", "bbbbb", "ccccccccccc"], + mykey7: true, + }, + }, + requestCode: 2, + }, +).then((void) => { + console.info("==========================>startAbilityForResult=======================>"); +}); +``` + + + +#### FeatureAbility.terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void + +* Functionality + + Destroys this Page ability, with the result code and data sent to the caller. This method uses a callback to return the result. + + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | ------------- | ---- | ------------------- | +| parameter | Read-only| [AbilityResult](#AbilityResult)| Yes| Ability to start.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +featureAbility.terminateSelfWithResult( + { + resultCode: 1, + want: + { + action: "action.system.home", + entities: ["entity.system.home"], + type: "MIMETYPE", + flags: FLAG_AUTH_READ_URI_PERMISSION, + deviceId: "", + bundleName: "com.example.featureabilitytest", + abilityName: "com.example.featureabilitytest.MainAbility", + uri:"", + parameters: { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [1, 15], + mykey5: [false, true, false], + mykey6: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey7: true, + } + }, + }, +); +``` + + + +#### FeatureAbility.terminateSelfWithResult(parameter: AbilityResult): Promise\ + +* Functionality + + Destroys this Page ability, with the result code and data sent to the caller. This method uses a promise to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | --------------------------------------- | ---- | ------------------- | +| parameter | Read-only| [AbilityResult](#AbilityResult)| Yes| Ability to start.| + + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.terminateSelfWithResult( + { + resultCode: 1, + want: + { + action: "action.system.home", + entities: ["entity.system.home"], + type: "MIMETYPE", + flags: FLAG_AUTH_READ_URI_PERMISSION, + deviceId: "", + bundleName: "com.example.featureabilitytest", + abilityName: "com.example.featureabilitytest.MainAbility", + uri:"", + parameters: { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [1, 15], + mykey5: [false, true, false], + mykey6: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey7: true, + } + }, + } +).then((void) => { + console.info("==========================>terminateSelfWithResult=======================>"); +}); +``` + + + +#### FeatureAbility.hasWindowFocus(callback: AsyncCallback\): void + +* Functionality + + Checks whether the main window of this ability has the focus. This method uses a callback to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ----------------------- | ---- | ---------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +* Return values + + Returns **true** if the main window of this ability has the focus; returns **false** otherwise. + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.hasWindowFocus() +``` + + + +#### FeatureAbility.hasWindowFocus(): Promise\ + +* Functionality + + Checks whether the main window of this ability has the focus. This method uses a promise to return the result. + +* Parameters + + None + +* Return values + + Returns **true** if the main window of this ability has the focus; returns **false** otherwise. + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.hasWindowFocus().then((void) => { + console.info("==========================>hasWindowFocus=======================>"); +}); +``` + + + +#### FeatureAbility.getWant(callback: AsyncCallback\) + +* Functionality + + Obtains the **Want** object sent from this ability. This method uses a callback to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | -------------------- | ---- | ---------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.getWant() +``` + + + +#### FeatureAbility.getWant(): void + +* Functionality + + Obtains the **Want** object sent from this ability. This method uses a promise to return the result. + +* Parameters + + None + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.getWant().then((void) => { + console.info("==========================>getWantCallBack=======================>"); +}); +``` + + + +#### FeatureAbility.getContext(): Context + +* Functionality + + Obtains the application context. + +* Return values + + Returns the application context. + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +var context = featureAbility.getContext() +context.getBundleName() +``` + + + +#### FeatureAbility.terminateSelf(callback: AsyncCallback\): void + +* Functionality + + Destroys this Page ability, with the result code and data sent to the caller. This method uses a callback to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | -------------------- | ---- | ---------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.terminateSelf() +``` + + + +#### FeatureAbility.terminateSelf(): Promise\ + +* Functionality + + Destroys this Page ability, with the result code and data sent to the caller. This method uses a promise to return the result. + +* Parameters + + None + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureability'; +featureAbility.terminateSelf().then((void) => { console.info("==========================>terminateSelfCallBack=======================>"); +}); +``` + +#### FeatureAbility.connectAbility(request: Want, options:ConnectOptions): number + +* Functionality + + Connects this ability to a specific Service ability. This method uses a callback to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------- | -------- | -------------- | ---- | -------------------------- | +| request | Read-only| Want | Yes| Service ability to connect.| +| options | Read-only| ConnectOptions | Yes| Callback used to return the result.| + +* Want parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------------ | -------- | -------- | ---- | ---------------------------------- | +| deviceId | Read-only| string | No| Device ID of the Service ability to connect. The default value is the local device ID.| +| bundleName | Read-only| string | Yes| Bundle name of the Service ability to connect.| +| abilityName | Read-only| string | Yes| Class name of the Service ability to connect.| + +- ConnectOptions + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------------ | -------- | -------- | ---- | ---------------------------------- | +| onConnect | Read-only| function | Yes| Callback invoked when the connection is successful.| +| onDisconnect | Read-only| function | Yes| Callback invoked when the connection fails.| +| onFailed | Read-only| function | Yes| Callback invoked when **connectAbility** fails to be called.| + +* Return values + + Returns the ID of the Service ability connected. + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + deviceId: deviceId, + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` + +#### FeatureAbility.disconnectAbility(connection: number, callback:AsyncCallback\): void + +* Functionality + + Disconnects this ability from a specific Service ability. This method uses a callback to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ------------- | ---- | ------------------------------ | +| connection | Read-only| number | Yes| ID of the Service ability to disconnect.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +var result = featureAbility.disconnectAbility(connId, + (error,data) => { + console.log('featureAbilityTest DisConnectJsSameBundleName result errCode : ' + error.code + " data: " + data) + }, +); +``` + +#### FeatureAbility.disconnectAbility(connection: number): Promise\ + +* Functionality + + Disconnects this ability from a specific Service ability. This method uses a promise to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ------ | ---- | ------------------------------ | +| connection | Read-only| number | Yes| ID of the Service ability to disconnect.| + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = featureAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +var result = await featureAbility.disconnectAbility(connId); +``` + + +#### FeatureAbility.continueAbility(options: ContinueAbilityOptions, callback: AsyncCallback\): void; + +* Functionality + + Migrates an ability to another device. This method uses a callback to return the execution result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ---------------------- | ---- | ------------------- | +| options | Read-only| ContinueAbilityOptions | Yes| Ability to migrate.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- ContinueAbilityOptions + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ------- | ---- | ----------------------------------------------------------- | +| deviceId | Read-only| string | Yes| Information about the ability to migrate.| +| reversible | Read-only| boolean | Yes| Whether migration back is supported. Currently, this feature is not supported. This parameter is reserved and can be set to **false**.| + +* Example + +```javascript +import featureAbility from '@ohos.ability.featureAbility' + +async StartContinueAbility(deviceId) { + let continueAbilityOptions = { + reversible: false, + deviceId: deviceId, + } + function ContinueAbilityCallback(err, data) { + console.info("[Demo] ContinueAbilityCallback, result err = " + JSON.stringify(err)); + console.info("[Demo] ContinueAbilityCallback, result data= " + JSON.stringify(data)); + } + await featureAbility.continueAbility(continueAbilityOptions, ContinueAbilityCallback); + console.info('[Demo] featureAbility.StartContinueAbility end'); +} +this.StartContinueAbility(remoteDeviceId); //remoteDeviceId is acquired from DeviceManager +``` + +#### AbilityResult + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | --------------------- | ---- | ------------------------------------------------------------ | +| resultCode | Read-only| number | Yes| Result code returned after the ability is destroyed. The feature for defining error-specific result codes is coming soon.| +| want | Read-only| [Want](#Want)| No| Data returned after the ability is destroyed. You can define the data to be returned. This parameter can be **null**.| + +#### StartAbilityParameter + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------------------- | -------- | --------------------- | ---- | ------------------------------------------------------------ | +| want | Read-only| [Want](#Want)| Yes| Information about the ability to start.| +| abilityStartSetting | Read-only| {[key: string]: any} | No| Special attribute of the ability to start. This attribute can be passed in the method call.| + +#### Want + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | Read-only| string | No| ID of the device that runs the ability.| +| bundleName | Read-only| string | No| Bundle name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| abilityName | Read-only| string | No| Name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| 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, a number is passed. For details, see [flags](#flags).| +| action | Read-only| string | No| Action option.| +| parameters | Read-only| {[key: string]: any} | No| List of parameters in a **Want** object.| +| entities | Read-only| Array\ | No| List of entities.| + +## flags + +| Name| Name| Description| +| ------------------------------------ | ---------- | ------------------------------------------------------------ | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI.| +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI.| +| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability.| +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device.| +| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS.| +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability.| +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.| +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.| +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler.| +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started.| +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible.| +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed.| +| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed.| +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object passed to **ohos.app.Context#startAbility** and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack.| +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md new file mode 100644 index 0000000000000000000000000000000000000000..2b6aa580963fbac78fa9b2676edfc46147593b70 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -0,0 +1,2051 @@ +# File Management + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import fileio from '@ohos.fileio'; +``` + +## Required Permissions + +None + +## Usage + +Before using this module to perform operations on a file or directory, you must obtain the absolute path of the file or directory. For details, see **getOrCreateLocalDir** in the **Context** module. + + +Absolute file or directory path = Application directory path + File name or directory name + +For example, if the application directory obtained by using the API is _dir_ and the file name is _file name_**.txt**, the absolute path of the file is as follows: + +``` +let path = dir + "file name.txt" +``` + +The file descriptor is as follows: + +``` +let fd = fileio.openSync(path); +``` + +## fileio.statSync + +statSync\(path:string\): Stat + +Synchronously obtains file information. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Stat

+

Detailed file information.

+
+ +- Example + + ``` + let stat = fileio.statSync(path); + ``` + + +## fileio.opendirSync + +opendirSync\(path: string\): Dir + +Synchronously opens a directory. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the directory to open.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Dir

+

An instance of the Dir class corresponding to a directory.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(path); + ``` + + +## fileio.accessSync + +accessSync\(path: string, mode?: number\): void + +Synchronously checks whether the current process can access a file. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+

mode

+

number

+

No

+

Options for accessing the file. You can specify multiple options, separated with a bitwise OR operator (|). The default value is 0.

+

The options are as follows:

+
  • 0: Check whether the file exists.
+
  • 1: Check whether the current process has the execute permission on the file.
  • 2: Check whether the current process has the write permission on the file.
  • 4: Check whether the process has the read permission on the file.
+
+ +- Example + + ``` + fileio.accessSync(path); + ``` + + +## fileio.closeSync + +closeSync\(fd: number\): void + +Synchronously closes a file. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to close.

+
+ +- Example + + ``` + fileio.closeSync(fd); + ``` + + +## fileio.copyFileSync + +fileio.copyFileSync\(src: string, dest: string, mode?:number\): void + +Synchronously copies a file. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

src

+

string

+

Yes

+

Path of the file to copy.

+

dest

+

string

+

Yes

+

Target file path.

+

mode

+

number

+

No

+

Option for overwriting the file of the same name in the destination path. The default value is 0, which is the only value supported.

+

0: Overwrite the file with the same name completely and truncate the part that is not overwritten.

+
+ +- Example + + ``` + fileio.copyFileSync(src, dest); + ``` + + +## fileio.mkdirSync + +fileio.mkdirSync\(path: string, mode?: number\): void + +Synchronously creates a directory. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the directory to create.

+

mode

+

number

+

No

+

Permission on the directory to create. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is 0o775.

+
  • 0o775: The owner has the read, write, and execute permissions, and other users have the read and execute permissions on the directory.
  • 0o700: The owner has the read, write, and execute permissions on the directory.
  • 0o400: The owner has the read permission on the directory.
  • 0o200: The owner has the write permission on the directory.
  • 0o100: The owner has the execute permission on the directory.
  • 0o070: The user group has the read, write, and execute permissions on the directory.
  • 0o040: The user group has the read permission on the directory.
  • 0o020: The user group has the write permission on the directory.
  • 0o010: The user group has the execute permission on the directory.
  • 0o007: Other users have the read, write, and execute permissions on the directory.
  • 0o004: Other users have the read permission on the directory.
  • 0o002: Other users have the write permission on the directory.
  • 0o001: Other users have the execute permission on the directory.
+
+ +- Example + + ``` + fileio.mkdirSync(path); + ``` + + +## fileio.openSync + +openSync\(path: string, flags?: number, mode?: number\): number + +Synchronously opens a file. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the file to open.

+

flags

+

number

+

No

+

Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.

+
  • 0o0: Open file in read-only mode.
  • 0o1: Open file in write-only mode.
  • 0o2: Open file in read/write mode.
+

In addition, you can specify the following options using a bitwise OR operator (|). By default, no additional option is specified.

+
  • 0o100: If the file does not exist, create a file. If you use this option, you must also specify mode.
  • 0o200: If 0o100 is added and the file already exists, throw an exception.
  • 0o1000: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
  • 0o2000: Open the file in append mode. New data will be appended to the file (written to the end of the file).
  • 0o4000: If path points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
  • 0o200000: If path points to a directory, throw an exception.
  • 0o400000: If path points to a symbolic link, throw an exception.
  • 0o4010000: Open the file in synchronous I/O mode.
+

mode

+

number

+

No

+

Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is 0o666.

+
  • 0o666: The owner, user group, and other users have the read and write permissions on the file.
  • 0o700: The owner has the read, write, and execute permissions on the file.
  • 0o400: The owner has the read permission on the directory.
  • 0o200: The owner has the write permission on the directory.
  • 0o100: The owner has the execute permission on the directory.
  • 0o070: All user groups have the read, write, and execute permissions on the directory.
  • 0o040: All user groups have the read permission on the directory.
  • 0o020: All user groups have the write permission on the directory.
  • 0o010: All user groups have the execute permission on the directory.
  • 0o007: Other users have the read, write, and execute permissions on the directory.
  • 0o004: Other users have the read permission on the directory.
  • 0o002: Other users have the write permission on the directory.
  • 0o001: Other users have the execute permission on the directory.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

File descriptor of the file opened.

+
+ +- Example + + ``` + fileio.openSync(path); + ``` + + +## fileio.readSync + +readSync\(fd: number, buffer: ArrayBuffer, options?: Object\): number + +Synchronously reads data from a file. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to read.

+

buffer

+

ArrayBuffer

+

Yes

+

Buffer used for reading the file.

+

options

+

Object

+

No

+

The options are as follows:

+
  • offset (number): position of the buffer to which the data will be read in reference to the start address of the buffer. It is optional. The default value is 0.
  • length (number): length of the data to read. It is optional. The default value is the buffer length minus the offset.
  • position (number): position of the data to read in the file. It is optional. By default, data is read from the current position.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Length of the data read.

+
+ +- Example + + ``` + let fd = fileio.openSync(path, 0o2); + let buf = new ArrayBuffer(4096); + fileio.readSync(fd, buf); + console.log(String.fromCharCode.apply(null, new Uint8Array(buf))); + ``` + + +## fileio.rmdirSync + +rmdirSync\(path: string\): void + +Synchronously removes a directory. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the directory to remove.

+
+ +- Example + + ``` + fileio.rmdirSync(path); + ``` + + +## fileio.unlinkSync + +unlinkSync\(path: string\): void + +Synchronously deletes a file. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the file to delete.

+
+ +- Example + + ``` + fileio.unlinkSync(path); + ``` + + +## fileio.writeSync + +writeSync\(fd: number, buffer: ArrayBuffer | string, options?:Object\): number + +Synchronously writes data to a file. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to write.

+

buffer

+

ArrayBuffer | string

+

Yes

+

A string or data from a buffer to be written to the file.

+

options

+

Object

+

No

+

The options are as follows:

+
  • offset (number): position of the data to write in reference to the start address of the data. It is optional. The default value is 0.
  • length (number): length of the data to write. It is optional. The default value is the buffer length minus the offset.
  • position (number): position of the data to be written in the file. It is optional. By default, data is written from the current position.
  • encoding (string): format of the data to be encoded. You must set it when the data is a string. The default value is utf-8. Only utf-8 is supported.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Length of the data written in the file.

+
+ +- Example + + ``` + let fd = fileio.openSync(path, 0o102, 0o666); + fileio.writeSync(fd, "hello, world"); + ``` + + +## fileio.chmodSync7+ + +chmodSync\(path: string, mode: number\): void + +Synchronously changes the file permissions based on its path. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+

mode

+

number

+

Yes

+

Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).

+
  • 0o700: The owner has the read, write, and execute permissions on the directory.
  • 0o400: The owner has the read permission on the directory.
  • 0o200: The owner has the write permission on the directory.
  • 0o100: The owner has the execute permission on the directory.
  • 0o070: The user group has the read, write, and execute permissions on the directory.
  • 0o040: The user group has the read permission on the directory.
  • 0o020: The user group has the write permission on the directory.
  • 0o010: The user group has the execute permission on the directory.
  • 0o007: Other users have the read, write, and execute permissions on the directory.
  • 0o004: Other users have the read permission on the directory.
  • 0o002: Other users have the write permission on the directory.
  • 0o001: Other users have the execute permission on the directory.
+
+ +- Example + + ``` + fileio.chmodSync(fpath, mode); + ``` + + +## fileio.fstatSync7+ + +fstatSync\(fd: number\): Stat + +Synchronously obtains file status information based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the target file.

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Stat>

+

File status information obtained.

+
+ + +- Example + + ``` + let fd = fileio.openSync(path); + let stat = fileio.fstatSync(fd); + ``` + + +## fileio.ftruncateSync7+ + +ftruncateSync\(fd: number, len?: number\): void + +Synchronously truncates a file based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to truncate.

+

len

+

number

+

No

+

File length, in bytes, after truncation.

+
+ + +- Example + + ``` + fileio.ftruncate(fd, len); + ``` + + +## fileio.fchmodSync7+ + +fchmodSync\(existingPath: string, newPath: string\): void + +Synchronously changes the file permissions based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the target file.

+

mode

+

number

+

Yes

+

Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|).

+
  • 0o700: The owner has the read, write, and execute permissions on the file.
  • 0o400: The owner has the read permission on the directory.
  • 0o200: The owner has the write permission on the directory.
  • 0o100: The owner has the execute permission on the directory.
  • 0o070: The user group has the read, write, and execute permissions on the directory.
  • 0o040: The user group has the read permission on the directory.
  • 0o020: The user group has the write permission on the directory.
  • 0o010: The user group has the execute permission on the directory.
  • 0o007: Other users have the read, write, and execute permissions on the directory.
  • 0o004: Other users have the read permission on the directory.
  • 0o002: Other users have the write permission on the directory.
  • 0o001: Other users have the execute permission on the directory.
+
+ +- Example + + ``` + fileio.fchmodSync(fd, mode); + ``` + + +## fileio.truncateSync7+ + +truncateSync\(fpath: string, len?: number\): void + +Synchronously truncates a file based on the file path. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the file to truncate.

+

len

+

number

+

No

+

File length, in bytes, after truncation.

+
+ + +- Example + + ``` + fileio.ftruncate(path, len); + ``` + + +## fileio.renameSync7+ + +renameSync\(oldPath: string, newPath: string\): void + +Synchronously renames a file. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

oldPath

+

string

+

Yes

+

Absolute path of the file to rename.

+

Newpath

+

String

+

Yes

+

Absolute path of the file renamed.

+
+ +- Example + + ``` + fileio.renameSync(oldpath, newpath); + ``` + + +## fileio.fsyncSync7+ + +fsyncSync\(fd: number\): void + +Synchronizes a file in synchronous mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the file to synchronize.

+
+ +- Example + + ``` + fileio.fyncsSync)(fd); + ``` + + +## fileio.chownSync7+ + +chownSync\(path: string, uid: number, gid: number\): void + +Synchronously changes the file owner based on its path. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+

uid

+

number

+

Yes

+

New UID.

+

gid

+

number

+

Yes

+

New GID.

+
+ +- Example + + ``` + let stat = fileio.statSync(fpath) + fileio.chownSync(path, stat.uid, stat.gid); + ``` + + +## fileio.createStreamSync7+ + +createStreamSync\(path: string, mode: string\): Stream + +Synchronously opens a stream based on the file path. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Absolute path of the target file.

+

mode

+

string

+

Yes

+
  • r: Open a file for reading. The file must exist.
  • r+: Open a file for both reading and writing. The file must exist.
  • w: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
  • w+: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
  • a: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
  • a+: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
+
+ + +- Return values + + + + + + + + + + +

Name

+

Description

+

Stream

+

Stream operation result.

+
+ +- Example + + ``` + let ss = fileio.createStream(path, "r+"); + ``` + + +## fileio.fdopenStreamSync7+ + +fdopenStreamSync\(fd: number, mode: string\): Stream + +Synchronously opens a stream based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the target file.

+

mode

+

string

+

Yes

+
  • r: Open a file for reading. The file must exist.
  • r+: Open a file for both reading and writing. The file must exist.
  • w: Open a file for writing. If the file exists, clear its content. If the file does not exist, create a file.
  • w+: Open a file for both reading and writing. If the file exists, clear its content. If the file does not exist, create a file.
  • a: Open a file in append mode for writing at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
  • a+: Open a file in append mode for reading or updating at the end of the file. If the file does not exist, create a file. If the file exists, write data to the end of the file (the original content of the file is reserved).
+
+ + +- Return values + + + + + + + + + + +

Name

+

Description

+

Stream

+

Stream operation result.

+
+ +- Example + + ``` + let ss = fileio.fdopenStreamSync(fd, "r+"); + ``` + + +## fileio.fchownSync7+ + +fchownSync\(fd: number, uid: number, gid: number\): void + +Synchronously changes the file owner based on the file descriptor. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fd

+

number

+

Yes

+

File descriptor of the target file.

+

uid

+

number

+

Yes

+

New UID.

+

gid

+

number

+

Yes

+

New GID.

+
+ +- Example + + ``` + let stat = fileio.statSync(fpath); + fileio.fchownSync(fd, stat.uid, stat.gid); + ``` + + +## Stat + +Provides detailed file information. Before invoking a method of the **Stat** class, use the [fileio.statSync](#section014281412198) method to create a **Stat** instance. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

dev

+

number

+

Yes

+

No

+

Major device number.

+

ino

+

number

+

Yes

+

No

+

File ID. Different files on the same device have different inos.

+

mode

+

number

+

Yes

+

No

+

File type and permission. The first four bits indicate the file type, and the last 12 bits indicate the permission. The bit fields are described follows:

+
  • 0o170000: mask used to obtain the file type.
  • 0o140000: The file is a socket.
  • 0o120000: The file is a symbolic link.
  • 0o100000: The file is a regular file.
  • 0o060000: The file is a block device.
  • 0o040000: The file is a directory.
  • 0o020000: The file is a character device.
  • 0o010000: The file is a named pipe (also known as a FIFO).
  • 0o0700: mask used to obtain owner permissions.
  • 0o0400: The owner has the read permission on a regular file or a directory entry.
  • 0o0200: The owner has the permission to write a regular file or has the permission to create and delete a directory entry.
  • 0o0100: The owner has the permission to execute a regular file or has the permission to search for the specified path in a directory.
  • 0o0070: mask used to obtain user group permissions.
  • 0o0040: The user group has the read permission on a regular file or a directory entry.
  • 0o0020: The user group has the permission to write a regular file or has the permission to create and delete a directory entry.
  • 0o0010: The user group has the permission to execute a regular file or has the permission to search for the specified path in a directory.
  • 0o0007: mask used to obtain permissions of other users.
  • 0o0004: Other user groups have the read permission on a regular file or a directory entry.
  • 0o0002: Other user groups have the permission to write a regular file or have the permission to create and delete a directory entry.
  • 0o0001: Other user groups have the permission to execute a regular file or have the permission to search for the specified path in a directory.
+

nlink

+

number

+

Yes

+

No

+

Number of hard links in the file.

+

uid

+

number

+

Yes

+

No

+

ID of the file owner.

+

gid

+

number

+

Yes

+

No

+

ID of the user group of the file.

+

rdev

+

number

+

Yes

+

No

+

Minor device number.

+

size

+

number

+

Yes

+

No

+

File size, in bytes. This parameter is valid only for regular files.

+

blocks

+

number

+

Yes

+

No

+

Number of blocks occupied by a file. Each block is 512 bytes.

+

atime

+

number

+

Yes

+

No

+

Time of the last access of file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.

+

mtime

+

number

+

Yes

+

No

+

Time of the last modification of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.

+

ctime

+

number

+

Yes

+

No

+

Time of the last status change of the file. The value is the number of seconds elapsed since 00:00:00 on January 1, 1970.

+
+ +### isBlockDevice + +isBlockDevice\(\): boolean + +Checks whether a directory entry is a block special file. A block special file supports access by block only, and it is cached when accessed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a block special file.

+
+ +- Example + + ``` + let isBLockDevice = fileio.statSync(path).isBlockDevice(); + ``` + + +### isCharacterDevice + +isCharacterDevice\(\): boolean + +Checks whether a directory entry is a character special file. A character special file supports random access, and it is not cached when accessed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a character special file.

+
+ +- Example + + ``` + let isCharacterDevice = fileio.statSync(path).isCharacterDevice(); + ``` + + +### isDirectory + +isDirectory\(\): boolean + +Checks whether a directory entry is a directory. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a directory.

+
+ +- Example + + ``` + let isDirectory= fileio.statSync(path).isDirectory(); + ``` + + +### isFIFO + +isFIFO\(\): boolean + +Checks whether a directory entry is a named pipe \(or FIFO\). Named pipes are used for inter-process communication. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a FIFO.

+
+ +- Example + + ``` + let isFIFO= fileio.statSync(path).isFIFO(); + ``` + + +### isFile + +isFile\(\): boolean + +Checks whether a directory entry is a regular file. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a regular file.

+
+ +- Example + + ``` + let isFile= fileio.statSync(fpath).isFile(); + ``` + + +### isSocket + +isSocket\(\): boolean + +Checks whether a directory entry is a socket. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a socket.

+
+ +- Example + + ``` + let isSocket = fileio.statSync(path).isSocket(); + ``` + + +### isSymbolicLink + +isSymbolicLink\(\): boolean + +Checks whether a directory entry is a symbolic link. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a symbolic link.

+
+ +- Example + + ``` + let isSymbolicLink = fileio.statSync(path).isSymbolicLink(); + ``` + + +## Stream7+ + +File stream. Before calling a method of the **Stream** class, use the [fileio.createStreamSync](#section1956102153713) method to create a **Stream** instance. + +### closeSync7+ + +closeSync\(\): void + +Synchronously closes the stream. + +- Example + + ``` + let ss= fileio.createStreamSync(path); + ss.closeSync(); + ``` + + +### flushSync7+ + +flushSync\(\): void + +Synchronously flushes the stream. + +- Example + + ``` + let ss= fileio.createStreamSync(path); + ss.flushSync(); + ``` + + +### writeSync7+ + +writeSync\(buffer: ArrayBuffer | string, options?:Object\): number + +Synchronously writes data into the stream. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

buffer

+

ArrayBuffer | string

+

Yes

+

A string or data from a buffer to be written to the file.

+

options

+

Object

+

No

+

The options are as follows:

+
  • offset (number): position of the data to write in reference to the start address of the data. It is optional. The default value is 0.
  • length (number): length of the data to write. It is optional. The default value is the buffer length minus the offset.
  • position (number): position of the data to be written in the file. It is optional. By default, data is written from the current position.
  • encoding (string): format of the data to be encoded. You must set it when the data is a string. The default value is utf-8. Only utf-8 is supported.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Length of the data written in the file.

+
+ +- Example + + ``` + let ss= fileio.createStreamSync(fpath,"r+"); + ss.writeSync("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}); + ``` + + +### readSync7+ + +readSync\(buffer: ArrayBuffer, options?: Object\): number + +Synchronously reads data from the stream. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

buffer

+

ArrayBuffer

+

Yes

+

Buffer used for reading the file.

+

options

+

Object

+

No

+

The options are as follows:

+
  • offset (number): position of the buffer to which the data will be read in reference to the start address of the buffer. It is optional. The default value is 0.
  • length (number): length of the data to read. It is optional. The default value is the buffer length minus the offset.
  • position (number): position of the data to read in the file. It is optional. By default, data is read from the current position.
+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Length of the data read.

+
+ +- Example + + ``` + let ss = fileio.createStreamSync(fpath, "r+"); + ss.readSync(new ArrayBuffer(4096),{offset: 1,length: FILE_CONTENT.length,position: 5}); + ``` + + +## Dir + +Manages directories. Before calling a method of the **Dir** class, use the [fileio.opendirSync](#section7741145112216) method to create a **Dir** instance. + +### readSync + +readSync\(\): Dirent + +Synchronously reads the next directory entry. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Dirent

+

Directory entry read.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let dirent = dir.readSync(); + console.log(dirent.name); + ``` + + +### closeSync + +closeSync\(\): void + +Closes a directory. After a directory is closed, the file descriptor in **Dir** will be released and the directory entry cannot be read from **Dir**. + +- Example + + ``` + let dir = fileio.opendirSync(dpath); + dir.closeSync(); + ``` + + +## Dirent + +Provides information about files and directories. Before calling a method of the **Dirent** class, use the [readSync](#section10198204912710) method to create a **Dirent** instance. + +### Attributes + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

name

+

string

+

Yes

+

No

+

Directory entry name.

+
+ +### isBlockDevice + +isBlockDevice\(\): boolean + +Checks whether a directory entry is a block device file. A block special file supports access by block only, and it is cached when accessed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a block device file.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isBLockDevice = dir.readSync().isBlockDevice(); + ``` + + +### isCharacterDevice + +isCharacterDevice\(\): boolean + +Checks whether a directory entry is a character device file. A character special file supports random access, and it is not cached when accessed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a character device file.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isCharacterDevice = dir.readSync().isCharacterDevice(); + ``` + + +### isDirectory + +isDirectory\(\): boolean + +Checks whether a directory entry is a directory. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a directory.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isDirectory = dir.readSync().isDirectory(); + ``` + + +### isFIFO + +isFIFO\(\): boolean + +Checks whether a directory entry is a named pipe \(or FIFO\). Named pipes are used for inter-process communication. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a FIFO.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isFIFO = dir.readSync().isFIFO(); + ``` + + +### isFile + +isFile\(\): boolean + +Checks whether a directory entry is a regular file. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a regular file.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isFile = dir.readSync().isFile(); + ``` + + +### isSocket + +isSocket\(\): boolean + +Checks whether a directory entry is a socket. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a socket.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isSocket = dir.readSync().isSocket(); + ``` + + +### isSymbolicLink + +isSymbolicLink\(\): boolean + +Checks whether a directory entry is a symbolic link. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the directory entry is a symbolic link.

+
+ +- Example + + ``` + let dir = fileio.opendirSync(dpath); + let isSymbolicLink = dir.readSync().isSymbolicLink(); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md new file mode 100644 index 0000000000000000000000000000000000000000..cc9dad8a12182393f6bafe668d9633210a2829ad --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -0,0 +1,418 @@ +# HiAppEvent + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import hiAppEvent from '@ohos.hiAppEvent'; +``` + +## Required Permissions + +None. + +## hiAppEvent.write + +write\(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback\): void + +Writes event information to the event file of the current day. This function supports JSON parameters and uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

eventName

+

string

+

Yes

+

Indicates the application event name.

+

eventType

+

EventType

+

Yes

+

Indicates the application event type.

+

keyValues

+

object

+

Yes

+

Indicates an array of JSON parameters of the application event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

+

callback

+

AsyncCallback<void>

+

No

+

Indicates the callback function, which can be used to process the received return value.

+
  • Value 0 indicates that the event verification is successful, and the event will be written to the event file asynchronously.
  • A value greater than 0 indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
  • A value smaller than 0 indicates that the event verification fails, and the event will not be written to the event file.
+
+ +- Example + + ``` + hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => { + if (err) { + // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + console.error(`failed to write event because ${err.code}`); + return; + } + + // Event writing succeeded. + console.log(`success to write event: ${value}`); + }); + ``` + + +## hiAppEvent.write + +write\(eventName: string, eventType: EventType, keyValues: object\): Promise + +Writes event information to the event file of the current day. This function supports JSON parameters and uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

eventName

+

string

+

Yes

+

Indicates the application event name.

+

eventType

+

EventType

+

Yes

+

Indicates the application event type.

+

keyValues

+

object

+

Yes

+

Indicates an array of JSON parameters of the application event. A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to process the callback in the then() and catch() methods when event writing succeeded or failed.

+
+ +- Example + + ``` + hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}) + .then((value) => { + // Event writing succeeded. + console.log(`success to write event: ${value}`); + }).catch((err) => { + // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + console.error(`failed to write event because ${err.code}`); + }); + ``` + + +## hiAppEvent.configure + +configure\(config: ConfigOption\): boolean + +Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

config

+

ConfigOption

+

Yes

+

Configuration items for application event logging.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the configuration is successful; returns false otherwise.

+
+ +- Example + + ``` + // Configure the application event logging switch. + hiAppEvent.configure({ + disable: true + }); + + // Configure the maximum size of the directory that stores the event logging files. + hiAppEvent.configure({ + maxStorage: '100M' + }); + ``` + + +## ConfigOption + +Provides the configuration items for application event logging. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

disable

+

boolean

+

No

+

Application event logging switch. The value true means to disable the application event logging function, and the value false means the opposite.

+

maxStorage

+

string

+

No

+

Maximum size of the event file storage directory. The default value is 10M. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space.

+
+ +## EventType + +Enumerates event types. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

FAULT

+

1

+

Fault event

+

STATISTIC

+

2

+

Statistical event

+

SECURITY

+

3

+

Security event

+

BEHAVIOR

+

4

+

Behavior event

+
+ +## Event + +Provides constants that define the names of all predefined events. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

USER_LOGIN

+

string

+

Yes

+

No

+

User login event.

+

USER_LOGOUT

+

string

+

Yes

+

No

+

User logout event.

+

DISTRIBUTED_SERVICE_START

+

string

+

Yes

+

No

+

Distributed service startup event.

+
+ +## Param + +Provides constants that define the names of all predefined event parameters. + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

USER_ID

+

string

+

Yes

+

No

+

Custom user ID.

+

DISTRIBUTED_SERVICE_NAME

+

string

+

Yes

+

No

+

Distributed service name.

+

DISTRIBUTED_SERVICE_INSTANCE_ID

+

string

+

Yes

+

No

+

Distributed service instance ID.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md new file mode 100644 index 0000000000000000000000000000000000000000..6f684c8c06d674c9cc43cc409acd1c2e962129f7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -0,0 +1,255 @@ +# Internationalization \(i18n\) + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- This module contains enhanced i18n APIs, which are not defined in ECMA 402. + + +## Modules to Import + +``` +import i18n from '@ohos.i18n'; +``` + +## Required Permissions + +None + +## i18n.getDisplayLanguage + +getDisplayLanguage\(language: string, locale: string, sentenceCase?: boolean\): string + +Obtains the localized script for the specified language. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

language

+

string

+

Yes

+

Specified language.

+

locale

+

string

+

Yes

+

Locale ID.

+

sentenceCase

+

boolean

+

No

+

Whether to use sentence case for the localized script.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Localized script for the specified language.

+
+ +- Example + + ``` + i18n.getDisplayLanguage("zh", "en-GB", true); + i18n.getDisplayLanguage("zh", "en-GB"); + ``` + + +## i18n.getDisplayCountry + +getDisplayCountry\(country: string, locale: string, sentenceCase?: boolean\): string + +Obtains the localized script for the specified country. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

country

+

string

+

Yes

+

Specified country.

+

locale

+

string

+

Yes

+

Locale ID.

+

sentenceCase

+

boolean

+

No

+

Whether to use sentence case for the localized script.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Localized script for the specified country.

+
+ +- Example + + ``` + i18n.getDisplayCountry("zh-CN", "en-GB", true); + i18n.getDisplayCountry("zh-CN", "en-GB"); + ``` + + +## i18n.getSystemLanguage + +getSystemLanguage\(\): string + +Obtains the system language. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

System language ID.

+
+ +- Example + + ``` + i18n.getSystemLanguage(); + ``` + + +## i18n.getSystemRegion + +getSystemRegion\(\): string + +Obtains the system region. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

System region ID.

+
+ +- Example + + ``` + i18n.getSystemRegion(); + ``` + + +## i18n.getSystemLocale + +getSystemLocale\(\): string + +Obtains the system locale. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

System locale ID.

+
+ +- Example + + ``` + i18n.getSystemLocale(); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md new file mode 100644 index 0000000000000000000000000000000000000000..7d182fd07eb55b848088f153625278a4e469e405 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -0,0 +1,1180 @@ +# Internationalization \(intl\) + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- This module contains standard i18n APIs, which are defined in ECMA 402. + + +## Modules to Import + +``` +import Intl from '@ohos.intl'; +``` + +## Required Permissions + +None + +## Locale + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

language

+

string

+

Yes

+

No

+

Language associated with the locale.

+

script

+

string

+

Yes

+

No

+

Script type of the language.

+

region

+

string

+

Yes

+

No

+

Region associated with the locale.

+

baseName

+

string

+

Yes

+

No

+

Basic information about the locale.

+

caseFirst

+

string

+

Yes

+

No

+

Whether case is taken into account for the locale's collation rules.

+

calendar

+

string

+

Yes

+

No

+

Calendar for the locale.

+

collation

+

string

+

Yes

+

No

+

Collation rules for the locale.

+

hourCycle

+

string

+

Yes

+

No

+

Time system for the locale.

+

numberingSystem

+

string

+

Yes

+

No

+

Numbering system for the locale.

+

numeric

+

boolean

+

Yes

+

No

+

Whether to apply special collation rules for numeric characters.

+
+ +### constructor + +constructor\(locale: string, options?:options\) + +Creates a **Locale** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

A string containing locale information, including the language, optional script, and locale.

+

options

+

options

+

No

+

Options for creating the Locale object.

+
+ + +- Example + + ``` + var locale = new Intl.Locale("zh-CN"); + ``` + + +### toString + +toString\(\): string + +Converts locale information to a string. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

String containing locale information.

+
+ + +- Example + + ``` + var locale = new Intl.Locale("zh-CN"); + locale.toString(); + ``` + + +### maximize + +maximize\(\): Locale + +Maximizes information of the **Locale** object. If the script and locale information is missing, add the information. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Locale

+

Locale object with the maximized information.

+
+ + +- Example + + ``` + var locale = new Intl.Locale("zh-CN"); + locale.maximize(); + ``` + + +### minimize + +minimize\(\): Locale + +Minimizes information of the **Locale** object. If the script and locale information is present, delete the information. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Locale

+

Locale object with the minimized information.

+
+ + +- Example + + ``` + var locale = new Intl.Locale("zh-CN"); + locale.minimize(); + ``` + + +## DateTimeFormat + +### constructor + +constructor\(locale: string, options?:DateTimeOptions\) + +Creates a **DateTimeOptions** object for the specified locale. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

A string containing locale information, including the language, optional script, and locale.

+

options

+

DateTimeOptions

+

No

+

Options of the DateTimeFormat object.

+
+ + +- Example + + ``` + var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); + ``` + + +### constructor + +constructor\(locales: Array, options?:DateTimeOptions\) + +Creates a **DateTimeOptions** object for the specified array of locales. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locales

+

Array<string>

+

Yes

+

An array of strings containing locale information.

+

options

+

DateTimeOptions

+

No

+

Options of the DateTimeFormat object.

+
+ + +- Example + + ``` + var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); + ``` + + +### format + +format\(date: Date\): string; + +Formats the specified date and time. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

date

+

Date

+

Yes

+

Date and time to be formatted.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

A string containing the formatted date and time.

+
+ + +- Example + + ``` + var date = new Date(2021, 11, 17, 3, 24, 0); + var datefmt = new Intl.DateTimeFormat("en-GB"); + datefmt.format(date); + ``` + + +### formatRange + +formatRange\(fromDate: Date, toDate: Date\): string; + +Formats the specified date range. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

startDate

+

Date

+

Yes

+

Start date and time to be formatted.

+

endDate

+

Date

+

Yes

+

End date and time to be formatted.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

A string containing the formatted date and time range.

+
+ + +- Example + + ``` + var startDate = new Date(2021, 11, 17, 3, 24, 0); + var endDate = new Date(2021, 11, 18, 3, 24, 0); + var datefmt = new Intl.DateTimeFormat("en-GB"); + datefmt.formatRange(startDate, endDate); + ``` + + +### resolvedOptions + +resolvedOptions\(\): DateTimeOptions + +Obtains the options of the **DateTimeFormat** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

DateTimeOptions

+

Options of the DateTimeFormat object.

+
+ + +- Example + + ``` + var datefmt = new Intl.DateTimeFormat("en-GB"); + datefmt.resolvedOptions(); + ``` + + +## NumberFormat + +### constructor + +constructor\(locale: string, options?:NumberOptions\) + +Creates a **NumberFormat** object for the specified locale. + +Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

A string containing locale information, including the language, optional script, and locale.

+

options

+

NumberOptions

+

No

+

Options of the NumberFormat object.

+
+ +- Example + + ``` + var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); + ``` + + +### constructor + +constructor\(locales: Array, options?:NumberOptions\) + +Creates a **NumberFormat** object for the specified array of locales. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locales

+

Array<string>

+

Yes

+

An array of strings containing locale information.

+

options

+

NumberOptions

+

No

+

Options of the NumberFormat object.

+
+ + +- Example + + ``` + var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + ``` + + +### format + +format\(number: number\): string; + +Formats a number. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

number

+

number

+

Yes

+

Number to be formatted.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Formatted number.

+
+ + +- Example + + ``` + var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + numfmt.format(1223); + ``` + + +### resolvedOptions + +resolvedOptions\(\): NumberOptions + +Obtains the options of the **NumberFormat** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

NumberOptions

+

Options of the NumberFormat object.

+
+ + +- Example + + ``` + var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + numfmt.resolvedOptions(); + ``` + + +## DateTimeOptions + +Provides the options for the **DateTimeFormat** object. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

locale

+

string

+

Yes

+

No

+

Locale information.

+

dateStyle

+

string

+

Yes

+

Yes

+

Date display format. The value can be long, short, medium, or full.

+

timeStyle

+

string

+

Yes

+

Yes

+

Time display format. The value can be long, short, medium, or full.

+

hourCycle

+

string

+

Yes

+

Yes

+

Hour cycle. The value can be h11, h12, h23, or h24.

+

timeZone

+

string

+

Yes

+

Yes

+

Time zone represented by a valid IANA time zone ID.

+

numberingSystem

+

string

+

Yes

+

Yes

+

Numbering system.

+

hour12

+

boolean

+

Yes

+

Yes

+

Whether to use the 12-hour clock.

+

weekday

+

string

+

Yes

+

Yes

+

Workday display format. The value can be long, short, or narrow.

+

era

+

string

+

Yes

+

Yes

+

Era display format. The value can be long, short, or narrow.

+

year

+

string

+

Yes

+

Yes

+

Year display format. The value can be numeric or 2-digit.

+

month

+

string

+

Yes

+

Yes

+

Month display format. The value can be numeric, 2-digit, long, short, or narrow.

+

day

+

string

+

Yes

+

Yes

+

Day display format. The value can be numeric or 2-digit.

+

hour

+

string

+

Yes

+

Yes

+

Hour display format. The value can be numeric or 2-digit.

+

minute

+

string

+

Yes

+

Yes

+

Minute display format. The value can be numeric or 2-digit.

+

second

+

string

+

Yes

+

Yes

+

Second display format. The value can be numeric or 2-digit.

+

timeZoneName

+

string

+

Yes

+

Yes

+

Localized representation of a time zone name.

+

dayPeriod

+

string

+

Yes

+

Yes

+

Time period display format. The value can be long, short, or narrow.

+

localeMatcher

+

string

+

Yes

+

Yes

+

Locale matching algorithm. The value can be lookup or best fit.

+

formatMatcher

+

string

+

Yes

+

Yes

+

Format matching algorithm. The value can be basic or best fit.

+
+ +## NumberOptions + +Provides the device capability. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

locale

+

string

+

Yes

+

No

+

Locale information.

+

currency

+

string

+

Yes

+

Yes

+

Currency for the specified locale.

+

currencySign

+

string

+

Yes

+

Yes

+

Currency symbol.

+

currencyDisplay

+

string

+

Yes

+

Yes

+

Currency display mode. The value can be symbol, narrowSymbol, code, or name.

+

unit

+

string

+

Yes

+

Yes

+

Currency unit.

+

unitDisplay

+

string

+

Yes

+

Yes

+

Currency unit display format. The value can be long, short, or medium.

+

signDisplay

+

string

+

Yes

+

Yes

+

Number sign display format. The value can be auto, never, always, or expectZero.

+

compactDisplay

+

string

+

Yes

+

Yes

+

Compact display format. The value can be long or short.

+

notation

+

string

+

Yes

+

Yes

+

Number notation. The value can be standard, scientific, engineering, or compact.

+

localeMatcher

+

string

+

Yes

+

Yes

+

Locale matching algorithm. The value can be lookup or best fit.

+

style

+

string

+

Yes

+

Yes

+

Number display format. The value can be decimal, currency, percent, or unit.

+

numberingSystem

+

string

+

Yes

+

Yes

+

Numbering system.

+

useGrouping

+

boolean

+

Yes

+

Yes

+

Whether to enable grouping for display.

+

miniumumIntegerDigits

+

number

+

Yes

+

Yes

+

Minimum number of integer digits.

+

miniumumFractionDigits

+

number

+

Yes

+

Yes

+

Minimum number of fraction digits.

+

maxiumumFractionDigits

+

number

+

Yes

+

Yes

+

Maximum number of fraction digits.

+

miniumumSignificantDigits

+

number

+

Yes

+

Yes

+

Minimum number of significant digits.

+

maxiumumSignificantDigits

+

number

+

Yes

+

Yes

+

Maximum number of significant digits.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md new file mode 100644 index 0000000000000000000000000000000000000000..d4430fd798d4ef558605cb65e7463d2e1c646921 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -0,0 +1,407 @@ +# Audio Playback and Recording + +## Modules to Import + +``` +import media from '@ohos.multimedia.media'; +``` + +## Required Permissions + +None + +## media.createAudioPlayer + +Creates an **AudioPlayer** instance. + +**Return values** + +| Type | Description | +| --------------------------- | ------------------------------------------------------------ | +| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. | + +**Example** + +``` +var audioplayer = media.createAudioPlayer(); +``` + +## media.createAudioRecorder + +createAudioRecorder(): AudioRecorder + +Creates an **AudioRecorder** instance to control audio recording. + +**Return values** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. | + +**Example** + +``` +var audiorecorder = media.createAudioRecorder(); +``` + +## AudioPlayer + +Manages and plays audio. Before calling a method of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ----------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | +| src | string | Yes | Yes | Audio media URI. Popular audio formats (mp4, aac, mp3, and ogg) are supported. The value can be a local absolute path starting with **file://**. | +| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop playback. | +| currentTime | number | Yes | No | Current playback position. | +| duration | number | Yes | No | Audio duration. | +| state | [AudioState](#audiostate) | Yes | No | Playback status. | + +### play + +play\(\): void + +Starts audio playback. + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('play', () => { + console.log('Playback starts.'); +}); +audioplayer.play(); +``` + +### pause + +pause\(\): void + +Pauses audio playback. + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('pause', () => { + console.log('Playback paused.'); +}); +audioplayer.pause(); +``` + + +### stop + +stop\(\): void + +Stops audio playback. + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('stop',() => { + console.log('Playback stopped.'); +}); +audioplayer.stop(); +``` + + +### seek + +seek\(timeMs: number\): void + +Seeks to the specified playback position. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ----------------------------- | +| timeMs | number | Yes | Playback position to seek to. | + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('timeupdate', (action) => { + var newTime = audioplayer.currenTime; + if(newTime >= 30000) { + console.info('Seek succeeded. New time: ' + newTime); + } else { + console.info('Seek failed.'); + } +}); +audioplayer.seek(30000); +``` + +### setVolume + +setVolume\(vol: number\): void + +Sets the volume. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%). | + +**Example** + +``` +audioplayer.src = 'file:///data/media/sounds.mp4'; +audioplayer.on('volumeChange', () => { + console.log('Playback volume changed.'); +}); +audioplayer.setVolume(1); +``` + +### reset7+ + +reset\(\): void + +Switches the audio resource to be played. + +**Example** + +``` +audioplay.reset(); +``` + +### release + +release\(\): void + +Releases audio resources. + +**Example** + +``` +audioplay.release(); +``` + +### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') + +Listens for audio playback events. + +on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void) + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the playback event to listen for. The following events are supported: **play**, **pause**, **stop**, **reset**, **dataLoad**, **finish**, and **volumeChange**.
- The **play** event is triggered when audio playback starts.
- The **pause** event is triggered when audio playback is paused.
- The **stop** event is triggered when audio playback stops.
- The **reset** event is triggered when the player is reset.
- The **dataLoad** event is triggered when audio data is loaded.
- The **finish** event is triggered when audio playback is finished.
- The **volumeChange** event is triggered when the playback volume changes. | +| callback | function | Yes | Callback used to listen for the playback event. | + +**Example** + +``` +audioplayer.src = 'file://xxx/sounds.mp4'; +audioplayer.on('play', () => { + console.log('Playback starts.'); +}); +audioplayer.play(); +``` + +### on('timeUpdate') + +on(type: 'timeUpdate', callback: Callback\): void + +Listens for audio playback timestamp update events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the playback event to listen for. Only the **timeUpdate** event is supported.
- The **timeUpdate** event is triggered when the audio playback timestamp is updated. It is also triggered when the **seek** method is called. | +| callback | Callback<number> | Yes | Callback used to listen for the playback event. | + +**Example** + +``` +audioplayer.src = 'file://xxx/sounds.mp4'; +audioplayer.on('timeupdate', (newTime ) => { + if(newTime >= 30000) { + console.info('Seek succeeded. New time: ' + newTime); + } else { + console.info('Seek failed.'); + } +}); +audioplayer.seek(30000); +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Listens for playback error events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the playback error event to listen for.
- The **error** event is triggered when an error occurs during audio playback. | +| callback | ErrorCallback | Yes | Callback used to listen for the playback event. | + +**Example** + +``` +audioplayer.src = 'file:///data/sounds.mp4'; +audioplayer.on('error', (err) => { + console.info('error callback info: ' + err); +}); +audioplayer.setVolume(30000); +``` + + +## AudioState + +Describes the audio playback state. + +| Name | Description | +| ------- | -------------------------- | +| idle | Audio playback is idle. | +| playing | The audio is being played. | +| paused | Audio playback is paused. | +| stopped | Audio playback is stopped. | + +## AudioRecorder + +Provides methods to record audio. Before calling an **AudioRecorder** method, you must use [createAudioRecorder\(\)](#mediacreateaudiorecorder) to create an **AudioRecorder** instance. + +### prepare + +prepare(config: AudioRecorderConfig): void + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------------------------------------------- | --------- | ------------------------------------------------------------ | +| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels | + +**Example** + + ``` + let audioRecorderConfig = { + audioEncoder : AAC_LC , + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : AAC_ADTS, + uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', + } + audiorecorder.prepare(audioRecorderConfig) + ``` +### start + +start(): void + +Starts audio recording. + +**Example** + +``` +audiorecorder.start(); +``` + +### stop + +stop(): void + +Stops audio recording. + +**Example** + +``` +audiorecorder.stop(); +``` + +### release + +release(): void + +**Example** + +``` +audiorecorder.release(); +``` + +### reset + +reset(): void + +Resets audio recording. + +Before resetting audio recording, you must call **stop\(\)** to stop recording. After audio recording is reset, you must call **prepare\(\)** to set the recording configurations for another recording. + +**Example** + +``` +audiorecorder.reset(); +``` + +### on('prepare' | 'start' | 'stop' | 'release' | 'reset') + +on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void + +Listens for audio recording events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the audio recording event to listen for. The following events are supported: **prepare**, **start**, **stop**, **release**, and **reset**.
- The **prepare** event is triggered when the audio recording preparation is complete.
- The **start** event is triggered when audio recording starts.
- The **stop** event is triggered when audio recording stops.
- The **release** event is triggered when resources related to audio recording are released.
- The **reset** event is triggered when audio recording is reset. | +| callback | function | Yes | Callback used to listen for the audio recording event. | + +**Example** + +``` +audiorecorder.on('prepare', () => { + console.log('Preparation succeeded.'); + audiorecorder.start(); +}); +``` + +### on('error') + +on(type: 'error', callback: ErrorCallback): void + +Listens for audio recording error events. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Type of the audio recording error event to listen for.
- The **error** event is triggered when an error occurs during audio recording. | +| callback | function | Yes | Callback used to listen for the audio recording event. | + +## AudioRecorderConfig + +Describes audio recording configurations. + +| Name | Type | Mandatory | Description | +| ------------------ | --------------------------------------- | --------- | ------------------------------------------------------------ | +| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**. | +| audioEncodeBitRate | number | No | Bit rate for audio encoding. The default value is **48000**. | +| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**. | +| numberOfChannels | number | No | Number of audio channels. The default value is **2**. | +| format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**. | +| uri | string | Yes | Audio output URI. The following types of URIs are supported:
1. Absolute path:
file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. Path with the file descriptor (FD): file://1 (FD number) | + +## AudioEncoder + +Enumerates audio encoding formats. + +| Name | Default Value | Description | +| ------ | ------------- | ---------------------------------------------- | +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC). | + +## AudioOutputFormat + +Enumerates audio output formats. + +| Name | Default Value | Description | +| -------- | ------------- | ------------------------------------------------------------ | +| MPEG_4 | 2 | MPEG-4. | +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), a transmission stream format of Advanced Audio Coding (AAC) audio. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..1e4bbafcd5e8928ab009a869bddfbb2debb8f1c4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -0,0 +1,3267 @@ +# Notification Module + +## Applicable Devices + +| API | Phone | Tablet | Smart TV | Wearable | +| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | +| Notification.publish(request: NotificationRequest, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.publish(request: NotificationRequest) | Yes | Yes | Yes | Yes | +| Notification.cancel(id: number, label: string, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.cancel(id:number, label?:string) | Yes | Yes | Yes | Yes | +| Notification.cancel(id: number, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.cancelAll(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.cancelAll() | Yes | Yes | Yes | Yes | +| Notification.addSlot(slot: NotificationSlot, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.addSlot(slot: NotificationSlot) | Yes | Yes | Yes | Yes | +| Notification.addSlot(type: SlotType, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.addSlot(type: SlotType) | Yes | Yes | Yes | Yes | +| Notification.addSlots(slots: Array\, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.addSlots(slots: Array\) | Yes | Yes | Yes | Yes | +| Notification.getSlot(slotType: SlotType, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.getSlot(slotType: SlotType) | Yes | Yes | Yes | Yes | +| Notification.getSlots(callback: AsyncCallback>) | Yes | Yes | Yes | Yes | +| Notification.getSlots() | Yes | Yes | Yes | Yes | +| Notification.removeSlot(slotType: SlotType, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.removeSlot(slotType: SlotType) | Yes | Yes | Yes | Yes | +| Notification.removeAllSlots(callback: AsyncCallback\): void | Yes | Yes | Yes | Yes | +| Notification.removeAllSlots(): Promise\ | Yes | Yes | Yes | Yes | +| Notification.subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo) | Yes | Yes | Yes | Yes | +| Notification.unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.unsubscribe(subscriber: NotificationSubscriber) | Yes | Yes | Yes | Yes | +| Notification.enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.enableNotification(bundle: BundleOption, enable: boolean) | Yes | Yes | Yes | Yes | +| Notification.isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.isNotificationEnabled(bundle: BundleOption) | Yes | Yes | Yes | Yes | +| Notification.isNotificationEnabled(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.isNotificationEnabled() | Yes | Yes | Yes | Yes | +| Notification.displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.displayBadge(bundle: BundleOption, enable: boolean) | Yes | Yes | Yes | Yes | +| Notification.isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.isBadgeDisplayed(bundle: BundleOption) | Yes | Yes | Yes | Yes | +| Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot) | Yes | Yes | Yes | Yes | +| Notification.getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>) | Yes | Yes | Yes | Yes | +| Notification.getSlotsByBundle(bundle: BundleOption) | Yes | Yes | Yes | Yes | +| Notification.getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.getSlotNumByBundle(bundle: BundleOption) | Yes | Yes | Yes | Yes | +| Notification.remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.remove(bundle: BundleOption, notificationKey: NotificationKey) | Yes | Yes | Yes | Yes | +| Notification.remove(hashCode: string, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.remove(hashCode: string) | Yes | Yes | Yes | Yes | +| Notification.removeAll(bundle: BundleOption, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.removeAll(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.removeAll(bundle?: BundleOption) | Yes | Yes | Yes | Yes | +| Notification.getAllActiveNotifications(callback: AsyncCallback>) | Yes | Yes | Yes | Yes | +| Notification.getAllActiveNotifications() | Yes | Yes | Yes | Yes | +| Notification.getActiveNotificationCount(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.getActiveNotificationCount() | Yes | Yes | Yes | Yes | +| Notification.getActiveNotifications(callback: AsyncCallback>) | Yes | Yes | Yes | Yes | +| Notification.getActiveNotifications() | Yes | Yes | Yes | Yes | +| Notification.cancelGroup(groupName: string, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.cancelGroup(groupName: string) | Yes | Yes | Yes | Yes | +| Notification.removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.removeGroupByBundle(bundle: BundleOption, groupName: string) | Yes | Yes | Yes | Yes | +| Notification.setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.setDoNotDisturbDate(date: DoNotDisturbDate) | Yes | Yes | Yes | Yes | +| Notification.getDoNotDisturbDate(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.getDoNotDisturbDate() | Yes | Yes | Yes | Yes | +| Notification.supportDoNotDisturbMode(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| Notification.supportDoNotDisturbMode() | Yes | Yes | Yes | Yes | +| WantAgent.getWantAgent(info: WantAgentInfo, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| WantAgent.getWantAgent(info: WantAgentInfo): Promise\ | Yes | Yes | Yes | Yes | +| WantAgent.getBundleName(agent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| WantAgent.getBundleName(agent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | +| WantAgent.getUid(agent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| WantAgent.getUid(agent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | +| WantAgent.getWant(agent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| WantAgent.getWant(agent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | +| WantAgent.cancel(agent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| WantAgent.cancel(agent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | +| WantAgent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) | Yes | Yes | Yes | Yes | +| WantAgent.equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | +| WantAgent.equal(agent: WantAgent, otherAgent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | + + +## Required Permissions + +None + + +## Modules to Import + +```js +import Notification from '@ohos.notification'; +``` + +## Notification.publish(request: NotificationRequest, callback: AsyncCallback\) + +- Functionality + + Publishes a notification. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ------------------------------------------- | +| request | Read-only| NotificationRequest | Yes| Notification to publish.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- NotificationRequest + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------------------- | -------- | --------------------------------------------- | ---- | -------------------------- | +| content | Readable and writable| NotificationContent | Yes| Notification content.| +| id | Readable and writable| number | No| Notification ID.| +| slotType | Readable and writable| SlotType | No| Notification slot type.| +| isOngoing | Readable and writable| boolean | No| Whether the notification is an ongoing notification.| +| isUnremovable | Readable and writable| boolean | No| Whether the notification can be removed.| +| deliveryTime | Readable and writable| number | No| Time when the notification is sent.| +| tapDismissed | Readable and writable| boolean | No| Whether the notification can be automatically cleared.| +| autoDeletedTime | Readable and writable| number | No| Time when the notification is automatically cleared.| +| wantAgent | Readable and writable| WantAgent | No| **WantAgent** object to which the notification will be redirected after being clicked.| +| extraInfo | Readable and writable| {[key: string]: any} | No| Extended parameter.| +| color | Readable and writable| number | No| Background color of the notification.| +| colorEnabled | Readable and writable| boolean | No| Whether the notification background color is enabled.| +| isAlertOnce | Readable and writable| boolean | No| Whether the notification triggers an alert only once.| +| isStopwatch | Readable and writable| boolean | No| Whether to display the stopwatch.| +| isCountDown | Readable and writable| boolean | No| Whether to display the countdown time.| +| isFloatingIcon | Readable and writable| boolean | No| Whether the notification is displayed as a floating icon.| +| label | Readable and writable| string | No| Notification label.| +| badgeIconStyle | Readable and writable| number | No| Notification badge type.| +| showDeliveryTime | Readable and writable| boolean | No| Whether to display the time when the notification is delivered.| +| actionButtons | Readable and writable| Array\ | No| Buttons in the notification. Up to two buttons are allowed.| +| smallIcon | Readable and writable| PixelMap | No| Small notification icon.| +| largeIcon | Readable and writable| PixelMap | No| Large notification icon.| +| creatorBundleName | Read-only| string | No| Name of the bundle that creates the notification.| +| creatorUid | Read-only| number | No| UID of the notification creator.| +| creatorPid | Read-only| number | No| PID of the notification creator.| +| hashCode | Read-only| string | No| Unique ID of the notification.| +| classification | Readable and writable| string | No| Notification category.| +| groupName | Readable and writable| string | No| Notification group name.| +| template8+ | Readable and writable| [NotificationTemplate](#notificationtemplate) | No| Notification template.| + +NotificationContent + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----------- | -------- | ---------------------------- | ---- | ------------------ | +| contentType | Readable and writable| ContentType | Yes| Notification content type.| +| normal | Readable and writable| NotificationBasicContent | No| Normal text.| +| longText | Readable and writable| NotificationLongTextContent | No| Long text.| +| multiLine | Readable and writable| NotificationMultiLineContent | No| Multi-line text.| +| picture | Readable and writable| NotificationPictureContent | No| Picture-attached.| + +- ContentType + +| Name| Readable/Writable| Type| Description| +| --------------------------------- | -------- | ----------- | ---------------- | +| NOTIFICATION_CONTENT_BASIC_TEXT | Read-only| ContentType | Normal text notification.| +| NOTIFICATION_CONTENT_LONG_TEXT | Read-only| ContentType | Long text notification.| +| NOTIFICATION_CONTENT_PICTURE | Read-only| ContentType | Picture-attached notification.| +| NOTIFICATION_CONTENT_CONVERSATION | Read-only| ContentType | Conversation notification.| +| NOTIFICATION_CONTENT_MULTILINE | Read-only| ContentType | Multi-line text notification.| + +- NotificationBasicContent + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------- | -------- | ------ | ---- | -------------------------------- | +| title | Readable and writable| string | Yes| Notification title.| +| text | Readable and writable| string | Yes| Notification content.| +| additionalText | Readable and writable| string | Yes| Additional information of the notification.| + +- NotificationLongTextContent + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------- | -------- | ------ | ---- | -------------------------------- | +| title | Readable and writable| string | Yes| Notification title.| +| text | Readable and writable| string | Yes| Notification content.| +| additionalText | Readable and writable| string | Yes| Additional information of the notification.| +| longText | Readable and writable| string | Yes| Long text content of the notification.| +| briefText | Readable and writable| string | Yes| Brief text of the notification.| +| expandedTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| + +- NotificationMultiLineContent + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------- | -------- | --------------- | ---- | -------------------------------- | +| title | Readable and writable| string | Yes| Notification title.| +| text | Readable and writable| string | Yes| Notification content.| +| additionalText | Readable and writable| string | Yes| Additional information of the notification.| +| briefText | Readable and writable| string | Yes| Brief text of the notification.| +| longTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| +| lines | Readable and writable| Array\ | Yes| Multi-line content.| + +- NotificationPictureContent + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------- | -------- | -------------- | ---- | -------------------------------- | +| title | Readable and writable| string | Yes| Notification title.| +| text | Readable and writable| string | Yes| Notification content.| +| additionalText | Readable and writable| string | Yes| Additional information of the notification.| +| briefText | Readable and writable| string | Yes| Brief text of the notification.| +| expandedTitle | Readable and writable| string | Yes| Title of the notification in the expanded state.| +| picture | Readable and writable| image.PixelMap | Yes| Picture included in the notification.| + +- SlotType + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------------- | -------- | -------- | ---- | -------- | +| SOCIAL_COMMUNICATION | Read-only| SlotType | No| Notification slot for social communication.| +| SERVICE_INFORMATION | Read-only| SlotType | No| Notification slot for service information.| +| CONTENT_INFORMATION | Read-only| SlotType | No| Notification slot for content consultation.| +| OTHER_TYPES | Read-only| SlotType | No| Notification slot for other purposes.| + +- NotificationActionButton + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | --------------------- | ---- | ------------------------- | +| title | Readable and writable| string | Yes| Button title.| +| wantAgent | Readable and writable| wantAgent | Yes| **WantAgent** of the button.| +| extras | Readable and writable| Array\ | No| Extra information of the button.| +| icon | Readable and writable| image.PixelMap | No| Button icon.| +| userInput | Readable and writable| NotificationUserInput | No| User input object.| + +- NotificationUserInput + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ------ | ---- | ----------------------------- | +| inputKey | Readable and writable| string | Yes| Key to identify the user input.| + + +- Return value + + void + +- Example + +```js +// publish callback +function publishCallback(err) { + console.info("==========================>publishCallback=======================>"); +} +// NotificationRequest object +var notificationRequest = { + id: 1, + content: { + contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} +Notification.publish(notificationRequest, publishCallback) +``` + + + +## Notification.publish(request: NotificationRequest) + +- Functionality + + Publishes a notification. This method uses a promise to return the result. + +- Return value + + Promise\ + +- Example + +```js +// NotificationRequest object +var notificationRequest = { + notificationId: 1, + content: { + contentType: notify.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} +Notification.publish(notificationRequest).then((void) => { + console.info("==========================>publishCallback=======================>"); +}); + +``` + + + +## Notification.cancel(id: number, label: string, callback: AsyncCallback\) + +- Functionality + + Cancels a notification with the specified ID and label. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| id | Read-only| number | Yes| Notification ID.| +| label | Read-only| string | Yes| Notification label.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +// cancel callback +function cancelCallback(err) { + console.info("==========================>cancelCallback=======================>"); +} +Notification.cancel(0, "label", cancelCallback) +``` + + + +## Notification.cancel(id: number, label? : string) + +- Functionality + + Cancels a notification with the specified ID and label. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----- | -------- | ------ | ---- | -------- | +| id | Read-only| number | Yes| Notification ID.| +| label | Read-only| string | No| Notification label.| + +- Return value + + Promise\ + +- Example + +```js +Notification.cancel(0).then((void) => { + console.info("==========================>cancelCallback=======================>"); +}); +``` + + + +## Notification.cancel(id: number, callback: AsyncCallback\) + +- Functionality + + Cancels a notification with the specified ID. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| id | Read-only| number | Yes| Notification ID.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +// cancel callback +function cancelCallback(err) { + console.info("==========================>cancelCallback=======================>"); +} +Notification.cancel(0, cancelCallback) +``` + + + +## Notification.cancelAll(callback: AsyncCallback\) + +- Functionality + + Cancels all notifications. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +// cancel callback +function cancelAllback(err) { + console.info("==========================>cancelAllback=======================>"); +} +Notification.cancelAll(cancelCallback) +``` + + + +## Notification.cancelAll() + +- Functionality + + Cancels all notifications. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\ + +- Example + +```js +Notification.cancelAll().then((void) => { + console.info("==========================>cancelAllback=======================>"); +}); +``` + + + +## Notification.addSlot(slot: NotificationSlot, callback: AsyncCallback\) + +- Functionality + + Adds a notification slot. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| slot | Read-only| NotificationSlot | Yes| Notification slot to add.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- NotificationSlot + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------------- | -------- | --------------- | ---- | ------------------------------------------ | +| type | Readable and writable| SlotType | Yes| Notification slot type.| +| level | Readable and writable| number | No| Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | Readable and writable| string | No| Description of the notification slot.| +| badgeFlag | Readable and writable| boolean | No| Whether to display the badge.| +| bypassDnd | Readable and writable| boolean | No| Whether to bypass the system do-not-disturb (DND) setting.| +| lockscreenVisibility | Readable and writable| boolean | No| How the notification is displayed on the locked screen.| +| vibrationEnabled | Readable and writable| boolean | No| Whether vibration is enabled for the notification.| +| sound | Readable and writable| string | No| Notification sound.| +| lightEnabled | Readable and writable| boolean | No| Whether light is enabled for the notification.| +| lightColor | Readable and writable| number | No| Notification light color.| +| vibrationValues | Readable and writable| Array\ | No| Notification vibration mode.| + +* Return values + + void + +* Example + +```js +// addSlot callback +function addSlotCallBack(err) { + console.info("==========================>addSlotCallBack=======================>"); +} +// NotificationSlot object +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +Notification.addSlot(notificationSlot, addSlotCallBack) +``` + + + +## Notification.addSlot(slot: NotificationSlot) + +- Functionality + + Adds a notification slot. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---- | -------- | ---------------- | ---- | -------------------- | +| slot | Read-only| NotificationSlot | Yes| Notification slot to add.| + +- Return value + + Promise\ + +- Example + +```js +// NotificationSlot object +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +Notification.addSlot(notificationSlot).then((void) => { + console.info("==========================>addSlotCallback=======================>"); +}); +``` + + + +## Notification.addSlot(type: SlotType, callback: AsyncCallback\) + +- Functionality + + Adds a notification slot. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ---------------------- | +| type | Read-only| SlotType | Yes| Type of the notification slot to add.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +// addSlot callback +function addSlotCallBack(err) { + console.info("==========================>addSlotCallBack=======================>"); +} +Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack) +``` + + + +## Notification.addSlot(type: SlotType) + +- Functionality + + Adds a notification slot. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---- | -------- | -------- | ---- | ---------------------- | +| type | Read-only| SlotType | Yes| Type of the notification slot to add.| + +- Return value + + Promise\ + +- Example + +```js +Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then((void) => { + console.info("==========================>addSlotCallback=======================>"); +}); +``` + + + +## Notification.addSlots(slots: Array\, callback: AsyncCallback\) + +- Functionality + + Adds multiple notification slots. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ------------------------- | ---- | ------------------------ | +| slots | Read-only| Array\ | Yes| Notification slots to add.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +// addSlots callback +function addSlotsCallBack(err) { + console.info("==========================>addSlotsCallBack=======================>"); +} +// NotificationSlot object +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +// NotificationSlotArray object +var notificationSlotArray = new Array(); +notificationSlotArray[0] = notificationSlot; + +Notification.addSlots(notificationSlotArray, addSlotsCallBack) +``` + + + +## Notification.addSlots(slots: Array\) + +- Functionality + + Adds multiple notification slots. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----- | -------- | ------------------------- | ---- | ------------------------ | +| slots | Read-only| Array\ | Yes| Notification slots to add.| + +- Return value + + Promise\ + +- Example + +```js +// NotificationSlot object +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +// NotificationSlotArray object +var notificationSlotArray = new Array(); +notificationSlotArray[0] = notificationSlot; + +Notification.addSlots(notificationSlotArray).then((void) => { + console.info("==========================>addSlotCallback=======================>"); +}); +``` + + + +## Notification.getSlot(slotType: SlotType, callback: AsyncCallback\) + +- Functionality + + Obtains a notification slot of the specified type. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------------------- | ---- | ----------------------------------------------------------- | +| slotType | Read-only| slotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +// getSlot callback +function getSlotCallback(err,data) { + console.info("==========================>getSlotCallback=======================>"); +} +var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.getSlot(slotType, getSlotCallback) +``` + + + +## Notification.getSlot(slotType) + +- Functionality + + Obtains a notification slot of the specified type. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | -------- | ---- | ----------------------------------------------------------- | +| slotType | Read-only| slotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| + +- Return value + + Promise\ + +- Example + +```js +var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.getSlot(slotType).then((data) => { + console.info("==========================>getSlotCallback=======================>"); +}); +``` + + + +## Notification.getSlots(callback: AsyncCallback>) + +- Functionality + + Obtains all notification slots. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------------------- | ---- | -------------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +// getSlots callback +function getSlotsCallback(err,data) { + console.info("==========================>getSlotsCallback=======================>"); +} +Notification.getSlots(getSlotsCallback) +``` + + + +## Notification.getSlots() + +- Functionality + + Obtains all notification slots of the current application. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\\> + +- Example + +```js +Notification.getSlots().then((data) => { + console.info("==========================>getSlotsCallback=======================>"); +}); +``` + + + +## Notification.removeSlot(slotType: SlotType, callback: AsyncCallback\) + +- Functionality + + Removes a notification slot of the specified type. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ----------------------------------------------------------- | +| SlotType | Read-only| SlotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +// removeSlot callback +function removeSlotCallback(err) { + console.info("==========================>removeSlotCallback=======================>"); +} +var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.removeSlot(slotType,removeSlotCallback) +``` + + + +## Notification.removeSlot(slotType: SlotType) + +- Functionality + + Removes a notification slot of the specified type. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | -------- | ---- | ----------------------------------------------------------- | +| SlotType | Read-only| SlotType | Yes| Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| + +- Return value + + Promise\ + +- Example + +```js +var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.removeSlot(slotType).then((void) => { + console.info("==========================>removeSlotCallback=======================>"); +}); +``` + + + +## Notification.removeAllSlots(callback: AsyncCallback\) + +- Functionality + + Removes all notification slots. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function removeAllCallBack(err) { + console.info("================>removeAllCallBack=======================>"); +} +Notification.removeAllSlots(removeAllCallBack) +``` + + + +## Notification.removeAllSlots() + +- Functionality + + Removes all notification slots. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\ + +- Example + +```js +Notification.removeAllSlots().then((void) => { + console.info("==========================>removeAllCallBack=======================>"); +}); +``` + + + +## Notification.subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\) + +- Functionality + + Subscribes to a notification with the subscription information specified. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ------------------------- | ---- | ---------------- | +| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| +| info | Read-only| NotificationSubscribeInfo | Yes| Subscription information.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- NotificationSubscriber + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------------------------------------------------------------ | -------- | -------- | ---- | -------------------------- | +| onConsume?:(data: SubscribeCallbackData) | Readable and writable| function | No| Callback for receiving notifications.| +| onCancel?:(data: SubscribeCallbackData) | Readable and writable| function | No| Callback for canceling notifications.| +| onUpdate?:(data: NotificationSortingMap) | Readable and writable| function | No| Callback for notification sorting updates.| +| onConnect?:() | Readable and writable| function | No| Callback for subscription.| +| onDisconnect?:() | Readable and writable| function | No| Callback for unsubscription.| +| onDestroy?:() | Readable and writable| function | No| Callback for service destruction.| +| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) | Readable and writable| function | No| Callback for DND time setting updates.| + +- SubscribeCallbackData + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------------- | -------- | ---------------------- | ---- | -------- | +| request | Read-only| NotificationRequest | Yes| Notification content.| +| sortingMap | Read-only| NotificationSortingMap | No| Notification sorting information.| +| reason | Read-only| number | No| Reason for deletion.| +| sound | Read-only| string | No| Sound used for notification.| +| vibrationValues | Read-only| Array\ | No| Vibration used for notification.| + +- NotificationSortingMap + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------- | -------- | ------------------------------------ | ---- | ---------------- | +| sortings | Read-only| {[key: string]: NotificationSorting} | Yes| Array of notification sorting information.| +| sortedHashCode | Read-only| Array\ | Yes| Array of unique notification IDs.| + +- NotificationSorting + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ---------------- | ---- | ------------ | +| slot | Read-only| NotificationSlot | Yes| Notification slot.| +| hashCode | Read-only| string | Yes| Unique ID of the notification.| +| ranking | Read-only| number | Yes| Notification sequence number.| + +- DoNotDisturbType + + +| Name| Readable/Writable| Type| Description| +| ------------ | -------- | --------------------- | ---------------------------------------- | +| TYPE_NONE | Read-only| enum DoNotDisturbType | Non-DND.| +| TYPE_ONCE | Read-only| enum DoNotDisturbType | One-shot DND at the specified time segment (only considering the hour and minute)| +| TYPE_DAILY | Read-only| enum DoNotDisturbType | Daily DND at the specified time segment (only considering the hour and minute)| +| TYPE_CLEARLY | Read-only| enum DoNotDisturbType | DND at the specified time segment (considering the year, month, day, hour, and minute)| + +- DoNotDisturbDate + +| Name| Readable/Writable| Type| Description| +| ----- | -------- | ---------------- | ------------------------ | +| type | Readable and writable| DoNotDisturbType | DND time type.| +| begin | Readable and writable| Date | DND start time.| +| end | Readable and writable| Date | DND end time.| + +- NotificationSubscribeInfo + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----------- | -------- | --------------- | ---- | ------------------------------- | +| bundleNames | Readable and writable| Array\ | No| Bundle names of the applications whose notifications are to be subscribed to.| +| userId | Readable and writable| number | No| User whose notifications are to be subscribed to.| + +- Return value + + void + +- Example + +```js +// subscribe callback +function subscribeCallback(err) { + console.info("==========================>subscribeCallback=======================>"); +} +function onConsumeCallback(err, data) { + console.info("==========================>onConsumeCallback=======================>"); +} +var subscriber = { + onConsume: onConsumeCallback +} +var info = { + bundleNames: ["bundleName1","bundleName2"] +} +Notification.subscribe(subscriber, info, subscribeCallback); +``` + + + +## Notification.subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) + +- Functionality + + Subscribes to a notification. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ---------------------- | ---- | ---------------- | +| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function subscribeCallback(err) { + console.info("==========================>subscribeCallback=======================>"); +} +function onConsumeCallback(err, data) { + console.info("==========================>onConsumeCallback=======================>"); +} +var subscriber = { + onConsume: onConsumeCallback +} +Notification.subscribe(subscriber, subscribeCallback); +``` + + + +## Notification.subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo) + +- Functionality + + Subscribes to a notification with the subscription information specified. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ------------------------- | ---- | ------------ | +| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| +| info | Read-only| NotificationSubscribeInfo | No| Subscription information.| + +- Return value + + Promise\ + +- Example + +```js +function onConsumeCallback(err, data) { + console.info("==========================>onConsumeCallback=======================>"); +} +var subscriber = { + onConsume: onConsumeCallback +}; +Notification.subscribe(subscriber).then((void) => { + console.info("==========================>subscribeCallback=======================>"); +}); +``` + + + +## Notification.unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) + +- Functionality + + Unsubscribes from a notification. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ---------------------- | ---- | -------------------- | +| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function unsubscribeCallback(err) { + console.info("==========================>unsubscribeCallback=======================>"); +} +function onConsumeCallback(err, data) { + console.info("==========================>onConsumeCallback=======================>"); +} +var subscriber = { + onConsume: onConsumeCallback +} +Notification.unsubscribe(subscriber, unsubscribeCallback); +``` + + + +## Notification.unsubscribe(subscriber: NotificationSubscriber) + +- Functionality + + Unsubscribes from a notification. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ---------------------- | ---- | ------------ | +| subscriber | Read-only| NotificationSubscriber | Yes| Notification subscriber.| + +- Return value + + Promise\ + +- Example + +```js +function onConsumeCallback(err, data) { + console.info("==========================>onConsumeCallback=======================>"); +} +var subscriber = { + onConsume: onConsumeCallback +}; +Notification.unsubscribe(subscriber).then((void) => { + console.info("==========================>unsubscribeCallback=======================>"); +}); +``` + + + +## Notification.enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) + +- Functionality + + Sets whether to enable notification for a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| enable | Read-only| boolean | Yes| Whether to enable notification.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- BundleOption + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------ | ---- | ------ | +| bundle | Readable and writable| string | Yes| Bundle name.| +| uid | Readable and writable| number | No| User ID.| +- Return value + + void + +- Example + +```js +function enableNotificationCallback(err) { + console.info("==========================>enableNotificationCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +Notification.enableNotification(bundle, false, enableNotificationCallback); +``` + + + +## Notification.enableNotification(bundle: BundleOption, enable: boolean) + +- Functionality + + Sets whether to enable notification for a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------------ | ---- | ---------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| enable | Read-only| boolean | Yes| Whether to enable notification.| + +- Return value + + Promise\ + +- Example + +```js +var bundle = { + bundle: "bundleName1"; +} +Notification.enableNotification(bundle, false).then((void) => { + console.info("==========================>enableNotificationCallback=======================>"); +}); +``` + + + +## Notification.isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\) + +- Functionality + + Checks whether notification is enabled for a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ------------------------ | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function isNotificationEnabledCallback(err, data) { + console.info("==========================>isNotificationEnabledCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); +``` + + + +## Notification.isNotificationEnabled(bundle: BundleOption) + +- Functionality + + Checks whether notification is enabled for a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------------ | ---- | ---------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| + +- Return value + + Promise\ + +- Example + +```js +var bundle = { + bundle: "bundleName1"; +} +Notification.isNotificationEnabled(bundle).then((data) => { + console.info("==========================>isNotificationEnabledCallback=======================>"); +}); +``` + + + +## Notification.isNotificationEnabled(callback: AsyncCallback\) + +- Functionality + + Checks whether notification is enabled for the current application. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ------------------------ | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function isNotificationEnabledCallback(err, data) { + console.info("==========================>isNotificationEnabledCallback=======================>"); +} + +Notification.isNotificationEnabled(isNotificationEnabledCallback); +``` + + + +## Notification.isNotificationEnabled() + +- Functionality + + Checks whether notification is enabled for the current application. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\ + +- Example + +```js +Notification.isNotificationEnabled().then((data) => { + console.info("==========================>isNotificationEnabledCallback=======================>"); +}); +``` + + + +## Notification.displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) + +- Functionality + + Sets whether to display the badge in notifications for a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| enable | Read-only| boolean | Yes| Whether to display the badge.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function displayBadgeCallback(err) { + console.info("==========================>displayBadgeCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +Notification.displayBadge(bundle, false, displayBadgeCallback); +``` + + + +## Notification.displayBadge(bundle: BundleOption, enable: boolean) + +- Functionality + + Sets whether to display the badge in notifications for a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------------ | ---- | ---------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| enable | Read-only| boolean | Yes| Whether to display the badge.| + +- Return value + + Promise\ + +- Example + +```js +var bundle = { + bundle: "bundleName1"; +} +Notification.displayBadge(bundle, false).then((void) => { + console.info("==========================>displayBadgeCallback=======================>"); +}); +``` + + + +## Notification.isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\) + +- Functionality + + Checks whether the badge will be displayed in notifications of a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ------------------------ | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function isBadgeDisplayedCallback(err, data) { + console.info("==========================>isBadgeDisplayedCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); +``` + + + +## Notification.isBadgeDisplayed(bundle: BundleOption) + +- Functionality + + Checks whether the badge will be displayed in notifications of a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------------ | ---- | ---------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| + +- Return value + + Promise\ + +- Example + +```js +var bundle = { + bundle: "bundleName1"; +} +Notification.isBadgeDisplayed(bundle).then((data) => { + console.info("==========================>isBadgeDisplayedCallback=======================>"); +}); +``` + + + +## Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\) + +- Functionality + + Sets a notification slot for a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| slot | Read-only| NotificationSlot | Yes| Notification slot.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function setSlotByBundleCallback(err) { + console.info("==========================>setSlotByBundleCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); +``` + + + +## Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot) + +- Functionality + + Sets a notification slot for a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------------ | ---- | ---------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| slot| Read-only| NotificationSlot| Yes| Notification slot.| + +- Return value + + Promise\ + +- Example + +```js +var bundle = { + bundle: "bundleName1"; +} +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +Notification.displayBadge(bundle, notificationSlot).then((void) => { + console.info("==========================>setSlotByBundleCallback=======================>"); +}); +``` + + + +## Notification.getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>) + +- Functionality + + Obtains the notification slots of a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ---------------------------------------- | ---- | -------------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function getSlotsByBundleCallback(err, data) { + console.info("==========================>getSlotsByBundleCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); +``` + + + +## Notification.getSlotsByBundle(bundle: BundleOption) + +- Functionality + + Obtains the notification slots of a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------------ | ---- | ---------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| + +- Return value + + Promise> + +- Example + +```js +var bundle = { + bundle: "bundleName1"; +} +Notification.getSlotsByBundle(bundle).then((data) => { + console.info("==========================>getSlotsByBundleCallback=======================>"); +}); +``` + + + +## Notification.getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\) + +- Functionality + + Obtains the number of notification slots of a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ------------------------- | ---- | ---------------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function getSlotNumByBundle(err, data) { + console.info("==========================>getSlotNumByBundleCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); +``` + + + +## Notification.getSlotNumByBundle(bundle: BundleOption) + +- Functionality + + Obtains the number of notification slots of a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------------ | ---- | ---------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| + +- Return value + + Promise\ + +- Example + +```js +var bundle = { + bundle: "bundleName1"; +} +Notification.getSlotNumByBundle(bundle).then((data) => { + console.info("==========================>getSlotNumByBundleCallback=======================>"); +}); +``` + + + +## Notification.remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\) + +- Functionality + + Removes a notification for a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------------- | -------- | --------------------- | ---- | -------------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| notificationKey | Read-only| NotificationKey | Yes| Notification key.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- NotificationKey + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----- | -------- | ------ | ---- | -------- | +| id | Readable and writable| number | Yes| Notification ID.| +| label | Readable and writable| string | No| Notification label.| + +- Return value + + void + +- Example + +```js +function removeCallback(err) { + console.info("==========================>removeCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +var notificationKey = { + id: 0; + label: "label"; +} +Notification.remove(bundle, notificationKey, removeCallback); +``` + + + +## Notification.remove(bundle: BundleOption, notificationKey: NotificationKey) + +- Functionality + + Removes a notification for a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------------- | -------- | --------------- | ---- | ---------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| notificationKey | Read-only| NotificationKey | Yes| Notification key.| + +- Return value + + Promise\ + +- Example + +```js +var bundle = { + bundle: "bundleName1"; +} +var notificationKey = { + id: 0; + label: "label"; +} +Notification.remove(bundle, notificationKey).then((void) => { + console.info("==========================>removeCallback=======================>"); +}); +``` + + + +## Notification.remove(hashCode: string, callback: AsyncCallback\) + +- Functionality + + Removes a notification. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| hashCode | Read-only| string | Yes| Unique notification ID.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function removeCallback(err) { + console.info("==========================>removeCallback=======================>"); +} + +Notification.remove(hashCode, removeCallback); +``` + + + +## Notification.remove(hashCode: string) + +- Functionality + + Removes a notification. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ---------- | ---- | ---------- | +| hashCode | Read-only| string | Yes| Unique notification ID.| + +- Return value + + Promise\ + +- Example + +```js +Notification.remove(hashCode).then((void) => { + console.info("==========================>removeCallback=======================>"); +}); +``` + + + +## Notification.removeAll(bundle: BundleOption, callback: AsyncCallback\) + +- Functionality + + Removes all notifications for a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ---------------------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function removeAllCallback(err) { + console.info("==========================>removeAllCallback=======================>"); +} +var bundle = { + bundle: "bundleName1"; +} +Notification.removeAll(bundle, removeAllCallback); +``` + + + +## Notification.removeAll(callback: AsyncCallback\) + +- Functionality + + Removes all notifications. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | -------------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function removeAllCallback(err) { + console.info("==========================>removeAllCallback=======================>"); +} + +Notification.removeAll(removeAllCallback); +``` + + + +## Notification.removeAll(bundle?: BundleOption) + +- Functionality + + Removes all notifications for a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------ | -------- | ------------ | ---- | ---------- | +| bundle | Read-only| BundleOption | No| Bundle information.| + +- Return value + + Promise\ + +- Example + +```js +Notification.removeAll().then((void) => { + console.info("==========================>removeAllCallback=======================>"); +}); +``` + + + +## Notification.getAllActiveNotifications(callback: AsyncCallback>) + +- Functionality + + Obtains all active notifications. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ------------------------------------------- | ---- | -------------------- | +| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function getAllActiveNotificationsCallback(err, data) { + console.info("==========================>getAllActiveNotificationsCallback=======================>"); +} + +Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); +``` + + + +## Notification.getAllActiveNotifications() + +- Functionality + + Obtains all active notifications. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\\> + +- Example + +```js +Notification.getAllActiveNotifications().then((data) => { + console.info("==========================>getAllActiveNotificationsCallback=======================>"); +}); +``` + + + +## Notification.getActiveNotificationCount(callback: AsyncCallback\) + +- Functionality + + Obtains the number of active notifications. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ---------------------- | ---- | ---------------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function getActiveNotificationCountCallback(err, data) { + console.info("==========================>getActiveNotificationCountCallback=======================>"); +} + +Notification.getActiveNotificationCount(getActiveNotificationCountCallback); +``` + + + +## Notification.getActiveNotificationCount() + +- Functionality + + Obtains the number of active notifications. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\ + +- Example + +```js +Notification.getActiveNotificationCount().then((data) => { + console.info("==========================>getActiveNotificationCountCallback=======================>"); +}); +``` + + + +## Notification.getActiveNotifications(callback: AsyncCallback>) + +- Functionality + + Obtains active notifications of the current application. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ------------------------------------------- | ---- | ------------------------------ | +| callback | Read-only| AsyncCallback> | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function getActiveNotificationsCallback(err, data) { + console.info("==========================>getActiveNotificationsCallback=======================>"); +} + +Notification.getActiveNotifications(getActiveNotificationsCallback); +``` + + + +## Notification.getActiveNotifications() + +- Functionality + + Obtains active notifications. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\\> + +- Example + +```js +Notification.getActiveNotifications().then((data) => { + console.info("==========================>getActiveNotificationsCallback=======================>"); +}); +``` + + + +## Notification.cancelGroup(groupName: string, callback: AsyncCallback\) + +- Functionality + + Cancels a notification group of the current application. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | --------------------- | ---- | ---------------------------- | +| groupName | Read-only| string | Yes| Name of the notification group to cancel.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function cancelGroupCallback(err) { + console.info("==========================>cancelGroupCallback=======================>"); +} + +var groupName = "GroupName"; + +Notification.cancelGroup(groupName, cancelGroupCallback); +``` + + + +## Notification.cancelGroup(groupName: string) + +- Functionality + + Cancels a notification group of the current application. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | ------ | ---- | -------------- | +| groupName | Read-only| string | Yes| Name of the notification group to cancel.| + +- Return value + + Promise\ + +- Example + +```js +var groupName = "GroupName"; +Notification.cancelGroup(groupName).then(() => { + console.info("==========================>cancelGroupPromise=======================>"); +}); +``` + + + +## Notification.removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\) + +- Functionality + + Removes a notification group for a specified bundle. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | --------------------- | ---- | ---------------------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| groupName | Read-only| string | Yes| Name of the notification group to remove.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function removeGroupByBundleCallback(err) { + console.info("==========================>removeGroupByBundleCallback=======================>"); +} + +var bundleOption = {bundle: "Bundle"}; +var groupName = "GroupName"; + +Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); +``` + + + +## Notification.removeGroupByBundle(bundle: BundleOption, groupName: string) + +- Functionality + + Removes a notification group for a specified bundle. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | ------------ | ---- | -------------- | +| bundle | Read-only| BundleOption | Yes| Bundle information.| +| groupName | Read-only| string | Yes| Name of the notification group to remove.| + +- Return value + + Promise\ + +- Example + +```js +var bundleOption = {bundle: "Bundle"}; +var groupName = "GroupName"; +Notification.removeGroupByBundle(bundleOption, groupName).then(() => { + console.info("==========================>removeGroupByBundlePromise=======================>"); +}); +``` + + + +## Notification.setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\) + +- Functionality + + Sets the DND time. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ---------------------- | +| date | Read-only| DoNotDisturbDate | Yes| DND time to set.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function setDoNotDisturbDateCallback(err) { + console.info("==========================>setDoNotDisturbDateCallback=======================>"); +} + +var doNotDisturbDate = { + type: notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} + +Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); +``` + + + +## Notification.setDoNotDisturbDate(date: DoNotDisturbDate) + +- Functionality + + Sets the DND time. This method uses a promise to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---- | -------- | ---------------- | ---- | -------------- | +| date | Read-only| DoNotDisturbDate | Yes| DND time to set.| + +- Return value + + Promise\ + +- Example + +```js +var doNotDisturbDate = { + type: notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} +Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { + console.info("==========================>setDoNotDisturbDatePromise=======================>"); +}); +``` + + + +## Notification.getDoNotDisturbDate(callback: AsyncCallback\) + +- Functionality + + Obtains the DND time. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------------------- | ---- | ---------------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function getDoNotDisturbDateCallback(err,data) { + console.info("==========================>getDoNotDisturbDateCallback=======================>"); +} + +Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); +``` + + + +## Notification.getDoNotDisturbDate() + +- Functionality + + Obtains the DND time. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\ + +- Example + +```js +Notification.getDoNotDisturbDate().then((data) => { + console.info("==========================>getDoNotDisturbDatePromise=======================>"); +}); +``` + + + +## Notification.supportDoNotDisturbMode(callback: AsyncCallback\) + +- Functionality + + Checks whether the DND mode is supported. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ------------------------ | ---- | -------------------------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +function supportDoNotDisturbModeCallback(err,data) { + console.info("==========================>supportDoNotDisturbModeCallback=======================>"); +} + +Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); +``` + + + +## Notification.supportDoNotDisturbMode() + +- Functionality + + Checks whether the DND mode is supported. This method uses a promise to return the result. + +- Parameters + + None + +- Return value + + Promise\ + +- Example + +```js +Notification.supportDoNotDisturbMode().then((data) => { + console.info("==========================>supportDoNotDisturbModePromise=======================>"); +}); +``` + + + +## Notification.isSupportTemplate + +isSupportTemplate(templateName: string, callback: AsyncCallback\): void + +Checks whether a specified template exists. This method uses a callback to return the result. + +- Parameters + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| templateName | string | Yes| Template name.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +- Example + +```javascript +var templateName = 'process'; +function isSupportTemplateCallback(err, data) { + console.info("isSupportTemplateCallback"); +} + +Notification.isSupportTemplate(templateName, isSupportTemplateCallback); +``` + + + +## Notification.isSupportTemplate + +isSupportTemplate(templateName: string): Promise\ + +Checks whether a specified template exists. This method uses a promise to return the result. + +- Parameters + +| Name| Type| Mandatory| Description| +| ------------ | ------ | ---- | -------- | +| templateName | string | Yes| Name| + +- Return value + +| Type| Description| +| ------------------ | --------------- | +| Promise\ | Promise used to return the result.| + +- Example + +```javascript +var templateName = 'process'; + +Notification.isSupportTemplate(templateName).then((data) => { + console.info("isSupportTemplateCallback"); +}); +``` + + + +## NotificationTemplate + +Describes the template information. + +| Name| Type| Readable| Writable| Description| +| ---- | ---------------------- | ---- | ---- | -------- | +| name | string | Yes| Yes| Template name.| +| data | {[key:string]: Object} | Yes| Yes| Template data.| + + + +## WantAgent APIs + +## Modules to Import + +```js +import WantAgent from '@ohos.wantAgent'; +``` + +## WantAgent.getWantAgent(info: WantAgentInfo, callback: AsyncCallback\) + +- Functionality + + Obtains a **WantAgent** object. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | -------------------------- | ---- | ----------------------- | +| info | Read-only| WantAgentInfo | Yes| Information about the **WantAgent** object to obtain.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- WantAgentInfo + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------------- | -------- | ------------------------------- | ---- | ---------------------- | +| wants | Readable and writable| Array\ | Yes| Array of all **Want** objects.| +| operationType | Readable and writable| wantAgent.OperationType | Yes| Type of the operation specified in a **Want** object.| +| requestCode | Readable and writable| number | Yes| Request code defined by the user.| +| wantAgentFlags | Readable and writable| Array | No| Array of flags for using the **WantAgent** object.| +| extraInfo | Readable and writable| {[key: string]: any} | No| Extra information.| + +- + WantAgentFlags + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | +| ONE_TIME_FLAG | Read-only| enum | No| The **WantAgent** object can be used only once.| +| NO_BUILD_FLAG | Read-only| enum | No| The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned.| +| CANCEL_PRESENT_FLAG | Read-only| enum | No| The existing **WantAgent** object should be canceled before a new object is generated.| +| UPDATE_PRESENT_FLAG | Read-only| enum | No| Extra data of the existing **WantAgent** object is replaced with that of the new object.| +| CONSTANT_FLAG | Read-only| enum | No| The **WantAgent** object is immutable.| + +- OperationType + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----------------- | -------- | ---- | ---- | ----------------------- | +| UNKNOWN_TYPE | Read-only| enum | No| Unknown operation.| +| START_ABILITY | Read-only| enum | No| Starts an ability with a UI.| +| START_ABILITIES | Read-only| enum | No| Starts multiple abilities with a UI.| +| START_SERVICE | Read-only| enum | No| Starts an ability without a UI.| +| SEND_COMMON_EVENT | Read-only| enum | No| Sends a common event.| + +- Return value + + void + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info("==========================>getWantAgentCallback=======================>"); +} +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +``` + + + +## WantAgent.getWantAgent(info: WantAgentInfo): Promise\ + +- Functionality + + Obtains a **WantAgent** object. This method uses a promise to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---- | -------- | ------------- | ---- | ------------- | +| info | Read-only| WantAgentInfo | Yes| Information about the **WantAgent** object to obtain.| + +- Return value + + Promise\ + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info("==========================>getWantAgentCallback=======================>"); +}); +``` + + + +## WantAgent.getBundleName(agent: WantAgent, callback: AsyncCallback\) + +- Functionality + + Obtains the bundle name of a **WantAgent** object. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ----------------------- | ---- | --------------------------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object whose bundle name is to be obtained.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info("==========================>getWantAgentCallback=======================>"); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) + +// getBundleName callback +function getBundleNameCallback(err, data) { + console.info("==========================>getBundleNameCallback=======================>"); +} +WantAgent.getBundleName(wantAgent, getBundleNameCallback) +``` + + + +## WantAgent.getBundleName(agent: WantAgent): Promise\ + +- Functionality + + Obtains the bundle name of a **WantAgent** object. This method uses a promise to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----- | -------- | --------- | ---- | ------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object whose bundle name is to be obtained.| + +- Return value + + Promise\ + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info("==========================>getWantAgentCallback=======================>"); + wantAgent = data; +}); + +WantAgent.getBundleName(wantAgent).then((data) => { + console.info("==========================>getBundleNameCallback=======================>"); +}); +``` + + + +## WantAgent.getUid(agent: WantAgent, callback: AsyncCallback\) + +- Functionality + + Obtains the user ID of a **WantAgent** object. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | ----------------------- | ---- | ----------------------------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object whose user ID is to be obtained.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info("==========================>getWantAgentCallback=======================>"); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) + +// getUid callback +function getUidCallback(err, data) { + console.info("==========================>getUidCallback=======================>"); +} +WantAgent.getUid(wantAgent, getUidCallback) +``` + + + +## WantAgent.getUid(agent: WantAgent): Promise\ + +- Functionality + + Obtains the user ID of a **WantAgent** object. This method uses a promise to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----- | -------- | --------- | ---- | ------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object whose user ID is to be obtained.| + +- Return value + + Promise\ + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info("==========================>getWantAgentCallback=======================>"); + wantAgent = data; +}); + +WantAgent.getUid(wantAgent).then((data) => { + console.info("==========================>getUidCallback=======================>"); +}); +``` + + + +## WantAgent.getWant(agent: WantAgent, callback: AsyncCallback\) + +- Functionality + + Obtains the want in a **WantAgent** object. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | ------------------------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info("==========================>getWantAgentCallback=======================>"); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentWantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) + +// getWant callback +function getWantCallback(err, data) { + console.info("==========================>getWantCallback=======================>"); +} +WantAgent.getWant(wantAgent, getWantCallback) +``` + + + +## WantAgent.getWant(agent: WantAgent): Promise\ + +- Functionality + + Obtains the want in a **WantAgent** object. This method uses a promise to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----- | -------- | --------- | ---- | ------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object.| + +- Return value + + Promise\ + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info("==========================>getWantAgentCallback=======================>"); + wantAgent = data; +}); + +WantAgent.getWant(wantAgent).then((data) => { + console.info("==========================>getWantCallback=======================>"); +}); +``` + + + +## WantAgent.cancel(agent: WantAgent, callback: AsyncCallback\) + +- Functionality + + Cancels a **WantAgent** object. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | --------------------- | ---- | --------------------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object to cancel.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info("==========================>getWantAgentCallback=======================>"); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) + +// cancel callback +function cancelCallback(err, data) { + console.info("==========================>cancelCallback=======================>"); +} +WantAgent.cancel(wantAgent, cancelCallback) +``` + + + +## WantAgent.cancel(agent: WantAgent): Promise\ + +- Functionality + + Cancels a **WantAgent** object. This method uses a promise to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----- | -------- | --------- | ---- | ------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object to cancel.| + +- Return value + + Promise\ + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info("==========================>getWantAgentCallback=======================>"); + wantAgent = data; +}); + +WantAgent.cancel(wantAgent).then((data) => { + console.info("==========================>cancelCallback=======================>"); +}); +``` + + + +## WantAgent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) + +- Functionality + + Triggers a **WantAgent** object. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----------- | -------- | ----------------------------- | ---- | ------------------------------- | +| agent | Read-only| WantAgent | Yes| **WantAgent** object to trigger.| +| triggerInfo | Read-only| TriggerInfo | Yes| **TriggerInfo** object.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- TriggerInfo + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | -------------------- | ---- | ----------- | +| code | Readable and writable| number | Yes| Result code.| +| want | Readable and writable| Want | No| Want.| +| permission | Readable and writable| string | No| Permission.| +| extraInfo | Readable and writable| {[key: string]: any} | No| Extra information.| + +- Return value + + void + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info("==========================>getWantAgentCallback=======================>"); + if (err.code == 0) { + wantAgent = data; + } else { + console.info('----getWantAgent failed!----'); + } +} +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) + +//Trigger callback +function triggerCallback(err, data) { + console.info("==========================>triggerCallback=======================>"); +} + +var triggerInfo = { + code:0 +} +WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) +``` + + + +## WantAgent.equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\) + +- Functionality + + Checks whether two **WantAgent** objects are equal. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ------------------------ | ---- | --------------------------------------- | +| agent | Read-only| WantAgent | Yes| The first **WantAgent** object.| +| otherAgent | Read-only| WantAgent | Yes| The second **WantAgent** object.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return value + + void + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent1; +var wantAgent2; + +// getWantAgent callback +function getWantAgentCallback(err, data) { + console.info("==========================>getWantAgentCallback=======================>"); + if (err.code == 0) { + wantAgent1 = data; + wantAgent2 = data; + } else { + console.info('----getWantAgent failed!----'); + } +} +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) + +// equal callback +function equalCallback(err, data) { + console.info("==========================>equalCallback=======================>"); +} +WantAgent.equal(wantAgent1, wantAgent2, equalCallback) +``` + + + +## WantAgent.equal(agent: WantAgent, otherAgent: WantAgent): Promise\ + +- Functionality + + Checks whether two **WantAgent** objects are equal. This method uses a promise to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | --------- | ---- | ------------- | +| agent | Read-only| WantAgent | Yes| The first **WantAgent** object.| +| otherAgent | Read-only| WantAgent | Yes| The second **WantAgent** object.| + +- Return value + + Promise\ + +- Example + +```js +import WantAgent from '@ohos.wantAgent'; +import { OperationType, WantAgentFlags } from '@ohos.wantagent'; + +// WantAgent object +var wantAgent1; +var wantAgent2; + +// WantAgentInfo object +var wantAgentInfo = { + wants: [ + { + deviceId: "deviceId", + bundleName: "com.neu.setResultOnAbilityResultTest1", + abilityName: "com.example.test.MainAbility", + action: "action1", + entities: ["entity1"], + type: "MIMETYPE", + uri: "key={true,true,false}", + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: "[1, 2, 3]", + mykey3: "ssssssssssssssssssssssssss", + mykey4: [false, true, false], + mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey6: true, + } + } + ], + operationType: OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +WantAgent.getWantAgent(wantAgentInfo).then((data) => { + console.info("==========================>getWantAgentCallback=======================>"); + wantAgent1 = data; + wantAgent2 = data; +}); + +WantAgent.equal(wantAgent1, wantAgent2).then((data) => { + console.info("==========================>equalCallback=======================>"); +}); +``` + + + +#### diff --git a/en/application-dev/reference/apis/js-apis-particleAbility.md b/en/application-dev/reference/apis/js-apis-particleAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..128d8282ba250fc4e887bd178e90308ee015b114 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-particleAbility.md @@ -0,0 +1,394 @@ +# ParticleAbility Module + +## Applicable Devices + +| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device| +| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ | +| particleAbility.startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\: void | Yes| Yes| Yes| Yes| No| No| +| particleAbility.startAbility(parameter: StartAbilityParameter): Promise\ | Yes| Yes| Yes| Yes| No| No| +| particleAbility.terminateSelf(callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| +| particleAbility.terminateSelf(): Promise\ | Yes| Yes| Yes| Yes| No| No| +| particleAbility.acquireDataAbilityHelper(uri: string): DataAbilityHelper | Yes| Yes| Yes| Yes| No| No| +| particleAbility.connectAbility(request: Want, options:ConnectOptions): number | Yes| Yes| Yes| Yes| No| No| +| particleAbility.disconnectAbility(connection: number, callback:AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| +| particleAbility.disconnectAbility(connection: number): Promise\ | Yes| Yes| Yes| Yes| No| No| + +## Constraints + +The ParticleAbility module is used to perform operations on abilities of the Data and Service types. + +## Modules to Import + +```js +import particleAbility from '@ohos.ability.particleAbility' +``` + +## particleAbility.startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\: void + +- Functionality + + Starts a Service ability. This method uses a callback to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | ------------------------------------------------------- | ---- | ----------------- | +| parameter | Read-only| [StartAbilityParameter](#StartAbilityParameter)| Yes| Ability to start.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return values + + void + +- Example + +```js +import particleAbility from '@ohos.ability.particleAbility' +particleAbility.startAbility( + { + want: + { + action: "action.system.home", + entities: ["entity.system.home"], + type: "MIMETYPE", + flags: FLAG_AUTH_READ_URI_PERMISSION; + deviceId: "", + bundleName: "com.example.Data", + abilityName: "com.example.Data.MainAbility", + uri:"" + }, + }, + (error, result) => { + console.log('particleAbility startAbility errCode:' + error + 'result:' + result) + }, +) +``` + + + +## particleAbility.startAbility(parameter: StartAbilityParameter): Promise\ + +- Functionality +Starts a Service ability. This method uses a promise to return the result. + +- Parameters + + +| Name| Readable/Writable| Type| Mandatory| Description| +| --------- | -------- | ------------------------------------------------------- | ---- | ----------------- | +| parameter | Read-only| [StartAbilityParameter](#StartAbilityParameter)| Yes| Ability to start.| +- Return values + + Promise\ + +- Example + +```js +import particleAbility from '@ohos.ability.particleAbility' +particleAbility.startAbility( + { + want: + { + action: "action.system.home", + entities: ["entity.system.home"], + type: "MIMETYPE", + flags: FLAG_AUTH_READ_URI_PERMISSION; + deviceId: "", + bundleName: "com.example.Data", + abilityName: "com.example.Data.MainAbility", + uri:"" + }, + }, +).then((void) => { + console.info("particleAbility startAbility"); +}); +``` + + + +## particleAbility.terminateSelf(callback: AsyncCallback\): void + +- Functionality + + Terminates this Service ability. This method uses a callback to return the result. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| -------- | -------- | -------------------- | ---- | -------------------- | +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +- Return values + + void + +- Example + +```js +import particleAbility from '@ohos.ability.particleAbility' +particleAbility.terminateSelf( + (error, result) => { + console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result) + } +) +``` + + + +## particleAbility.terminateSelf(): Promise\ + +- Functionality + + Terminates this Service ability. This method uses a promise to return the result. + +- Return values + + Promise\ + +- Example + +```js +import particleAbility from '@ohos.ability.particleAbility' +particleAbility.terminateSelf().then((void) => { + console.info("particleAbility terminateSelf"); +}); +``` + + + +## particleAbility.acquireDataAbilityHelper(uri: string): DataAbilityHelper + +- Functionality + + Obtains a **dataAbilityHelper** object. + +- Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| :--- | -------- | ------ | ---- | ---------------------- | +| uri | Read-only| string | Yes| URI of the file to open.| + +- Return values + +| Type| Description| +| ----------------- | ------------------------------------------ | +| DataAbilityHelper | A utility class used to help other abilities access a Data ability.| + +- Example + +```js +import particleAbility from '@ohos.ability.particleAbility' +var uri = ""; +particleAbility.acquireDataAbilityHelper(uri) +``` + +## particleAbility.connectAbility(request: Want, options:ConnectOptions): number + +* Functionality + + Connects this ability to a specific Service ability. This method uses a callback to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------- | -------- | -------------- | ---- | -------------------------- | +| request | Read-only| Want | Yes| Service ability to connect.| +| options | Read-only| ConnectOptions | Yes| Callback used to return the result.| + +- ConnectOptions + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------------ | -------- | -------- | ---- | ---------------------------------- | +| onConnect | Read-only| function | Yes| Callback invoked when the connection is set up.| +| onDisconnect | Read-only| function | Yes| Callback invoked when the connection is interrupted.| +| onFailed | Read-only| function | Yes| Callback invoked when the connection fails.| + +* Return values + + Returns the unique identifier of the connection. + +* Example + +```javascript +import particleAbility from '@ohos.ability.particleAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +``` + +## particleAbility.disconnectAbility(connection: number, callback:AsyncCallback\): void + +* Functionality + + Disconnects this ability from a specific Service ability. This method uses a callback to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ------------- | ---- | ------------------------------ | +| connection | Read-only| number | Yes| ID of the Service ability to disconnect.| +| callback | Read-only| AsyncCallback\ | Yes| Callback used to return the result.| + +* Return values + + void + +* Example + +```javascript +import particleAbility from '@ohos.ability.particleAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +var result = particleAbility.disconnectAbility(connId, + (error,data) => { + console.log('particleAbilityTest DisConnectAbility result errCode : ' + error.code + " data: " + data) + }, +); +``` + +## particleAbility.disconnectAbility(connection: number): Promise\ + +* Functionality + + Disconnects this ability from a specific Service ability. This method uses a promise to return the result. + +* Parameters + +| Name| Readable/Writable| Type| Mandatory| Description| +| ---------- | -------- | ------ | ---- | ------------------------------ | +| connection | Read-only| number | Yes| ID of the Service ability to disconnect.| + +* Return values + + Promise\ + +* Example + +```javascript +import particleAbility from '@ohos.ability.particleAbility' +function onConnectCallback(element, remote){ + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} +function onDisconnectCallback(element){ + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} +function onFailedCallback(code){ + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +var result = particleAbility.disconnectAbility(connId).then((void) => { + console.info("particleAbilityTest disconnectAbility"); +}); +``` + +## StartAbilityParameter + +| Name| Readable/Writable| Type| Mandatory| Description| +| ------------------- | -------- | --------------------- | ---- | ------------------------------------------------------------ | +| want | Read-only| [Want](#Want)| Yes| Information about the ability to start.| +| abilityStartSetting | Read-only| {[key: string]: any} | No| Special attribute of the ability to start. This attribute can be passed in the method call.| + +## Want + +| Name| Readable/Writable| Type| Mandatory| Description| +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | Read-only| string | No| ID of the device running the ability to start.| +| bundleName | Read-only| string | No| Bundle name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| abilityName | Read-only| string | No| Name of the ability to start. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can directly match the specified ability.| +| 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](#flags).| +| action | Read-only| string | No| Action option.| +| parameters | Read-only| {[key: string]: any} | No| List of parameters in the **Want** object.| +| entities | Read-only| Array\ | No| List of entities.| + +## flags + +| Name| Value| Description| +| ------------------------------------ | ---------- | ------------------------------------------------------------ | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI.| +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI.| +| FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability.| +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device.| +| FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS.| +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability.| +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.| +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.| +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler.| +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started.| +| FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible.| +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed.| +| FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed.| +| FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object passed to **ohos.app.Context#startAbility** and must be used together with **flag_ABILITY_NEW_MISSION**.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack.| +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| + +## AbilityStartSetting + +Defines special attributes of an ability, for example, **featureAbility.AbilityStartSetting.BOUNDS_KEY**. + +The **AbilityStartSetting** attribute is an object defined as [key: string]: any. The key is a type of **AbilityStartSetting**, and the value is a type of **AbilityWindowConfiguration**. + +| Name| Value| Description| +| --------------- | --------------- | -------------------------- | +| BOUNDS_KEY | "abilityBounds" | Ability window size.| +| WINDOW_MODE_KEY | "windowMode" | Ability window display mode.| +| DISPLAY_ID_KEY | "displayId" | Display device ID.| + +## AbilityWindowConfiguration + +Defines the window display modes of a Page ability, for example, **featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED**. + +| Name| Value| Description| +| --------------------------- | ---- | ---------- | +| WINDOW_MODE_UNDEFINED | 0 | The Page ability is in an undefined window display mode.| +| WINDOW_MODE_FULLSCREEN | 1 | The Page ability is in full screen mode.| +| WINDOW_MODE_SPLIT_PRIMARY | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.| +| WINDOW_MODE_SPLIT_SECONDARY | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.| +| WINDOW_MODE_FLOATING | 102 | The Page ability is displayed in floating window mode.| diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md new file mode 100644 index 0000000000000000000000000000000000000000..fedc273ec2cf3f56700a6064d9c5ae887fa8351d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -0,0 +1,179 @@ +# Power Management + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import power from '@ohos.power'; +``` + +## Required Permissions + +Shutdown: ohos.permission.SHUTDOWN + +Reboot: ohos.permission.REBOOT + +Reboot and entering the recovery mode: ohos.permission.REBOOT\_RECOVERY + +## power.shutdownDevice + +shutdownDevice\(reason: string\): void + +Shuts down the system. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reason

+

string

+

Yes

+

Reason for system shutdown.

+
+ +- Example + + ``` + power.shutdownDevice("shutdown_test"); + console.info('power_shutdown_device_test success') + ``` + + +## power.rebootDevice + +rebootDevice\(reason: string\): void + +Reboots the system. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reason

+

string

+

Yes

+

Reason for system reboot.

+
+ +- Example + + ``` + power.rebootDevice("reboot_test"); + console.info('power_reboot_device_test success') + ``` + + +## power.isScreenOn + +isScreenOn\(callback: AsyncCallback\): void + +Checks the screen status of the current device. + +- Parameters + + + + + + + + + + + + + + +

Type

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to obtain the return value.

+

The value true indicates that the screen is on, and value false indicates the opposite.

+
+ + +- Example + + ``` + power.isScreenOn((error, screenOn) => { + if (typeof error === "undefined") { + console.info('screenOn status is ' + screenOn); + } else { + console.log('error: ' + error); + } + }) + ``` + + +## power.isScreenOn + +isScreenOn\(\): Promise + +Checks the screen status of the current device. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to asynchronously obtain the return value. The value true indicates that the screen is on, and value false indicates the opposite.

+
+ +- Example + + ``` + power.isScreenOn() + .then(screenOn => { + console.info('screenOn status is ' + screenOn); + }) + .catch(error => { + console.log('error: ' + error); + }) + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md new file mode 100644 index 0000000000000000000000000000000000000000..34fc52c05097d07cd12caffa8f2952492cfc95b7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -0,0 +1,777 @@ +# Obtaining Process Information + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import process from '@ohos.process'; +``` + +## Required Permissions + +None + +## Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

egid

+

number

+

Yes

+

No

+

Effective group identifier (EGID) of a process.

+

euid

+

number

+

Yes

+

No

+

Effective user identifier (EUID) of a process.

+

gid

+

number

+

Yes

+

No

+

Group identifier (GID) of a process.

+

uid

+

number

+

Yes

+

No

+

User identifier (UID) of a process.

+

groups

+

number[]

+

Yes

+

No

+

An array with supplementary group IDs.

+

pid

+

number

+

Yes

+

No

+

Process ID (PID) of a process.

+

ppid

+

number

+

Yes

+

No

+

Parent process ID (PPID) of a process.

+
+ +## ChildProcess + +Allows a process to obtain the standard input and output of its child processes, send signals, and close its child processes. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

pid

+

number

+

Yes

+

No

+

PID of the child process.

+

ppid

+

number

+

Yes

+

No

+

PPID of the child process.

+

exitCode

+

number

+

Yes

+

No

+

Exit code of the child process.

+

killed

+

boolean

+

Yes

+

No

+

Whether the parent process successfully sends a signal to the child process to terminate it.

+
+ +### wait + +wait\(\): Promise + +Waits until the child process ends. This method uses a promise to return the exit code of the child process. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<number>

+

Promise used to return the exit code of the child process.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('ls'); + var result = child.wait(); + result.then(val=>{ + console.log("result = " + val); + }) + ``` + + +### getOutput + +getOutput\(\): Promise + +Obtains the standard output of the child process. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Uint8Array>

+

Promise used to return the standard output in a Uint8Array.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('ls'); + var result = child.wait(); + child.getOutput.then(val=>{ + console.log("child.getOutput = " + val); + }) + ``` + + +### getErrorOutput + +getErrorOutput\(\): Promise + +Obtains the standard error output of the child process. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Uint8Array>

+

Promise used to return the standard error output in a Uint8Array.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('madir test.text'); + var result = child.wait(); + child.getErrorOutput.then(val=>{ + console.log("child.getErrorOutput= " + val); + }) + ``` + + +### close + +close\(\): void + +Closes the child process in running. + +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('sleep 5; ls'); + child.close(); + ``` + + +### kill + +kill\(signal: number | string\): void + +Sends a signal to the specified child process to terminate it. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

signal

+

number | string

+

Yes

+

Number or string to send.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('sleep 5; ls'); + child.kill(9); + ``` + + +## process.runCmd + +runCmd\(command: string, options?: \{ timeout : number, killSignal : number | string, maxBuffer : number \}\) : ChildProcess + +Forks a new process to run a shell command and returns the **ChildProcess** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

command

+

string

+

Yes

+

Shell command to run.

+

options

+

Object

+

No

+

Related parameters.

+
+ + **Table 1** options + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timeout

+

number

+

No

+

Maximum running time (in ms) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a killSignal to the child process to terminate it. The default value is 0.

+

killSignal

+

number | string

+

No

+

Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is SIGTERM.

+

maxBuffer

+

number

+

No

+

Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is 1024 * 1024.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

ChildProcess

+

ChildProcess object.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var child = process.runCmd('ls', { maxBuffer : 2 }); + var result = child.wait(); + child.getOutput.then(val=>{ + console.log("child.getOutput = " + val); + } + ``` + + +## process.abort + +abort\(\): void + +Aborts a process and generates a core file. This method will cause a process to exit immediately. Exercise caution when using this method. + +- Example + + ``` + import process from '@ohos.process'; + process.abort(); + ``` + + +## process.on + +on\(type: string, listener: EventListener\): void + +Stores the events triggered by the user. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the events to store.

+

listener

+

EventListener

+

Yes

+

Callback invoked to return the event.

+
+ + **Table 2** EventListener + + + + + + + + + + +

Name

+

Description

+

EventListener = (evt: Object) => void

+

Event to store.

+
+ +- Example + + ``` + import process from '@ohos.process'; + process.on("data", (e)=>{ + console.log("data callback"); + }) + ``` + + +## process.off + +off\(type: string\): boolean + +Deletes the event stored by the user. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event to delete.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the event is deleted.

+
+ +- Example + + ``` + import process from '@ohos.process'; + process.on("data", (e)=>{ + console.log("data callback"); + }) + var result = process.off("data"); + ``` + + +## process.exit + +exit\(code: number\): void + +Terminates a process. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

code

+

number

+

Yes

+

Exit code of the process.

+
+ +- Example + + ``` + import process from '@ohos.process'; + process.exit(0); + ``` + + +## process.cwd + +cwd\(\): string + +Obtains the working directory of the process. + +- Example + + ``` + import process from '@ohos.process'; + var path = process.cwd(); + ``` + + +## process.chdir + +chdir\(dir: string\): void + +Changes the working directory of the process. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

dir

+

string

+

Yes

+

New working directory.

+
+ +- Example + + ``` + import process from '@ohos.process'; + process.chdir('/system'); + ``` + + +## process.uptime + +uptime\(\): number + +Obtains the running time of the process. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Running time of the process, in seconds.

+
+ +- Example + + ``` + import process from '@ohos.process'; + var time = process.uptime(); + ``` + + +## process.kill + +kill\(pid: number, signal: number\): boolean + +Sends a signal to the specified process to terminate it. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

pid

+

number

+

Yes

+

PID of the process, to which the signal will be sent.

+

signal

+

number

+

Yes

+

Signal to send.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Whether the signal is sent successfully.

+
+ +- Example + + ``` + import process from '@ohos.process' + var pres = process.pid + var result = that.kill(pres, 28) + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 69cac33509d195b8a3160f72b127a8ea17ac448c..0c5c2e4e31605656adb3a031425c6bdb0394ebdd 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -2,8 +2,7 @@ >**Note:** > ->- The APIs of this module are supported since API version 6. ->- APIs marked with 7+ are supported since API version 7. +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..d90f8aef6a156bfc2eb68a8d639aa001831d4f11 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -0,0 +1,1214 @@ +# Resource Manager + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import resourceManager from '@ohos.resourceManager'; +``` + +## Required Permissions + +None + +## resourceManager.getResourceManager + +getResourceManager\(callback: AsyncCallback\): void + +Obtains the **ResourceManager** object of the current application. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<ResourceManager>

+

Yes

+

Asynchronous callback used to return the ResourceManager object.

+
+ + +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + mgr.getString(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +## resourceManager.getResourceManager + +getResourceManager\(bundleName: string, callback: AsyncCallback\): void + +Obtains the **ResourceManager** object of the specified application. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

bundleName

+

string

+

Yes

+

Bundle name of the specified application.

+

callback

+

AsyncCallback<ResourceManager>

+

Yes

+

Asynchronous callback used to return the ResourceManager object.

+
+ +- Example + + ``` + resourceManager.getResourceManager("com.example.myapplication", (error, mgr) => { + }); + ``` + + +## resourceManager.getResourceManager + +getResourceManager\(\): Promise + +Obtains the **ResourceManager** object of the current application. This method uses a promise to return the result. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<ResourceManager>

+

Promise used to return the ResourceManager object.

+
+ +- Example + + ``` + resourceManager.getResourceManager().then(mgr => { + mgr.getString(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }).catch(error => { + console.log(error); + }); + ``` + + +## resourceManager.getResourceManager + +getResourceManager\(bundleName: string\): Promise + +Obtains the **ResourceManager** object of the specified application. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

bundleName

+

string

+

Yes

+

Bundle name of the specified application.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<ResourceManager>

+

Promise used to return the ResourceManager object.

+
+ +- Example + + ``` + resourceManager.getResourceManager("com.example.myapplication").then(mgr => { + + }).catch(error => { + + }); + ``` + + +## Direction + +Enumerates screen directions. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

DIRECTION_VERTICAL

+

0

+

Portrait

+

DIRECTION_HORIZONTAL

+

1

+

Landscape

+
+ +## DeviceType + +Enumerates device types. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

DEVICE_TYPE_PHONE

+

0x00

+

Phone

+

DEVICE_TYPE_TABLET

+

0x01

+

Tablet

+

DEVICE_TYPE_CAR

+

0x02

+

Head unit

+

DEVICE_TYPE_PC

+

0x03

+

PC

+

DEVICE_TYPE_TV

+

0x04

+

Smart TV

+

DEVICE_TYPE_WEARABLE

+

0x06

+

Wearable

+
+ +## ScreenDensity + +Enumerates screen density types. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SCREEN_SDPI

+

120

+

Screen density with small-scale dots per inch (SDPI).

+

SCREEN_MDPI

+

160

+

Screen density with medium-scale dots per inch (MDPI)

+

SCREEN_LDPI

+

240

+

Screen density with large-scale dots per inch (LDPI).

+

SCREEN_XLDPI

+

320

+

Screen density with extra-large-scale dots per inch (XLDPI).

+

SCREEN_XXLDPI

+

480

+

Screen density with extra-extra-large-scale dots per inch (XXLDPI).

+

SCREEN_XXXLDPI

+

640

+

Screen density with extra-extra-extra-large-scale dots per inch (XXXLDPI).

+
+ +## Configuration + +Provides the device configuration. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

direction

+

Direction

+

Yes

+

No

+

Screen direction of the current device.

+

locale

+

string

+

Yes

+

No

+

Current system language.

+
+ +## DeviceCapability + +Provides the device capability. + +### Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

screenDensity

+

ScreenDensity

+

Yes

+

No

+

Screen density of the current device.

+

deviceType

+

DeviceType

+

Yes

+

No

+

Type of the current device.

+
+ +## ResourceManager + +Provides the capability of accessing application resources. + +### getString + +getString\(resId: number, callback: AsyncCallback\): void + +Obtains the string corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

callback

+

AsyncCallback<string>

+

Yes

+

Asynchronous callback used to return the obtained string.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getString(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getString + +getString\(resId: number\): Promise + +Obtains the string corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

String corresponding to the resource ID.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getString(0x1000000).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getStringArray + +getStringArray\(resId: number, callback: AsyncCallback\>\): void + +Obtains the array of strings corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

callback

+

AsyncCallback<Array<string>>

+

Yes

+

Asynchronous callback used to return the obtained array of strings.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getStringArray(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getStringArray + +getStringArray\(resId: number\): Promise\> + +Obtains the array of strings corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Array<string>>

+

Array of character strings corresponding to the specified resource ID.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getStringArray(0x1000000).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getMedia + +getMedia\(resId: number, callback: AsyncCallback\): void + +Obtains the content of the media file corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

callback

+

AsyncCallback<Array<Uint8Array>>

+

Yes

+

Asynchronous callback used to return the content of the obtained media file.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getMedia(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getMedia + +getMedia\(resId: number\): Promise + +Obtains the content of the media file corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Array<Uint8Array>>

+

Promise used to return the content of the obtained media file.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getMedia(0x1000000).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getMediaBase64 + +getMediaBase64\(resId: number, callback: AsyncCallback\): void + +Obtains the Base64 code of the image corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

callback

+

AsyncCallback<string>

+

Yes

+

Asynchronous callback used to return the obtained Base64 code of the image.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getMediaBase64(0x1000000, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getMediaBase64 + +getMediaBase64\(resId: number\): Promise + +Obtains the Base64 code of the image corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise used to return the obtained Base64 code of the image.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getMediaBase64(0x1000000).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getConfiguration + +getConfiguration\(callback: AsyncCallback\): void + +Obtains the device configuration. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Configuration>

+

Yes

+

Asynchronous callback used to return the obtained device configuration.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getConfiguration((error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getConfiguration + +getConfiguration\(\): Promise + +Obtains the device configuration. This method uses a promise to return the result. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Configuration>

+

Promise used to return the device configuration.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getConfiguration().then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getDeviceCapability + +getDeviceCapability\(callback: AsyncCallback\): void + +Obtains the device capability. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<DeviceCapability>

+

Yes

+

Asynchronous callback used to return the obtained device capability.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getDeviceCapability((error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getDeviceCapability + +getDeviceCapability\(\): Promise + +Obtains the device capability. This method uses a promise to return the result. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<DeviceCapability>

+

Promise used to return the obtained device capability.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getDeviceCapability().then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + +### getPluralString + +getPluralString\(resId: number, num: number, callback: AsyncCallback\): void + +Obtains the specified number of singular-plural strings corresponding to the specified resource ID. This method uses a callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

num

+

number

+

Yes

+

Number that determines the plural or singular form.

+

callback

+

AsyncCallback<string>

+

Yes

+

Asynchronous callback used to return the obtained singular-plural string.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getPluralString(0x1000000, 1, (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getPluralString + +getPluralString\(resId: number, num: number\): Promise + +Obtains the specified number of singular-plural strings corresponding to the specified resource ID. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

resId

+

number

+

Yes

+

Resource ID.

+

num

+

number

+

Yes

+

Number that determines the plural or singular form.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise used to return the obtained singular-plural string.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getPluralString(0x1000000, 1).then(value => { + console.log(value); + }).catch(error => { + console.log("getstring promise " + error); + }); + }); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md new file mode 100644 index 0000000000000000000000000000000000000000..9c99661eb2ae5544557b53509bcb265d4c2c094e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -0,0 +1,402 @@ +# Running Lock + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import runninglock from '@ohos.runningLock'; +``` + +## Required Permissions + +To request or use a running lock, you must declare the **ohos.permission.RUNNING\_LOCK** permission. + +## RunningLockType + +Enumerates the types of running locks. + + + + + + + + + + + + + + + + +

Description

+

Default Value

+

Description

+

BACKGROUND

+

1

+

A lock that prevents the system from hibernating.

+

PROXIMITY_SCREEN_CONTROL

+

2

+

A lock that determines whether to turn on or off the screen based on the distance away from the screen.

+
+ +## runninglock.isRunningLockTypeSupported + +isRunningLockTypeSupported\(type: RunningLockType, callback: AsyncCallback\): void + +Checks whether a specified type of **RunningLock** is supported. This function uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

RunningLockType

+

Yes

+

Type of the RunningLock object.

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to obtain the return value.

+

The value true indicates that the specified type of RunningLock is supported, and value false indicates the opposite.

+
+ +- Example + + ``` + runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (error, supported) => { + if (typeof error === "undefined") { + console.info('BACKGROUND support status is ' + supported); + } else { + console.log('error: ' + error); + } + }) + ``` + + +## runninglock.isRunningLockTypeSupported + +isRunningLockTypeSupported\(type: RunningLockType\): Promise + +Checks whether a specified type of **RunningLock** is supported. This function uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

RunningLockType

+

Yes

+

Type of the RunningLock object.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<boolean>

+

Promise used to asynchronously obtain the return value. The value true indicates that the specified type of RunningLock is supported, and value false indicates the opposite.

+
+ +- Example + + ``` + runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.PROXIMITY_SCREEN_CONTROL) + .then(supported => { + console.info('PROXIMITY_SCREEN_CONTROL support status is ' + supported); + }) + .catch(error => { + console.log('error: ' + error); + }); + ``` + + +## runninglock.createRunningLock + +createRunningLock\(name: string, type: RunningLockType, callback: AsyncCallback\): void + +Creates a **RunningLock** object. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the RunningLock object.

+

type

+

RunningLockType

+

Yes

+

Type of the RunningLock object to be created.

+

callback

+

AsyncCallback<RunningLock>

+

Yes

+

Callback used to obtain the return value.

+
+ +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runninglock => { + var used = runninglock.isUsed(); + console.info('runninglock is used: ' + used); + runninglock.lock(500); + used = runninglock.isUsed(); + console.info('after lock runninglock is used ' + used); + }) + .catch(error => { + console.log('create runningLock test error: ' + error); + }) + ``` + + +## runninglock.createRunningLock + +createRunningLock\(name: string, type: RunningLockType\): Promise + +Creates a **RunningLock** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the RunningLock object.

+

type

+

RunningLockType

+

Yes

+

Type of the RunningLock object to be created.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<RunningLock>

+

Promise used to asynchronously obtain the returned RunningLock object.

+
+ +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runninglock => { + console.info('create runningLock success'); + }) + .catch(error => { + console.log('create runningLock test error: ' + error); + }) + ``` + + +## RunningLock + +Defines a **RunningLock** object. + +### lock + +lock\(timeout: number\): void + +Locks and holds a **RunningLock** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timeout

+

number

+

No

+

Duration for locking and holding the RunningLock object.

+
+ +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runningLock => { + runningLock.lock(100) + console.info('create runningLock success') + }) + .catch(error => { + console.log('Lock runningLock test error: ' + error) + }); + ``` + + +### unlock + +unlock\(\): void + +Releases a **Runninglock** object. + +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runningLock => { + runningLock.unlock() + console.info('unLock runningLock success') + }) + .catch(error => { + console.log('unLock runningLock test error: ' + error) + }); + ``` + + +### isUsed + +isUsed\(\): boolean + +Checks the status of the **Runninglock** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the Runninglock object is held; returns false if the Runninglock object is released.

+
+ +- Example + + ``` + runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) + .then(runningLock => { + var used = runningLock.isUsed() + console.info('runningLock used status: ' + used) + }) + .catch(error => { + console.log('runningLock isUsed test error: ' + error) + }); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..6c3f45743f9c1e4144d3a8e70d1c6aff8a3d9ab5 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -0,0 +1,3748 @@ +# Sensors + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The APIs of this module are supported since API version 8. + +## Modules to Import + +``` +import sensor from '@ohos.sensor'; +``` + +## Required Permissions + +To use the pedometer sensor, you must declare the **ohos.permission.ACTIVITY\_MOTION** permission. + +To use the heart rate sensor, you must declare the **ohos.permission.READ\_HEALTH\_DATA** permission. + +To use the acceleration sensor, you must declare the **ohos.permission.ACCELEROMETER** permission. + +To use the gyroscope sensor, you must declare the **ohos.permission.GYROSCOPE** permission. + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER, callback: AsyncCallback,options?: Options\): void + +Subscribes to acceleration sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ACCELEROMETER.

+

callback

+

AsyncCallback<AccelerometerResponse>

+

Yes

+

Callback used to return the acceleration sensor data. The reported data type in the callback is AccelerometerResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + }, + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_LINEAR\_ACCELERATION\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_LINEAR\_ACCELERATION,callback:AsyncCallback, options?: Options\): void + +Subscribes to data changes of the linear acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_LINEAR_ACCELERATION.

+

callback

+

AsyncCallback<LinearAccelerometerResponse>

+

Yes

+

Callback used to return the linear acceleration sensor data. The reported data type in the callback is LinearAccelerometerResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\_UNCALIBRATED\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\_UNCALIBRATED,callback:AsyncCallback, options?: Options\): void + +Subscribes to data changes of the uncalibrated acceleration sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED.

+

callback

+

AsyncCallback<AccelerometerUncalibratedResponse>

+

Yes

+

Callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is AccelerometerUncalibratedResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_GRAVITY\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_GRAVITY, callback: AsyncCallback,options?: Options\): void + +Subscribes to gravity sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GRAVITY.

+

callback

+

AsyncCallback<GravityResponse>

+

Yes

+

Callback used to return the gravity sensor data. The reported data type in the callback is GravityResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_GRAVITY,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE, callback: AsyncCallback, options?: Options\): void + +Subscribes to gyroscope sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GYROSCOPE.

+

callback

+

AsyncCallback<GyroscopeResponse>

+

Yes

+

Callback used to return the gyroscope sensor data. The reported data type in the callback is GyroscopeResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type:SensorType.SENSOR_TYPE_ID_GUROSCOPE,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\_UNCALIBRATED\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\_UNCALIBRATED,callback:AsyncCallback, options?: Options\): void + +Subscribes to data changes of the uncalibrated gyroscope sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED.

+

callback

+

AsyncCallback<GyroscopeUncalibratedResponse>

+

Yes

+

Callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is GyroscopeUncalibratedResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_SIGNIFICANT\_MOTION\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_SIGNIFICANT\_MOTION, callback: AsyncCallback, options?: Options\): void + +Subscribes to data changes of the significant motion sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_SIGNIFICANT_MOTION.

+

callback

+

AsyncCallback<SignificantMotionResponse>

+

Yes

+

Callback used to return the significant motion sensor data. The reported data type in the callback is SignificantMotionResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info('Scalar data: ' + data.scalar); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\_DETECTION\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\_DETECTION, callback: AsyncCallback, options?: Options\): void + +Subscribes to data changes of the pedometer detection sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PEDOMETER_DETECTION.

+

callback

+

AsyncCallback<PedometerDetectResponse>

+

Yes

+

Callback used to return the pedometer detection sensor data. The reported data type in the callback is PedometerDetectResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(error,data){ + if (error) { + console.error(""Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info('Scalar data: ' + data.scalar); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_PEDOMETER, callback: AsyncCallback, options?: Options\): void + +Subscribes to pedometer sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PEDOMETER.

+

callback

+

AsyncCallback<PedometerResponse>

+

Yes

+

Callback used to return the pedometer sensor data. The reported data type in the callback is PedometerResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the number of steps. + console.info('Steps: ' + data.steps); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_TEMPERATURE\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_TEMPERATURE,callback:AsyncCallback, options?: Options\): void + +Subscribes to data changes of the ambient temperature sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_AMBIENT_TEMPERATURE.

+

callback

+

AsyncCallback<AmbientTemperatureResponse>

+

Yes

+

Callback used to return the ambient temperature sensor data. The reported data type in the callback is AmbientTemperatureResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the temperature. + console.info('Temperature: ' + data.temperature); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD, callback: AsyncCallback,options?: Options\): void + +Subscribes to data changes of the magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_MAGNETIC_FIELD.

+

callback

+

AsyncCallback<MagneticFieldResponse>

+

Yes

+

Callback used to return the magnetic field sensor data. The reported data type in the callback is MagneticFieldResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\_UNCALIBRATED\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\_UNCALIBRATED,callback:AsyncCallback, options: Options\): void + +Subscribes to data changes of the uncalibrated magnetic field sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED.

+

callback

+

AsyncCallback<MagneticFieldUncalibratedResponse>

+

Yes

+

Callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is MagneticFieldUncalibratedResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + ensor.on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + {interval: 10000000} // Set the data reporting frequency. + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_PROXIMITY\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_PROXIMITY, callback: AsyncCallback,options?: Options\): void + +Subscribes to proximity sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PROXIMITY.

+

callback

+

AsyncCallback<ProximityResponse>

+

Yes

+

Callback used to return the proximity sensor data. The reported data type in the callback is ProximityResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the proximity. + console.info('Distance: ' + data.distance); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_HUMIDITY\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_HUMIDITY, callback: AsyncCallback,options?: Options\): void + +Subscribes to humidity sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HUMIDITY.

+

callback

+

AsyncCallback<HumidityResponse>

+

Yes

+

Callback used to return the humidity sensor data. The reported data type in the callback is HumidityResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the humidity. + console.info('Humidity: ' + data.humidity); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_BAROMETER\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_BAROMETER, callback: AsyncCallback,options?: Options\): void + +Subscribes to barometer sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_BAROMETER.

+

callback

+

AsyncCallback<BarometerResponse>

+

Yes

+

Callback used to return the barometer sensor data. The reported data type in the callback is BarometerResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_BAROMETER,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the atmospheric pressure. + console.info('Atmospheric pressure: ' + data.pressure); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_HALL\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_HALL, callback: AsyncCallback, options?: Options\): void + +Subscribes to data changes of the Hall effect sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HALL.

+

callback

+

AsyncCallback<HallResponse>

+

Yes

+

Callback used to return the Hall effect sensor data. The reported data type in the callback is HallResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_HALL,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the status. + console.info('Status: ' + data.status); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_LIGHT\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_LIGHT, callback: AsyncCallback, options?: Options\): void + +Subscribes to data changes of the ambient light sensor. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_AMBIENT_LIGHT.

+

callback

+

AsyncCallback<LightResponse>

+

Yes

+

Callback used to return the ambient light sensor data. The reported data type in the callback is LightResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the illumination. + console.info(''Illumination: ' + data.intensity); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_ORIENTATION\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_ORIENTATION, callback: AsyncCallback, options?: Options\): void + +Subscribes to orientation sensor data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ORIENTATION.

+

callback

+

AsyncCallback<OrientationResponse>

+

Yes

+

Callback used to return the orientation sensor data. The reported data type in the callback is OrientationResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_ROTATION\_VECTOR\) + +on\(type:SensorType.SENSOR\_TYPE\_ID\_ROTATION\_VECTOR,callback:AsyncCallback,options?: Options\): void + +Subscribes to rotation vector data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ROTATION_VECTOR.

+

callback

+

AsyncCallback<RotationVectorResponse>

+

Yes

+

Callback used to return the rotation vector sensor data. The reported data type in the callback is RotationVectorResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + {interval: 10000000} + ); + ``` + + +## sensor.on\(SensorType.SENSOR\_TYPE\_ID\_WEAR\_DETECTION\) + +on\(type: SensorType.SENSOR\_TYPE\_ID\_WEAR\_DETECTION, callback: AsyncCallback,options?: Options\): void + +Subscribes to wear detection data changes. If this API is called multiple times for the same application, the last call takes effect. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_WEAR_DETECTION.

+

callback

+

AsyncCallback<WearDetectionResponse>

+

Yes

+

Callback used to return the wear detection sensor data. The reported data type in the callback is WearDetectionResponse.

+

options

+

Options

+

No

+

Interval at which the callback is invoked to return the sensor data. The default value is 200,000,000 ns.

+
+ +- Example + + ``` + sensor.on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(error,data){ + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the wear status. + console.info('Wear status: ' + data.value); + } + {interval: 10000000} + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER, callback: AsyncCallback\): void + +Subscribes to only one acceleration sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ACCELEROMETER.

+

callback

+

AsyncCallback<AccelerometerResponse>

+

Yes

+

One-shot callback used to return the acceleration sensor data. The reported data type in the callback is AccelerometerResponse.

+
+ + +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_LINEAR\_ACCELERATION\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_LINEAR\_ACCELERATION,callback:AsyncCallback\): void + +Subscribes to only one data change of the linear acceleration sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_LINEAR_ACCELERATION.

+

callback

+

AsyncCallback<LinearAccelerometerResponse>

+

Yes

+

One-shot callback used to return the linear acceleration sensor data. The reported data type in the callback is LinearAccelerometerResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\_UNCALIBRATED\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_ACCELEROMETER\_UNCALIBRATED,callback:AsyncCallback\): void + +Subscribes to only one data change of the uncalibrated acceleration sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED.

+

callback

+

AsyncCallback<AccelerometerUncalibratedResponse>

+

Yes

+

One-shot callback used to return the uncalibrated acceleration sensor data. The reported data type in the callback is AccelerometerUncalibratedResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_GRAVITY\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_GRAVITY, callback: AsyncCallback\): void + +Subscribes to only one gravity sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GRAVITY.

+

callback

+

AsyncCallback<GravityResponse>

+

Yes

+

One-shot callback used to return the gravity sensor data. The reported data type in the callback is GravityResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_GRAVITY, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE, callback: AsyncCallback\): void + +Subscribes to only one gyroscope sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GYROSCOPE.

+

callback

+

AsyncCallback<GyroscopeResponse>

+

Yes

+

One-shot callback used to return the gyroscope sensor data. The reported data type in the callback is GyroscopeResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\_UNCALIBRATED\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_GYROSCOPE\_UNCALIBRATED,callback:AsyncCallback\): void + +Subscribes to only one data change of the uncalibrated gyroscope sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED.

+

callback

+

AsyncCallback<GyroscopeUncalibratedResponse>

+

Yes

+

One-shot callback used to return the uncalibrated gyroscope sensor data. The reported data type in the callback is GyroscopeUncalibratedResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_SIGNIFICANT\_MOTION\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_SIGNIFICANT\_MOTION,callback:AsyncCallback\): void + +Subscribes to only one data change of the significant motion sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_SIGNIFICANT_MOTION.

+

callback

+

AsyncCallback<SignificantMotionResponse>

+

Yes

+

One-shot callback used to return the significant motion sensor data. The reported data type in the callback is SignificantMotionResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info('Scalar data: ' + data.scalar); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\_DETECTION\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\_DETECTION,callback:AsyncCallback\): void + +Subscribes to only one data change of the pedometer detection sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PEDOMETER_DETECTION.

+

callback

+

AsyncCallback<PedometerDetectResponse>

+

Yes

+

One-shot callback used to return the pedometer detection sensor data. The reported data type in the callback is PedometerDetectResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info('Scalar data: ' + data.scalar); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_PEDOMETER\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_PEDOMETER, callback: AsyncCallback\): void + +Subscribes to only one pedometer sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PEDOMETER.

+

callback

+

AsyncCallback<PedometerResponse>

+

Yes

+

One-shot callback used to return the pedometer sensor data. The reported data type in the callback is PedometerResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the number of steps. + console.info('Steps: ' + data.steps); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_TEMPERATURE\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_TEMPERATURE,callback:AsyncCallback\): void + +Subscribes to only one data change of the ambient temperature sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_AMBIENT_TEMPERATURE.

+

callback

+

AsyncCallback<AmbientTemperatureResponse>

+

Yes

+

One-shot callback used to return the ambient temperature sensor data. The reported data type in the callback is AmbientTemperatureResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the temperature data. + console.info('Temperature: ' + data.temperature); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD, callback: AsyncCallback\): void + +Subscribes to only one data change of the magnetic field sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_MAGNETIC_FIELD.

+

callback

+

AsyncCallback<MagneticFieldResponse>

+

Yes

+

One-shot callback used to return the magnetic field sensor data. The reported data type in the callback is MagneticFieldResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\_UNCALIBRATED\) + +once\(type:SensorType.SENSOR\_TYPE\_ID\_MAGNETIC\_FIELD\_UNCALIBRATED,callback:AsyncCallback\): void + +Subscribes to only one data change of the uncalibrated magnetic field sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED.

+

callback

+

AsyncCallback<MagneticFieldUncalibratedResponse>

+

Yes

+

One-shot callback used to return the uncalibrated magnetic field sensor data. The reported data type in the callback is MagneticFieldUncalibratedResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + // Print the x-, y-, and z-coordinate biases. + console.info('X-coordinate bias: ' + data.biasX); + console.info('Y-coordinate bias: ' + data.biasY); + console.info('Z-coordinate bias: ' + data.biasZ); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_PROXIMITY\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_PROXIMITY, callback: AsyncCallback\): void + +Subscribes to only one proximity sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_PROXIMITY.

+

callback

+

AsyncCallback<ProximityResponse>

+

Yes

+

One-shot callback used to return the proximity sensor data. The reported data type in the callback is ProximityResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the proximity. + console.info('Distance: ' + data.distance); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_HUMIDITY\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_HUMIDITY, callback: AsyncCallback\): void + +Subscribes to only one humidity sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HUMIDITY.

+

callback

+

AsyncCallback<HumidityResponse>

+

Yes

+

One-shot callback used to return the humidity sensor data. The reported data type in the callback is HumidityResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_HUMIDITY, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the humidity. + console.info('Humidity: ' + data.humidity); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_BAROMETER\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_BAROMETER, callback: AsyncCallback\): void + +Subscribes to only one barometer sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_BAROMETER.

+

callback

+

AsyncCallback<BarometerResponse>

+

Yes

+

One-shot callback used to return the barometer sensor data. The reported data type in the callback is BarometerResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_BAROMETER, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the atmospheric pressure. + console.info('Atmospheric pressure: ' + data.pressure); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_HALL\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_HALL, callback: AsyncCallback\): void + +Subscribes to only one data change of the Hall effect sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HALL.

+

callback

+

AsyncCallback<HallResponse>

+

Yes

+

One-shot callback used to return the Hall effect sensor data. The reported data type in the callback is HallResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_HALL, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the status. + console.info('Status: ' + data.status); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_LIGHT\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_AMBIENT\_LIGHT, callback: AsyncCallback\): void + +Subscribes to only one data change of the ambient light sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_AMBIENT_LIGHT.

+

callback

+

AsyncCallback<LightResponse>

+

Yes

+

One-shot callback used to return the ambient light sensor data. The reported data type in the callback is LightResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the illumination. + console.info('Illumination: ' + data.intensity); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_ORIENTATION\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_ORIENTATION, callback: AsyncCallback\): void + +Subscribes to only one orientation sensor data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ORIENTATION.

+

callback

+

AsyncCallback<OrientationResponse>

+

Yes

+

One-shot callback used to return the orientation sensor data. The reported data type in the callback is OrientationResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_ORIENTATION, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_ROTATION\_VECTOR\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_ROTATION\_VECTOR, callback: AsyncCallback\): void + +Subscribes to only one rotation vector data change. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_ROTATION_VECTOR.

+

callback

+

AsyncCallback<RotationVectorResponse>

+

Yes

+

One-shot callback used to return the rotation vector sensor data. The reported data type in the callback is RotationVectorResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the x-, y-, and z-coordinate components. + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_HEART\_RATE\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_HEART\_RATE, callback: AsyncCallback\): void + +Subscribes to only one data change of the heart rate sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_HEART_RATE.

+

callback

+

AsyncCallback<HeartRateResponse>

+

Yes

+

One-shot callback used to return the heart rate sensor data. The reported data type in the callback is HeartRateResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_HEART_RATE, function(error, data) { + if (error) { + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); + return; + } + // Print the heart rate. + console.info("Heart rate: " + data.heartRate); + } + ); + ``` + + +## sensor.once\(SensorType.SENSOR\_TYPE\_ID\_WEAR\_DETECTION\) + +once\(type: SensorType.SENSOR\_TYPE\_ID\_WEAR\_DETECTION, callback: AsyncCallback\): void + +Subscribes to only one data change of the wear detection sensor. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to subscribe to, which is SENSOR_TYPE_ID_WEAR_DETECTION.

+

callback

+

AsyncCallback<WearDetectionResponse>

+

Yes

+

One-shot callback used to return the wear detection sensor data. The reported data type in the callback is WearDetectionResponse.

+
+ +- Example + + ``` + sensor.once(type:SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(error, data) { + if (error) { + console.error("Failed to register data, error code is" + error.code + ", message: " + error.message); + return; + } + // Print the wear status. + console.info("Wear status: "+ data.value); + } + ); + ``` + + +## sensor.off + +off\(type: SensorType, callback?: AsyncCallback\): void + +Unsubscribes from sensor data changes. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

SensorType

+

Yes

+

Type of the sensor to unsubscribe from.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to return the execution result.

+
+ +- Example + + ``` + sensor.off(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error) { + if (error) { + console.error("Failed to unsubscribe from acceleration sensor data. Error code: " + error.code + "; message: " + error.message); + return; + } + console.info("Succeeded in unsubscribing from acceleration sensor data."); + } + ); + + ``` + + +## SensorType + +Enumerates the sensor types. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

SENSOR_TYPE_ID_ACCELEROMETER

+

1

+

Acceleration sensor.

+

SENSOR_TYPE_ID_GYROSCOPE

+

2

+

Gyroscope sensor.

+

SENSOR_TYPE_ID_AMBIENT_LIGHT

+

5

+

Ambient light sensor.

+

SENSOR_TYPE_ID_MAGNETIC_FIELD

+

6

+

Magnetic field sensor.

+

SENSOR_TYPE_ID_BAROMETER

+

8

+

Barometer sensor.

+

SENSOR_TYPE_ID_HALL

+

10

+

Hall effect sensor.

+

SENSOR_TYPE_ID_PROXIMITY

+

12

+

Proximity sensor.

+

SENSOR_TYPE_ID_HUMIDITY

+

13

+

Humidity sensor.

+

SENSOR_TYPE_ID_ORIENTATION

+

256

+

Orientation sensor.

+

SENSOR_TYPE_ID_GRAVITY

+

257

+

Gravity sensor.

+

SENSOR_TYPE_ID_LINEAR_ACCELERATION

+

258

+

Linear acceleration sensor.

+

SENSOR_TYPE_ID_ROTATION_VECTOR

+

259

+

Rotation vector sensor.

+

SENSOR_TYPE_ID_AMBIENT_TEMPERATURE

+

260

+

Ambient temperature sensor.

+

SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED

+

261

+

Uncalibrated magnetic field sensor.

+

SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED

+

263

+

Uncalibrated gyroscope sensor.

+

SENSOR_TYPE_ID_SIGNIFICANT_MOTION

+

264

+

Significant motion sensor.

+

SENSOR_TYPE_ID_PEDOMETER_DETECTION

+

265

+

Pedometer detection sensor.

+

SENSOR_TYPE_ID_PEDOMETER

+

266

+

Pedometer sensor.

+

SENSOR_TYPE_ID_HEART_RATE

+

278

+

Heart rate sensor.

+

SENSOR_TYPE_ID_WEAR_DETECTION

+

280

+

Wear detection sensor.

+

SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED

+

281

+

Uncalibrated acceleration sensor.

+
+ +## AccelerometerResponse + +Describes the acceleration sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## LinearAccelerometerResponse + +Describes the linear acceleration sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## AccelerometerUncalibratedResponse + +Describes the uncalibrated acceleration sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+

biasX

+

number

+

Yes

+

Yes

+

X-coordinate bias.

+

biasY

+

number

+

Yes

+

Yes

+

Y-coordinate bias.

+

biasZ

+

number

+

Yes

+

Yes

+

Z-coordinate bias.

+
+ +## GravityResponse + +Describes the gravity sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## OrientationResponse + +Describes the orientation sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## RotationVectorResponse + +Describes the rotation vector sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## GyroscopeResponse + +Describes the gyroscope sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## GyroscopeUncalibratedResponse + +Describes the uncalibrated gyroscope sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+

biasX

+

number

+

Yes

+

Yes

+

X-coordinate bias.

+

biasY

+

number

+

Yes

+

Yes

+

Y-coordinate bias.

+

biasZ

+

number

+

Yes

+

Yes

+

Z-coordinate bias.

+
+ +## SignificantMotionResponse + +Describes the significant motion sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

scalar

+

number

+

Yes

+

Yes

+

Intensity of a motion. This parameter specifies whether a device has a significant motion on three physical axes (X, Y, and Z). The value 0 means that the device does not have a significant motion, and 1 means the opposite.

+
+ +## ProximityResponse + +Describes the proximity sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

distance

+

number

+

Yes

+

Yes

+

Proximity between the visible object and the device monitor. The value 0 means the two are close to each other, and 1 means that they are far away from each other.

+
+ +## LightResponse + +Describes the ambient light sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

intensity

+

number

+

Yes

+

Yes

+

Illumination, in lux.

+
+ +## HallResponse + +Describes the Hall effect sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

status

+

number

+

Yes

+

Yes

+

Hall effect sensor status. This parameter specifies whether a magnetic field exists around a device. The value 0 means that a magnetic field exists around the device, and 1 means the opposite.

+
+ +## MagneticFieldResponse + +Describes the magnetic field sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+
+ +## MagneticFieldUncalibratedResponse + +Describes the uncalibrated magnetic field sensor data. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

x

+

number

+

Yes

+

Yes

+

X-coordinate component.

+

y

+

number

+

Yes

+

Yes

+

Y-coordinate component.

+

z

+

number

+

Yes

+

Yes

+

Z-coordinate component.

+

biasX

+

number

+

Yes

+

Yes

+

X-coordinate bias.

+

biasY

+

number

+

Yes

+

Yes

+

Y-coordinate bias.

+

biasZ

+

number

+

Yes

+

Yes

+

Z-coordinate bias.

+
+ +## PedometerResponse + +Describes the pedometer sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

steps

+

number

+

Yes

+

Yes

+

Number of steps. The number starts from 0 each time the device restarts.

+
+ +## HumidityResponse + +Describes the humidity sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

humidity

+

number

+

Yes

+

Yes

+

Ambient relative humidity, in a percentage (%).

+
+ +## PedometerDetectResponse + +Describes the pedometer detection sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

scalar

+

number

+

Yes

+

Yes

+

Pedometer detection. This parameter specifies whether a user takes a step. The value 0 means that the user does not take a step, and 1 means that the user takes a step.

+
+ +## AmbientTemperatureResponse + +Describes the ambient temperature sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

temperature

+

number

+

Yes

+

Yes

+

Ambient temperature, in degree Celsius.

+
+ +## BarometerResponse + +Describes the barometer sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

pressure

+

number

+

Yes

+

Yes

+

Atmospheric pressure, in pascal.

+
+ +## HeartRateResponse + +Describes the heart rate sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

heartRate

+

number

+

Yes

+

Yes

+

Heart rate, in beats per minute.

+
+ +## WearDetectionResponse + +Describes the wear detection sensor data. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

value

+

boolean

+

Yes

+

Yes

+

Whether the device is being worn. The value true means that the device is being worn, and false means the opposite.

+
+ +## Options + +Describes the sensor data reporting frequency. + + + + + + + + + + + + +

Name

+

Type

+

Description

+

interval

+

number

+

Frequency at which a sensor reports data. The default value is 200,000,000 ns.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 9d27fea1ef66d7e3727e2b3cfcaf22175668ea6c..bf7ff76d1586154ed1aff89465935d259901f5c9 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -2,8 +2,7 @@ >**Note:** > ->- The APIs of this module are supported since API version 6. ->- APIs marked with 7+ are supported since API version 7. +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index a45f89399ee9e2c5d7cd71585d08f9fb6f9c4c1c..82c9622de028bc4cf9c8e772a0f25301a8492534 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -2,9 +2,7 @@ >**Note:** > ->- The APIs of this module are supported since API version 6. -> ->- APIs marked with 7+ are supported since API version 7. +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md new file mode 100644 index 0000000000000000000000000000000000000000..32637f989dafb9d3b0a8c48796d1cc62000f5cca --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -0,0 +1,458 @@ +# systemParameter + +## Modules to Import + +``` +import parameter from '@ohos.systemParameter' +``` + +## Required Permissions + +None + +## parameter.getSync + +getSync\(key: string, def?: string\) + +Gets the value of the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

No

+

Default value

+
+ +**Return Values** + + + + + + + + + + +

Type

+

Description

+

string

+

System attribute value. If the specified key does not exist, the default value is returned. If no default value has been set, an empty string will be returned.

+
+ +**Example** + +``` +try { + var info = parameter.getSync("test.parameter.key"); + console.log(JSON.stringify(info)); +}catch(e){ + console.log("getSync unexpected error: " + e); +} +``` + +## parameter.get + +get\(key: string, callback: AsyncCallback\) + +Gets the value of the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

callback

+

AsyncCallback<string>

+

Yes

+

Callback function

+
+ +**Example** + +``` +try { + parameter.get("test.parameter.key", function (err, data) { + if (err == undefined) { + console.log("get test.parameter.key value success:" + data) + } else { + console.log(" get test.parameter.key value err:" + err.code) + }}); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + +## parameter.get + +get\(key: string, def: string, callback: AsyncCallback\) + +Gets the value of the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

Yes

+

Default value

+

callback

+

AsyncCallback<string>

+

Yes

+

Callback function

+
+ +**Example** + +``` +try { + parameter.get("test.parameter.key", "default", function (err, data) { + if (err == undefined) { + console.log("get test.parameter.key value success:" + data) + } else { + console.log(" get test.parameter.key value err:" + err.code) + } + }); +}catch(e){ + console.log("get unexpected error:" + e) +} +``` + +## parameter.get + +get\(key: string, def?: string\) + +Gets the value of the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

No

+

Default value

+
+ +**Return Values** + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise, which is used to obtain the result asynchronously

+
+ +**Example** + +``` +try { + var p = parameter.get("test.parameter.key"); + p.then(function (value) { + console.log("get test.parameter.key success: " + value); + }).catch(function (err) { + console.log("get test.parameter.key error: " + err.code); + }); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + +## parameter.setSync + +setSync\(key: string, value: string\) + +Sets a value for the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

value

+

string

+

Yes

+

System attribute value to set

+
+ +**Example** + +``` +try { + parameter.setSync("test.parameter.key", "default"); +}catch(e){ + console.log("set unexpected error: " + e); +} +``` + +## parameter.set + +set\(key: string, value: string, callback: AsyncCallback\) + +Sets a value for the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

Yes

+

Default value

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback function.

+
+ +**Example** + +``` +try { + parameter.set("test.parameter.key", "testValue", function (err, data) { + if (err == undefined) { + console.log("set test.parameter.key value success :" + data) + } else { + console.log("set test.parameter.key value err:" + err.code) + }}); +}catch(e){ + console.log("set unexpected error: " + e); +} +``` + +## parameter.set + +set\(key: string, def?: string\) + +Sets a value for the attribute with the specified key. + +**Parameters** + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

key

+

string

+

Yes

+

Key of the system attribute

+

def

+

string

+

No

+

Default value

+
+ +**Return Values** + + + + + + + + + + +

Type

+

Description

+

Promise<string>

+

Promise, which is used to obtain the result asynchronously

+
+ +**Example** + +``` +try { + var p = para.set("test.parameter.key", "testValue"); + p.then(function (value) { + console.log("set test.parameter.key success: " + value); + }).catch(function (err) { + console.log(" set test.parameter.key error: " + err.code); + }); +}catch(e){ + console.log("set unexpected error: " + e); +} +``` + diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md new file mode 100644 index 0000000000000000000000000000000000000000..e851eec1055856e6d5a97f45bb45199143ea742d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -0,0 +1,379 @@ +# Setting the System Time + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The APIs of this module are supported since API version 7. + +## Applicable Devices + + + + + + + + + + + + + + +

Phone

+

Tablet

+

Smart TV

+

Wearable

+

Yes

+

Yes

+

Yes

+

Yes

+
+ +## Modules to Import + +``` +import systemTime from '@ohos.systemTime'; +``` + +## systemTime.setTime + +setTime\(time : number, callback : AsyncCallback\) : void + +Set the system time. You must have the ohos.permission.SET\_TIME permission. The value is returned in callback mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

time

+

number

+

Yes

+

Timestamp to set, in milliseconds

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to process the received return value

+
+ +- Example + + ``` + // Set the date and time to 2021-01-20 02:36:25. + var time = 1611081385000; + systemTime.setTime(time, (error, data) => { + if (error) { + console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); + return; + } + console.log(`success to systemTime.setTime: ` + JSON.stringify(data)); + }); + ``` + + +## systemTime.setTime + +setTime\(time : number\) : Promise + +Set the system time. You must have the ohos.permission.SET\_TIME permission. The value is returned in promise mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

time

+

number

+

Yes

+

Timestamp to set, in milliseconds

+
+ + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Callback returned in promise mode

+
+ +- Example + + ``` + // Set the date and time to 2021-01-20 02:36:25. + var time = 1611081385000; + systemTime.setTime(time).then((data) => { + console.log(`success to systemTime.setTime: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); + }); + ``` + + +## systemTime.setDate + +setDate\(date: Date, callback: AsyncCallback\): void + +Set the system date. You must have the ohos.permission.SET\_TIME permission. The value is returned in callback mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

date

+

Date

+

Yes

+

Target date

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to process the received return value

+
+ +- Example + + ``` + var data = new Date("October 13, 2020 11:13:00"); + systemTime.setDate(data,(error, data) => { + if (error) { + console.error('SystemTimePlugin setDate failed because ' + JSON.stringify(error)); + return; + } + console.info('SystemTimePlugin setDate success data : ' + JSON.stringify(data)); + }); + ``` + + +## systemTime.setDate + +setDate\(date: Date\): Promise + +Set the system date. You must have the ohos.permission.SET\_TIME permission. The value is returned in promise mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

date

+

Date

+

Yes

+

Target date

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Callback returned in promise mode

+
+ +- Example + + ``` + var data = new Date("October 13, 2020 11:13:00"); + systemTime.setDate(data).then((value) => { + console.log(`SystemTimePlugin success to systemTime.setDate: ` + JSON.stringify(value)); + }).catch((error) => { + console.error(`SystemTimePlugin failed to systemTime.setDate because: ` + JSON.stringify(error)); + }); + ``` + + +## systemTime.setTimezone + +setTimezone\(timezone: string, callback: AsyncCallback\): void + +Set the system time zone. You must have the ohos.permission.SET\_TIME\_ZONE permission. The value is returned in callback mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timezone

+

string

+

Yes

+

System time zone

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback used to process the received return value

+
+ +- Example + + ``` + systemTime.setTimezone('Asia/Shanghai', (error, data) => { + if (error) { + console.error('SystemTimePlugin setTimezone failed because ' + JSON.stringify(error)); + return; + } + console.info('SystemTimePlugin setTimezone success data : ' + JSON.stringify(data)); + }); + ``` + + +## systemTime.setTimezone + +setTimezone\(timezone: string\): Promise + +Set the system time zone. You must have the ohos.permission.SET\_TIME\_ZONE permission. The value is returned in promise mode. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timezone

+

string

+

Yes

+

System time zone

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Callback returned in promise mode

+
+ +- Example + + ``` + systemTime.setTimezone('Asia/Shanghai').then((data) => { + console.log(`SystemTimePlugin success to systemTime.setTimezone: ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`SystemTimePlugin failed to systemTime.setTimezone because: ` + JSON.stringify(error)); + }); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md new file mode 100644 index 0000000000000000000000000000000000000000..c3bf1d9d3047dd4dc8bd9001b4a61fc497fe8021 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -0,0 +1,557 @@ +# Update + +The update module applies to updates throughout the entire OpenHarmony system, including built-in resources and preset applications, but not third-party applications. + +There are two types of updates: SD card update and over the air (OTA) update. + +- The SD card update depends on the update packages and SD cards. +- The OTA update depends on the server deployed by the phone manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the phone manufacturer. + +## Modules to Import + +```js +import client from '@ohos.update' +``` + +## Required Permissions + +None + +## Updater + +### getNewVersionInfo + +getNewVersionInfo(callback: AsyncCallback\): void + +Obtains the new version information. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ------------------------------------------------ | ---- | ------------------ | +| callback | AsyncCallback<[NewVersionInfo](#newversioninfo)> | No| Callback used to return the new version information.| + +**Example** + +``` +updater.getNewVersionInfo(info => { + console.log("getNewVersionInfo success " + info.status); + console.log(`info versionName = ` + info.result[0].versionName); + console.log(`info versionCode = ` + info.result[0].versionCode); + console.log(`info verifyInfo = ` + info.result[0].verifyInfo); +)}; +``` + +### getNewVersionInfo + +getNewVersionInfo(): Promise\ + +Obtains the new version information. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ------------------------------------------- | ------------------------- | +| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the new version information.| + +**Example** + +``` +var p = updater.getNewVersionInfo(); +p.then(function (value) { + console.log(`info versionName = ` + value.result[0].versionName); + console.log(`info versionCode = ` + value.result[0].versionCode); + console.log(`info verifyInfo = ` + value.result[0].verifyInfo); +}).catch(function (err) { + console.log("getNewVersionInfo promise error: " + err.code); +)}; +``` + +### checkNewVersion + +checkNewVersion(callback: AsyncCallback\): void + +Checks whether the current version is the latest. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ------------------------------------------------- | ---- | ------------------ | +| callback | AsyncCallback\<[NewVersionInfo](#newversioninfo)> | No| Callback used to return the new version information.| + +**Example** + +``` +updater.checkNewVersion(info => { + console.log("checkNewVersion success " + info.status); + console.log(`info versionName = ` + info.result[0].versionName); + console.log(`info versionCode = ` + info.result[0].versionCode); + console.log(`info verifyInfo = ` + info.result[0].verifyInfo); +)}; +``` + +### checkNewVersion + +checkNewVersion(): Promise\ + +Checks whether the current version is the latest. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ------------------------------------------- | ------------------------- | +| Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the new version information.| + +**Example** + +``` +var p = updater.checkNewVersion(); +p.then(function (value) { + console.log(`info versionName = ` + value.result[0].versionName); + console.log(`info versionCode = ` + value.result[0].versionCode); + console.log(`info verifyInfo = ` + value.result[0].verifyInfo); +}).catch(function (err) { + console.log("checkNewVersion promise error: " + err.code); +)}; +``` + +### verifyUpdatePackage + +verifyUpdatePackage(upgradeFile: string, certsFile: string): void + +Verifies whether the update package is valid. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------ | ---- | ------------------ | +| upgradeFile | string | Yes| Path of the update package to be verified.| +| certsFile | string | Yes| Certificate path.| + +**Example** + +``` +var getVar = update.getUpdater(); +getVar.on("verifyProgress", function (callback){ + console.info('on verifyProgress ' + callback.percent); +}); +getVar.verifyUpdatePackage("XXX", "XXX"); +getVar.off("verifyProgress"); +``` + +### rebootAndCleanUserData + +rebootAndCleanUserData(): Promise\ + +Reboots the device and clears the user partition data. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ---------------- | ------------------------------- | +| Promise\ | Promise used to return the execution result.| + +**Example** + +``` +var getVar = update.getUpdater(); +p = getVar.rebootAndCleanUserData(); +p.then(function (value) { + console.info("rebootAndCleanUserData promise success: " + value); +}).catch(function (err) { + console.info("rebootAndCleanUserData promise error: " + err.code); +}); +``` + +### rebootAndCleanUserData + +rebootAndCleanUserData(callback: AsyncCallback\): void + +Reboots the device and clears the user partition data. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | ---- | ---------------------- | +| callback | Function | Yes| AsyncCallback\ | + +**Example** + +``` +var getVar = update.getUpdater(); +getVar.rebootAndCleanUserData(function (err, data) { + if (err.code == 0) { + console.info("rebootAndCleanUserData callback success:" + data) + } else { + console.info("rebootAndCleanUserData callback err:" + err.code) + } +}); +``` + +### applyNewVersion + +applyNewVersion(): Promise\ + +Installs the update package. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ---------------- | ------------------------------- | +| Promise\ | Promise used to return the execution result.| + +**Example** + +``` +var getVar = update.getUpdater(); +p.then(function (value) { + console.info("applyNewVersion promise success: " + value); +}).catch(function (err) { + console.info("applyNewVersion promise error: " + err.code); +}); +``` + +### applyNewVersion + +applyNewVersion(callback: AsyncCallback\): void + +Installs the update package. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | ---- | ---------------------- | +| callback | Function | Yes| AsyncCallback\ | + +**Example** + +``` +var getVar = update.getUpdater(); +getVar.applyNewVersion(function (err, data) { + if (err.code == 0) { + console.info("applyNewVersion callback success:" + data) + } else { + console.info("applyNewVersion callback err:" + err.code) + } +}); +``` + +### download + +download(): void + +Downloads the new version and displays the download process. + +**Example** + +``` +updater.on("downloadProgress", progress => { + console.log("downloadProgress on" + progress); + console.log(`downloadProgress status: ` + progress.status); + console.log(`downloadProgress percent: ` + progress.percent); +)}; +updater.download(); +``` + +### upgrade + +updater.upgrade():void + +Starts an update. + +**Example** + +``` +updater.on("upgradeProgress", progress => { + console.log("upgradeProgress on" + progress); + console.log(`upgradeProgress status: ` + progress.status); + console.log(`upgradeProgress percent: ` + progress.percent); +)}; +updater.upgrade(); +``` + +### setUpdatePolicy + +setUpdatePolicy(policy: UpdatePolicy, callback: AsyncCallback\): void + +Sets the update policy. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ----------------------------- | ---- | ------------ | +| policy | [UpdatePolicy](#updatepolicy) | Yes| Update policy to set.| +| callback | AsyncCallback\ | Yes| Callback used to return the execution result.| + +**Example** + +``` +// Set the update policy. +let policy = { +autoDownload: false, +autoDownloadNet: true, +mode: 2, +autoUpgradeInterval: [ 2, 3 ], +autoUpgradeCondition: 2 +} +updater.setUpdatePolicy(policy, function(result) { +console.log("setUpdatePolicy ", result)}); +``` + +### setUpdatePolicy + +setUpdatePolicy(policy: UpdatePolicy): Promise\ + +Sets the update policy. This method uses a promise to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | ----------------------------- | ---- | ------------ | +| policy | [UpdatePolicy](#updatepolicy) | Yes| Update policy to set.| + +**Return values** + +| Type| Description| +| ---------------- | ----------------------- | +| Promise\ | Promise used to return the execution result.| + +**Example** + +``` +let policy = { +autoDownload: false, +autoDownloadNet: true, +mode: 2, +autoUpgradeInterval: [ 2, 3 ], +autoUpgradeCondition: 2 +} +updater.setUpdatePolicy(policy) +.then(data=> +console.log('Policy set successfully') +) +``` + +### getUpdatePolicy + +getUpdatePolicy(callback: AsyncCallback\): void + +Obtains the update policy. This method uses an asynchronous callback to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | --------------------------------------------- | ---- | -------------------- | +| callback | AsyncCallback\<[UpdatePolicy](#updatepolicy)> | No| Callback used to return the update policy.| + +**Example** + +``` +updater.getUpdatePolicy(policy => { + console.log("getUpdatePolicy success"); + console.log(`policy autoDownload = ` + policy.autoDownload); + console.log(`policy autoDownloadNet = ` + policy.autoDownloadNet); + console.log(`policy mode = ` + policy.mode); +)}; +``` + +### getUpdatePolicy + +getUpdatePolicy(): Promise\ + +Obtains the update policy. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| --------------------------------------- | --------------------------- | +| Promise\<[UpdatePolicy](#updatepolicy)> | Promise used to return the update policy.| + +**Example** + +``` +p = updater.getUpdatePolicy(); +p.then(function (value) { + console.log(`info autoDownload = ` + value.autoDownload); + console.log(`info autoDownloadNet = ` + value.autoDownloadNet); + console.log(`info mode = ` + value.mode); +}).catch(function (err) { + console.log("getUpdatePolicy promise error: " + err.code); +)}; +``` + +## update.getUpdater + +getUpdater(upgradeFile: string, updateType?: UpdateTypes): Updater + +Obtains the updater for the local update. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | --------------------------- | ---- | -------- | +| upgradeFile | string | Yes| Update file.| +| updateType | [UpdateTypes](#updatetypes) | Yes| Update type.| + +**Return values** + +| Type| Description| +| ------------------- | -------- | +| [Updater](#updater) | Updater object.| + +**Example** + +``` +try { + page.data.updater = update.getUpdater('/data/updater/updater.zip', 'OTA'); +} catch(error) { + console.error("Failed to get updater. Error: " + error); +} +``` + +## update.getUpdaterForOther + +getUpdaterForOther(upgradeFile: string, device: string, updateType?: UpdateTypes): Updater + +Obtains the updater for the device to be updated. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | --------------------------- | ---- | ---------- | +| upgradeFile | string | Yes| Update file.| +| device | string | Yes| Device to be updated.| +| updateType | [UpdateTypes](#updatetypes) | Yes| Update type.| + +**Return values** + +| Type| Description| +| ------------------- | -------- | +| [Updater](#updater) | Updater object.| + +**Example** + +``` +try { + page.data.updater = update.getUpdaterForOther('/data/updater/updater.zip', '1234567890', 'OTA'); +} catch(error) { + console.error("Failed to get updater. Error: " + error); +} +``` + +## update.getUpdaterFromOther + +getUpdaterFromOther(upgradeFile: string, device: string, updateType?: UpdateTypes): Updater + +Obtains the updater from another device for the device to be updated. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | --------------------------- | ---- | ---------- | +| upgradeFile | string | Yes| Update file.| +| device | string | Yes| Device to be updated.| +| updateType | [UpdateTypes](#updatetypes) | Yes| Update type.| + +**Return values** + +| Type| Description| +| ------------------- | -------- | +| [Updater](#updater) | Updater object.| + +**Example** + +``` +try { + page.data.updater = update.getUpdaterFromOther('/data/updater/updater.zip', '1234567890', 'OTA'); +} catch(error) { + console.error("Failed to get updater. Error: " + error); +} +``` + +## UpdateTypes + +Describes the update type. + +| Name| Description| +| ------ | -------- | +| OTA | OTA update.| +| patch | Patch update.| + +## PackageTypes + +Enumerates the update package types. + +| Name| Default Value| Description| +| -------------------- | ------ | -------------- | +| PACKAGE_TYPE_NORMAL | 1 | Common update package.| +| PACKAGE_TYPE_BASE | 2 | Basic update package.| +| PACKAGE_TYPE_CUST | 3 | Custom update package.| +| PACKAGE_TYPE_PRELOAD | 4 | Preinstalled update package.| +| PACKAGE_TYPE_COTA | 5 | Parameter configuration update package.| +| PACKAGE_TYPE_VERSION | 6 | Version update package.| +| PACKAGE_TYPE_PATCH | 7 | Patch package.| + +## InstallMode + +Enumerates the update modes. + +| Name| Default Value| Description| +| ------------------- | ------ | -------- | +| INSTALL_MODE_NORMAL | 0 | Normal update.| +| INSTALL_MODE_NIGHT | 1 | Update at night.| +| INSTALL_MODE_AUTO | 2 | Automatic update.| + +## NewVersionStatus + +Enumerates the new version check results. + +| Name| Default Value| Description| +| ------------------- | ------ | ---------------- | +| VERSION_STATUS_ERR | -1 | System error while checking for the new version.| +| VERSION_STATUS_NEW | 0 | New version detected.| +| VERSION_STATUS_NONE | 1 | No new version detected.| +| VERSION_STATUS_BUSY | 2 | System busy while checking for the new version.| + +## UpdatePolicy + +Defines the update policy. + +| Name| Parameter type.| Mandatory| Description| +| ------------------- | --------------------------- | ---- | -------------- | +| autoDownload | bool | Yes| Automatic update switch.| +| installMode | [InstallMode](#installmode) | Yes| Update mode.| +| autoUpgradeInterval | Array\ | Yes| Period of time for automatic update.| + +## NewVersionInfo + +Defines the new version information. + +| Name| Type| Mandatory| Description| +| --------------- | ------------------------------------------- | ---- | -------- | +| status | [NewVersionStatus](#newversionstatus) | Yes| Update status.| +| errMsg | string | Yes| Error message.| +| checkResults | Array<[CheckResult](#checkresult)> | Yes| Check result.| +| descriptionInfo | Array\<[DescriptionInfo](#descriptioninfo)> | Yes| Description.| + +## CheckResult + +Defines the check result. + +| Name| Type| Mandatory| Description| +| ------------- | ----------------------------- | ---- | ------------ | +| versionName | string | Yes| Version name.| +| versionCode | number | Yes| Version code.| +| size | number | Yes| Version size.| +| verifyInfo | string | Yes| Version verification information.| +| packageType | [PackageTypes](#packagetypes) | Yes| Version type.| +| descriptionId | string | Yes| Version description.| + +## DescriptionInfo + +Defines the version description information. + +| Name| Type| Mandatory| Description| +| ------------- | -------- | ---- | ----------------- | +| descriptionId | string | Yes| Version ID information.| +| content | string | Yes| Version changelog information.| diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md new file mode 100644 index 0000000000000000000000000000000000000000..bf7b0aca1a140b669759b1df81fff9b41cd26125 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -0,0 +1,421 @@ +# URL String Parsing + +> ![](../../public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import Url from '@ohos.url' +``` + + +## Required Permissions + +None + + +## URLSearchParams + + +### constructor + +constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) + +Creates a **URLSearchParams** instance. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| + +- Example + ``` + var objectParams = new URLSearchParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); + var objectParams1 = new URLSearchParams({"fod" : 1 , "bard" : 2}); + var objectParams2 = new URLSearchParams('?fod=1&bard=2'); + var urlObject = new URL('https://developer.mozilla.org/?fod=1&bard=2'); + var params = new URLSearchParams(urlObject .search); + ``` + + +### append + +append(name: string, value: string): void + +Appends a key-value pair into the query string. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Key of the key-value pair to append.| + | value | string | Yes| Value of the key-value pair to append.| + +- Example + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsObject = new URLSearchParams(urlObject.search.slice(1)); + paramsObject.append('fod', 3); + ``` + + +### delete + +delete(name: string): void + +Deletes key-value pairs of the specified key. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Key of the key-value pairs to delete.| + +- Example + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsobject = new URLSearchParams(urlObject.search.slice(1)); + paramsobject.delete('foo'); + ``` + + +### getAll + +getAll(name: string): string[] + +Obtains all the key-value pairs based on the specified key. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Key specified to obtain all key-value pairs.| + +- Return values + | Type| Description| + | -------- | -------- | + | string[] | All key-value pairs matching the specified key.| + +- Example + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsObject = new URLSearchParams(urlObject.search.slice(1)); + paramsObject.append('fod', 3); // Add a second value for the foo parameter. + console.log(params.getAll('fod')) // Output ["1","3"]. + ``` + + +### entries + +entries(): IterableIterator<[string, string]> + +Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. + +- Return values + | Type| Description| + | -------- | -------- | + | IterableIterator<[string, string]> | An ES6 iterator.| + +- Example + ``` + var searchParamsObject = new URLSearchParams("keyName1=valueName1&keyName2=valueName2"); + for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs + console.log(pair[0]+ ', '+ pair[1]); + } + ``` + + +### forEach + +forEach(callbackfn: (value: string, key: string, searchParams: Object) => void, thisArg?: Object): void + +Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callbackfn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| + | thisArg | Object | No| Value to use when the callback is invoked.| + + **Table 1** callbackfn parameter description + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | value | string | Yes| Value that is currently traversed.| + | key | string | Yes| Key that is currently traversed.| + | searchParams | Object | Yes| Instance that invokes the **forEach** method.| + +- Example + ``` + const myURLObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + myURLObject.searchParams.forEach((value, name, searchParams) => { + console.log(name, value, myURLObject.searchParams === searchParams); + }); + ``` + + +### get + +get(name: string): string | null + +Obtains the value of the first key-value pair based on the specified key. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Key specified to obtain the value.| + +- Return values + | Type| Description| + | -------- | -------- | + | string | Returns the value of the first key-value pair if obtained.| + | null | Returns null if no value is obtained.| + +- Example + ``` + var paramsOject = new URLSearchParams(document.location.search.substring(1)); + var name = paramsOject.get("name"); // is the string "Jonathan" + var age = parseInt(paramsOject.get("age"), 10); // is the number 18 + var address = paramsOject.get("address"); // null + ``` + + +### has + +has(name: string): boolean + +Checks whether a key has a value. +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Key specified to search for its value.| + +- Return values + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the value exists; returns **false** otherwise.| + +- Example + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsObject = new URLSearchParams(urlObject.search.slice(1)); + paramsObject.has('bard') === true; + ``` + + +### set + +set(name: string, value: string): void + +Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Key of the value to set.| + | value | string | Yes| Value to set.| + +- Example + ``` + let urlObject = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let paramsObject = new URLSearchParams(urlObject.search.slice(1)); + paramsObject.set('baz', 3); // Add a third parameter. + ``` + + +### sort + +sort(): void + + +Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns undefined. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained. + + +- Example + ``` + var searchParamsObject = new URLSearchParams("c=3&a=9&b=4&d=2"); // Create a test URLSearchParams object + searchParamsObject.sort(); // Sort the key/value pairs + console.log(searchParamsObject.toString()); // Display the sorted query string // Output a=9&b=2&c=3&d=4 + ``` + + +### keys + +keys(): IterableIterator<string> + + +Obtains an ES6 iterator that contains the keys of all the key-value pairs. + + +- Return values + | Type| Description| + | -------- | -------- | + | IterableIterator<string> | ES6 iterator that contains the keys of all the key-value pairs.| + + +- Example + ``` + var searchParamsObject = new URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing + for (var key of searchParamsObject .keys()) { // Output key-value pairs + console.log(key); + } + ``` + + +### values + +values(): IterableIterator<string> + +Obtains an ES6 iterator that contains the values of all the key-value pairs. + +- Return values + | Type| Description| + | -------- | -------- | + | IterableIterator<string> | ES6 iterator that contains the values of all the key-value pairs.| + +- Example + ``` + var searchParams = new URLSearchParams("key1=value1&key2=value2"); // Create a URLSearchParamsObject object for testing + for (var value of searchParams.values()) { + console.log(value); + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator](): IterableIterator<[string, string]> + + +Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. + + +- Return values + | Type| Description| + | -------- | -------- | + | IterableIterator<[string, string]> | An ES6 iterator.| + + +- Example + ``` + const paramsObject = new URLSearchParams('fod=bay&edg=bap'); + for (const [name, value] of paramsObject) { + console.log(name, value); + } + ``` + + +### tostring + +toString(): string + + +Obtains search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string. + + +- Return values + | Type| Description| + | -------- | -------- | + | string | String of serialized search parameters, which is percent-encoded if necessary.| + + +- Example + ``` + let url = new URL('https://developer.exampleUrl/?fod=1&bard=2'); + let params = new URLSearchParams(url.search.slice(1)); + params.append('fod', 3); + console.log(params.toString()); + ``` + + +## URL + + +### Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| hash | string | Yes| Yes| String that contains a harsh mark (#) followed by the fragment identifier of a URL.| +| host | string | Yes| Yes| Host information in a URL.| +| hostname | string | Yes| Yes| Hostname (without the port) in a URL.| +| href | string | Yes| Yes| String that contains the whole URL.| +| origin | string | Yes| No| Read-only string that contains the Unicode serialization of the origin of the represented URL.| +| password | string | Yes| Yes| Password in a URL.| +| pathname | string | Yes| Yes| Path in a URL.| +| port | string | Yes| Yes| Port in a URL.| +| protocol | string | Yes| Yes| Protocol in a URL.| +| search | string | Yes| Yes| Serialized query string in a URL.| +| searchParams | URLsearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| +| username | string | Yes| Yes| Username in a URL.| + + +### constructor + +constructor(url: string, base?: string | URL) + + +Creates a URL. + + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | url | string | Yes| Input object.| + | base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| + + +- Example + ``` + var mm = 'http://username:password@host:8080'; + var a = new URL("/", mm); // Output 'http://username:password@host:8080/'; + var b = new URL(mm); // Output 'http://username:password@host:8080/'; + new URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; + var c = new URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; + new URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; + new URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; + new URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 + new URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL + new URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL + new URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ + new URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ + ``` + + +### tostring + +toString(): string + +Converts the parsed URL into a string. + + +- Return values + | Type| Description| + | -------- | -------- | + | string | Website address in a serialized string.| + + +- Example + ``` + const url = new URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); + url.toString() + ``` + + +### toJSON + +toJSON(): string + + +Converts the parsed URL into a JSON string. + + +- Return values + | Type| Description| + | -------- | -------- | + | string | Website address in a serialized string.| + + +- Example + ``` + const url = new URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); + url.toJSON() + ``` diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md new file mode 100644 index 0000000000000000000000000000000000000000..34e564a8a54a4c9f4c187d00aa5f8c36c3a861c8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -0,0 +1,669 @@ +# String Encoding and Decoding + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import util from '@ohos.util'; +``` + +## Required Permissions + +None + +## util.printf + +printf\(format: string, ...args: Object\[\]\): string + +Prints the input content in a formatted string. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

format

+

string

+

Yes

+

Format of the string to print.

+

...args

+

Object[]

+

No

+

Data to format.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

String in the specified format.

+
+ +- Example + + ``` + var res = util.printf("%s", "hello world!"); + console.log(res); + ``` + + +## util.getErrorString + +getErrorString\(errno: number\): string + +Obtains detailed information about a system error code. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

errno

+

number

+

Yes

+

Error code generated.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Detailed information about the error code.

+
+ +- Example + + ``` + var errnum = 10; // 10: a system error number + var result = util.getErrorString(errnum); + console.log("result = " + result); + ``` + + +## util.callbackWrapper + +callbackWrapper\(original: Function\): \(err: Object, value: Object\)=\>void + +Calls back an asynchronous function. In the callback, the first parameter indicates the cause of the rejection \(if the promise has been resolved, the value is **null**\), and the second parameter indicates the resolved value. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

original

+

Function

+

Yes

+

Asynchronous function.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Function

+

Callback, in which the first parameter indicates the cause of the rejection (the value is null if the promise has been resolved) and the second parameter indicates the resolved value.

+
+ +- Example + + ``` + async function promiseFn() { + return Promise.reject('value'); + } + var cb = util.callbackWrapper(promiseFn); + cb((err, ret) => { + expect(err).strictEqual('value'); + expect(ret).strictEqual(undefined); + }) + ``` + + +## util.promiseWrapper + +promiseWrapper\(original: \(err: Object, value: Object\) =\> void\): Object + +Processes an asynchronous function and returns a promise version. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

original

+

Function

+

Yes

+

Asynchronous function to process.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Function

+

Function in the common error-first style (that is, (err, uses value) =>... is used as the last parameter) and the promise version.

+
+ +- Example + + ``` + function aysnFun(str1, str2, callback) { + if (typeof str1 === 'string' && typeof str1 === 'string') { + callback(null, str1 + str2); + } else { + callback('type err'); + } + } + let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); + newPromiseObj.then(res => { + expect(res).strictEqual('HelloWorld'); + }) + ``` + + +## TextDecoder + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

encoding

+

string

+

Yes

+

No

+

Encoding format.

+
  • Supported formats: utf-8, ibm866, iso-8859-2, iso-8859-3, iso-8859-4, iso-8859-5, iso-8859-6, iso-8859-7, iso-8859-8, iso-8859-8-i, iso-8859-10, iso-8859-13, iso-8859-14, iso-8859-15, koi8-r, koi8-u, macintosh, windows-874, windows-1250, windows-1251, windows-1252, windows-1253, windows-1254, windows-1255, windows-1256, windows-1257, windows-1258, x-mac-cyrilli, gbk, gb18030, big5, euc-jp, iso-2022-jp, shift_jis, euc-kr, utf-16be, utf-16le
+

fatal

+

boolean

+

Yes

+

No

+

Whether to display fatal errors.

+

ignoreBOM

+

boolean

+

Yes

+

No

+

Whether to ignore the byte order marker (BOM). The default value is false.

+
+ +### constructor + +constructor\(encoding?: string, options?: \{ fatal?: boolean; ignoreBOM?: boolean \},\) + +A constructor used to create a **TextDecoder** instance. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

encoding

+

string

+

No

+

Encoding format.

+

options

+

Object

+

No

+

Encoding-related options, which include fatal and ignoreBOM.

+
+ + **Table 1** options + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fatal

+

boolean

+

No

+

Whether to display fatal errors.

+

ignoreBOM

+

boolean

+

No

+

Whether to ignore the BOM.

+
+ +- Example + + ``` + var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM:true}); + ``` + + +### decode + +decode\(input: Uint8Array, options?:\{stream?:false\}\): string + +Decodes the input parameters and outputs the text. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

input

+

Uint8Array

+

Yes

+

Uint8Array to decode.

+

options

+

Object

+

No

+

Options related to decoding.

+
+ + **Table 2** options + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

stream

+

boolean

+

No

+

Whether to allow data blocks in the subsequent decode(). Set this parameter to true if data blocks are processed. If data is not divided into blocks or the last data block is processed, set this parameter to false. The default value is false.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Data decoded.

+
+ +- Example + + ``` + var textDecoder = new util.TextDecoder("utf-8",{ignoreBOM:true}); + var result = new Uint8Array(6); + result[0] = 0xEF; + result[1] = 0xBB; + result[2] = 0xBF; + result[3] = 0x61; + result[4] = 0x62; + result[5] = 0x63; + console.log("input num:"); + for(var j= 0; j < 6; j++) { + console.log(result[j]); + } + var retStr = textDecoder.decode( result , {stream:false}); + console.log("retStr = " + retStr); + ``` + + +## TextEncoder + +### Attributes + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

encoding

+

string

+

Yes

+

No

+

Encoding format. The default value is utf-8.

+
+ +### constructor + +constructor\(\) + +A constructor used to create a **TextEncoder** instance. + +- Example + + ``` + var textEncoder = new util.TextEncoder(); + ``` + + +### encode + +encode\(input?: string\): Uint8Array + +Encodes the input parameter. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

input

+

string

+

Yes

+

String to encode.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Uint8Array

+

Encoded text.

+
+ +- Example + + ``` + var textEncoder = new util.TextEncoder(); + var result = new Uint8Array(buffer); + result = textEncoder.encode("\uD800¥¥"); + ``` + + +### encodeInto + +encodeInto\(input: string, dest: Uint8Array,\):\{ read: number; written: number \} + +Stores the UTF-8 encoded text. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

input

+

string

+

Yes

+

String to encode.

+

dest

+

Uint8Array

+

Yes

+

Uint8Array instance used to store the UTF-8 encoded text.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Uint8Array

+

Encoded text.

+
+ +- Example + + ``` + var that = new util.TextEncoder(); + var buffer = new ArrayBuffer(4); + this.dest = new Uint8Array(buffer); + var result = that.encodeInto("abcd", this.dest); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md new file mode 100644 index 0000000000000000000000000000000000000000..661c24307550feeee1e511d2c9058aa649b2705a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -0,0 +1,413 @@ +# Vibration + +>![](../../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. + +## Modules to Import + +``` +import vibrate from '@ohos.vibrator'; +``` + +## Required Permissions + +ohos.permission.VIBRATE + +## vibrate.vibrate + +vibrate\(duration: number\): Promise + +Triggers vibration with a specific duration. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

duration

+

number

+

Yes

+

Vibration duration.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to indicate whether the vibration is triggered successfully.

+
+ + +- Example + + ``` + vibrator.vibrate(1000).then(error)=>{ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + console.log("Promise returned to indicate a successful vibration."); + } + } + ``` + + +## vibrate.vibrate + +vibrate\(duration: number, callback?: AsyncCallback\): void + +Triggers vibration with a specific duration. This method uses a callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

duration

+

number

+

Yes

+

Vibration duration.

+

callback

+

AsyncCallback<void>

+

No

+

Callback used to indicate whether the vibration is triggered successfully.

+
+ +- Example + + ``` + vibrator.vibrate(1000,function(error){ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + console.log("Callback returned to indicate a successful vibration."); + } + }) + ``` + + +## vibrate.vibrate + +vibrate\(effectId: EffectId\): Promise + +Triggers vibration with a specific effect. This method uses a promise to return the execution result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

effectId

+

EffectId

+

Yes

+

String that indicates the vibration effect.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to indicate whether the vibration is triggered successfully.

+
+ + +- Example + + ``` + vibrator.vibrate(effectId:EffectId).then(error)=>{ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + Console.log("Promise returned to indicate a successful vibration."); + } + } + ``` + + +## vibrate.vibrate + +vibrate\(effectId: EffectId, callback?: AsyncCallback\): void + +Triggers vibration with a specific effect. This method uses a callback to return the execution result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

effectId

+

EffectId

+

Yes

+

String that indicates the vibration effect.

+

callback

+

AsyncCallback<void>

+

No

+

Callback used to indicate whether the vibration is triggered successfully.

+
+ +- Example + + ``` + vibrator.vibrate(effectId:EffectId,function(error){ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + console.log("Callback returned to indicate a successful vibration."); + } + }) + ``` + + +## vibrate.stop + +stop\(stopMode: VibratorStopMode\): Promise + +Stops the vibration based on the specified **stopMode**. This method uses a promise to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this method fails to be called. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

stopMode

+

VibratorStopMode

+

Yes

+

Vibration mode to stop.

+
+ +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to indicate whether the vibration is stopped successfully.

+
+ + +- Example + + ``` + vibrator.stop(stopMode:VibratorStopMode).then((error)=>{ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + Console.log("Promise returned to indicate a successful stop."); + } + }) + ``` + + +## vibrate.stop + +stop\(stopMode: VibratorStopMode, callback?: AsyncCallback\): void; + +Stops the vibration based on the specified **stopMode**. This method uses a callback to return the execution result. If the specified **stopMode** is different from the mode used to trigger the vibration, this method fails to be called. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

stopMode

+

VibratorStopMode

+

Yes

+

Vibration mode to stop.

+

callback

+

AsyncCallback<void>

+

No

+

Callback used to indicate whether the vibration is stopped successfully.

+
+ +- Example + + ``` + vibrator.stop(stopMode:VibratorStopMode,function(error){ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + Console.log("Callback returned to indicate a successful stop."); + } + }) + ``` + + +## EffectId + +Describes the vibration effect. + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

EFFECT_CLOCK_TIMER

+

"haptic.clock.timer"

+

Vibration effect of the vibrator when a user adjusts the timer.

+
+ +## VibratorStopMode + +Describes the vibration mode to stop. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

VIBRATOR_STOP_MODE_TIME

+

"time"

+

Indicates that the vibration to stop is in duration mode. This vibration is triggered with the parameter duration of the number type.

+

VIBRATOR_STOP_MODE_PRESET

+

"preset"

+

Indicates the vibration to stop is in EffectId mode. This vibration is triggered with the parameter effectId of the EffectId type.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md new file mode 100644 index 0000000000000000000000000000000000000000..617d88183d0a304378d2f73efaf709a3f636499b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -0,0 +1,124 @@ +# WLAN + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import wifi from '@ohos.wifi_native_js'; +``` + +## wifi.isWifiActive + +isWifiActive(): boolean + +Checks whether WLAN is activated. + +**Return values** + +| Type| Description| +| -------- | ---------------------------- | +| boolean | Returns **true** if WLAN is activated; returns **false** otherwise.| + +## wifi.getSignalLevel + +getSignalLevel(rssi: number, band: number): number + +Obtains the WLAN signal strength. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---------- | -------- | -------- | --------------------- | +| rssi | number | Yes| Signal strength (in dBm) of the hotspot.| +| band | number | Yes| Frequency band of the WLAN access point (AP).| + +**Return values** + +| Type| Description| +| -------- | ---------------------------- | +| number | Signal strength obtained. The value range is 0 to 4.| + +## wifi.scan + +scan(): boolean + +Starts a scan for WLAN. + +**Return values** + +| Type| Description| +| -------- | -------------------------------------------- | +| boolean | Returns **true** if the scan is successful; returns **false** otherwise.| + +## wifi.getScanInfos + +getScanInfos(): Promise> + +Obtains the scan result. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ------------------------------------------------ | ---------------------- | +| Promise< Array\<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the scan result, which is a list of hotspots detected.| + +## wifi.getScanInfos + +getScanInfos(callback: AsyncCallback>): void + +Obtains the scan result. This method uses an asynchronous callback to return the result. + +| Name| Type| Mandatory| Description| +| ---------- | ----------------------------------------------------- | -------- | ------------------------------ | +| callback | AsyncCallback< Array\<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result, which is a list of hotspots detected.| + +**Example** + +``` +import wifi from '@ohos.wifi_native_js'; + + +wifi.getScanInfos(result => { + var len = Object.keys(result).length; + console.log("received scan info size: " + len); + for (var i = 0; i < len; ++j) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("timestamp: " + result[i].timestamp); + } +}); + +wifi.getScanInfos().then(result => { + var len = Object.keys(result).length; + console.log("received scan info size: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("timestamp: " + result[i].timestamp); + } +}); +``` + +## WifiScanInfo + +Defines WLAN hotspot information. + +| 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.| +| securityType | WifiSecurityType | Read-only| WLAN encryption type.| +| rssi | number | Read-only| Signal strength (in dBm) of the hotspot.| +| band | number | Read-only| Frequency band of the WLAN AP.| +| frequency | number | Read-only| Frequency of the WLAN AP.| +| timestamp | number | Read-only| Timestamp.| diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md new file mode 100644 index 0000000000000000000000000000000000000000..375db98333a6932c3dcde8cce453c5e3f4ef6baa --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -0,0 +1,2309 @@ +# Window + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import window from '@ohos.window'; +``` + +## Required Permissions + +ohos.permission.SYSTEM\_FLOAT\_WINDOW + +## SystemBarProperties + +Describes the properties of the status bar and navigation bar. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

statusBarColor

+

string

+

Yes

+

Yes

+

Color of the status bar. The color is a hexadecimal value, for example, #00FF00 or #FF00FF00.

+

isStatusBarLightIcon7+

+

boolean

+

Yes

+

Yes

+

Whether any icon on the status bar is highlighted.

+

navigationBarColor

+

string

+

Yes

+

Yes

+

Color of the navigation bar. The color is a hexadecimal value, for example, #00FF00 or #FF00FF00.

+

isNavigationBarLightIcon7+

+

boolean

+

Yes

+

Yes

+

Whether any icon on the navigation bar is highlighted.

+
+ +## Rect7+ + +Describes a rectangle. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

left

+

number

+

Yes

+

Yes

+

Left boundary of the rectangle.

+

top

+

number

+

Yes

+

Yes

+

Top boundary of the rectangle.

+

width

+

number

+

Yes

+

Yes

+

Width of the rectangle.

+

height

+

number

+

Yes

+

Yes

+

Height of the rectangle.

+
+ +## AvoidArea7+ + +Describes the area where the window cannot be displayed. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

leftRect

+

Rect

+

Yes

+

Yes

+

Rectangle on the left of the screen.

+

topRect

+

Rect

+

Yes

+

Yes

+

Rectangle at the top of the screen.

+

rightRect

+

Rect

+

Yes

+

Yes

+

Rectangle on the right of the screen.

+

bottomRect

+

Rect

+

Yes

+

Yes

+

Rectangle at the bottom of the screen.

+
+ +## Size7+ + +Describes the window size. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

width

+

number

+

Yes

+

Yes

+

Window width.

+

height

+

number

+

Yes

+

Yes

+

Window height.

+
+ +## WindowProperties + +Describes the window properties. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

windowRect7+

+

Rect

+

Yes

+

No

+

Window size.

+

type7+

+

WindowType

+

Yes

+

No

+

Window type.

+

brightness

+

number

+

Yes

+

Yes

+

Screen brightness. The value ranges from 0 to 1. The value 1 indicates the maximum brightness.

+

isTransparent7+

+

boolean

+

Yes

+

Yes

+

Whether the window is transparent. The default value is false.

+

isFullScreen

+

boolean

+

Yes

+

Yes

+

Whether the window is displayed in full screen mode. The default value is false.

+

isKeepScreenOn

+

boolean

+

Yes

+

Yes

+

Whether the screen is always on. The default value is false.

+

dimBehindValue7+

+

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.

+

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

+

Yes

+

Whether the window can gain focus. The default value is true.

+

touchable7+

+

boolean

+

Yes

+

Yes

+

Whether the window is touchable. The default value is true.

+

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.

+
+ +## SplitScreenBoundsInfo7+ + +Describes information about the split-screen boundary. + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

splitMode7+

+

number

+

Split-screen mode.

+

primaryBounds

+

Rect

+

Primary window boundary information, which is in the format of a Rect instance.

+

secondaryBounds

+

Rect

+

Secondary window boundary information, which is in the format of a Rect instance.

+
+ +## window.getTopWindow + +getTopWindow\(callback: AsyncCallback\): void + +Obtains a **Window** instance. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Window>

+

Yes

+

Callback used to return the current Window object.

+
+ +- Example + + ``` + window.getTopWindow((err, data) => { + if (err) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); + windowClass = data; + }); + ``` + + +## window.create7+ + +create\(id: string, type: WindowType, callback: AsyncCallback\): void + +Creates a subwindow. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

id

+

string

+

Yes

+

Window ID.

+

type

+

WindowType

+

Yes

+

Window type.

+

callback

+

AsyncCallback<Window>

+

Yes

+

Callback used to return the current Window object.

+
+ +- Example + +``` + window.create("first", 1, (err, data) => { + windowClass = data; + if (err) { + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('SubWindow created. Data: ' + JSON.stringify(data)) + windowClass.resetSize(500, 1000); + windowClass.setOutsideTouchable(true); + windowClass.loadContent("pages/index/index", (err, data) => { + }); +}) +``` + +## window.find7+ + +find\(id: string, callback: AsyncCallback\): void + +Finds a subwindow. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

id

+

string

+

Yes

+

Window ID.

+

callback

+

AsyncCallback<Window>

+

Yes

+

Callback used to return the current Window object.

+
+ +- Example + + ``` + window.find("first", (err, data) => { + if (err) { + console.error('Failed to find the subWindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('SubWindow found. Data: ' + JSON.stringify(data)) + windowClass = data; + }) + ``` + + +## window.getAbilityWindowMode7+ + +getAbilityWindowMode\(callback: AsyncCallback\): void + +Obtains the mode of this window. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<WindowMode>

+

Yes

+

Callback used to return the window mode.

+
+ +- Example + + ``` + window.getAbilityWindowMode((err, data) => { + if (err) { + console.error(''Failed to obtain the window mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Window mode obtained. Data:' + JSON.stringify(data)) + + }); + ``` + + +## window.getSplitScreenBounds7+ + +getSplitScreenBounds\(splitRatio: SplitRatio, callback: AsyncCallback\): void + +Obtains the position and area of multiple windows in split-screen mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

splitRatio

+

SplitRatio

+

Yes

+

Screen split ratio. The default ratio is 1:1. The value 1 indicates the ratio 1:2, and the value 2 indicates the ratio 2:1.

+

callback

+

AsyncCallback<SplitScreenBoundsInfo>

+

Yes

+

Callback used to return a SplitScreenBoundsInfo object that contains the split-screen boundary information.

+
+ +- Example + + ``` + var splitRatio = '1:1'; + window.getSplitScreenBounds(splitRatio, (err, data) => { + if (err) { + console.error('Failed to obtain the split-screen boundary information. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Split-screen boundary information obtained. Data: ' + JSON.stringify(data)) + + }); + ``` + + +## window.isFloatingAbilityWindowVisible7+ + +isFloatingAbilityWindowVisible\(callback:AsyncCallback\): void + +Checks whether the floating window is visible. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to indicate whether the floating window is visible.

+
+ +- Example + + ``` + window.isFloatingAbilityWindowVisible( (err, data) => { + if (err) { + console.error('Failed to check whether the floating window is visible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking whether the floating window is visible. Data:' + JSON.stringify(data)) + + }); + ``` + + +## window.setSplitBarVisibility7+ + +setSplitBarVisibility\(isVisibility: boolean, callback: AsyncCallback\): void + +Sets whether the split-screen divider is visible. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Description

+

isVisibility

+

boolean

+

Whether to display the divider. The value true means to display the divider, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Callback used to return the execution result.

+
+ +- Example + + ``` + var isVisibility = false; + window.setSplitBarVisibility(isVisibility , (err, data) => { + if (err) { + console.error('Failed to set the divider to be invisible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the divider to be invisible. Data:' + JSON.stringify(data)) + }); + ``` + + +## WindowType7+ + +Window type. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

TYPE_APP

+

0

+

Application window.

+

TYPE_SYSTEM_ALERT

+

1

+

System pop-up window.

+
+ +## AvoidAreaType7+ + +Describes the type of the area where the window cannot be displayed. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

TYPE_SYSTEM

+

0

+

Default area of the system.

+

TYPE_CUTOUT

+

1

+

Notch.

+
+ +## WindowMode7+ + +Describes the window mode of an application. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

UNDEFINED

+

1

+

The window mode is not defined by the application.

+

FULLSCREEN

+

2

+

The application is displayed in full screen.

+

PRIMARY

+

3

+

The application is displayed in the primary window in split-screen mode.

+

SECONDARY

+

4

+

The application is displayed in the secondary window in split-screen mode.

+

FLOATING

+

5

+

The application is displayed in a floating window.

+
+ +## splitMode7+ + +Describes the split-screen mode. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

VERTICAL

+

0

+

Vertical split-screen mode.

+

HORIZONTAL

+

1

+

Horizontal split-screen mode.

+
+ +## Window + +In the following API examples, you must use [getTopWindow\(\)](#section39061940191) to obtain a **Window** instance and then call the corresponding methods based on this instance. + +## setBrightness + +setBrightness\(brightness:number, callback: AsyncCallback\): void + +Sets the brightness for this window. + +- 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 invoked to return the result.

+
+ +- Example + + ``` + var brightness = 10; + windowClass.setBrightness(brightness, (err, data) => { + if (err) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setBackgroundColor + +setBackgroundColor\(color: string, callback: AsyncCallback\): void + +Sets the background color for this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

color

+

string

+

Yes

+

Background color to set. The color is a hexadecimal value, for example, #00FF00 or #FF00FF00.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var color = '#00ff33'; + windowClass.setBackgroundColor(color, (err, data) => { + if (err) { + console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setTransparent7+ + +setTransparent\(isTransparent: boolean, callback: AsyncCallback\): void + +Sets whether this window is transparent. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isTransparent

+

boolean

+

Yes

+

Whether the window is transparent.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isTransparent = true; + windowClass.setTransparent(isTransparent, (err, data) => { + if (err) { + console.error('Failed to set the window to be transparent. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be transparent. Data: ' + JSON.stringify(data)) + }); + ``` + + +## setFullScreen + +setFullScreen\(isFullScreen: boolean, callback: AsyncCallback\): void + +Sets whether to enable the full-screen mode for this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isFullScreen

+

boolean

+

Yes

+

Whether to enable the full-screen mode.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isFullScreen = true; + windowClass.setFullScreen(isFullScreen, (err, data) => { + if (err) { + console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setKeepScreenOn + +setKeepScreenOn\(isKeepScreenOn: boolean, callback: AsyncCallback\): void + +Sets whether to keep the screen always on. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isKeepScreenOn

+

boolean

+

Yes

+

Whether to keep the screen always on.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isKeepScreenOn = true; + windowClass.setKeepScreenOn(isKeepScreenOn, (err, data) => { + if (err) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setDimBehind7+ + +setDimBehind\(dimBehindValue: number, callback: AsyncCallback\): void + +Sets the dimness of the window that is not on top. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

dimBehindValue

+

number

+

Yes

+

Dimness of the window to set. The value ranges from 0 to 1. The value 1 indicates the dimmest.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.setDimBehind(0.5, (err, data) => { + if (err) { + console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the dimness. Data:' + JSON.stringify(data)); + }); + ``` + + +## setLayoutFullScreen7+ + +setLayoutFullScreen\(isLayoutFullScreen: boolean, callback: AsyncCallback\): void + +Sets whether the window layout is in full-screen mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isLayoutFullScreen

+

boolean

+

Yes

+

Whether the window layout is in full-screen mode.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isLayoutFullScreen= true; + windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { + if (err) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window layout to full-screen mode. Data:' + JSON.stringify(data)); + }); + ``` + + +## setFocusable7+ + +setFocusable\(isFocusable: boolean, callback: AsyncCallback\): void + +Sets whether this window can gain focus. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isFocusable

+

boolean

+

Yes

+

Whether the window can gain focus.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isFocusable= true; + windowClass.setFocusable(isFocusable, (err, data) => { + if (err) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setTouchable7+ + +setTouchable\(isTouchable: boolean, callback: AsyncCallback\): void + +Sets whether this window is touchable. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isTouchable

+

boolean

+

Yes

+

Whether the window is touchable.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isTouchable = true; + windowClass.setTouchable(isTouchable, (err, data) => { + if (err) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be touchable. Data:' + JSON.stringify(data)); + + }); + ``` + + +## setPrivacyMode7+ + +setPrivacyMode\(isPrivacyMode: boolean, callback: AsyncCallback\): void + +Sets whether this window is in privacy mode. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

isPrivacyMode

+

boolean

+

Yes

+

Whether the window is in privacy mode.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var isPrivacyMode = true; + windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { + if (err) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to privacy mode. Data:' + JSON.stringify(data)); + + }); + ``` + + +## setSystemBarEnable7+ + +setSystemBarEnable\(names: Array, callback: AsyncCallback\): void + +Sets whether to display the status bar and navigation bar in this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

names

+

Array

+

Yes

+

Whether to display the status bar and navigation bar. For example, to display the status bar and navigation bar, set this parameter to ["status", "navigation"].

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var names = ["status", "navigation"]; + windowClass.setSystemBarEnable(names, (err, data) => { + if (err) { + console.error('Failed to set the system bar to be visible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar to be visible. Data: ' + JSON.stringify(data)); + }); + ``` + + +## setSystemBarProperties + +setSystemBarProperties\(systemBarProperties: SystemBarProperties, callback: AsyncCallback\): void + +Sets the properties of the status bar and navigation bar in this window. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

SystemBarProperties

+

SystemBarProperties

+

Yes

+

Properties of the status bar and navigation bar to set.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + var SystemBarProperties={ + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // The following properties are supported since API version 7. + isStatusBarLightIcon: true, + isNavigationBarLightIcon:false + }; + windowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { + if (err) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); + }); + ``` + + +## getProperties + +getProperties\(callback: AsyncCallback\): void + +Obtains the properties of this window. This method uses an asynchronous callback to return the window properties. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<WindowProperties>

+

Yes

+

Callback used to return the window properties.

+
+ +- Example + + ``` + windowClass.getProperties((err, data) => { + if (err) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); + }); + ``` + + +## getAvoidArea7+ + +getAvoidArea\(type: AvoidAreaType, callback: AsyncCallback\): void + +Obtains the area where this window cannot be displayed, for example, the system bar area and notch area. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

AvoidAreaType

+

Yes

+

Type of the area. TYPE_SYSTEM indicates the default area of the system. TYPE_CUTOUT indicates the notch area.

+

callback

+

AsyncCallback<AvoidArea>

+

Yes

+

Callback used to return the area.

+
+ +- Example + + ``` + var type = window.AvoidAreaType.TYPE_SYSTEM; + windowClass.getAvoidArea(type, (err, data) => { + if (err) { + console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); + }); + ``` + + +## moveTo7+ + +moveTo\(x: number, y: number, callback: AsyncCallback\): void + +Moves this window. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

x

+

number

+

Yes

+

Distance that the window moves along the x-axis. A positive value indicates that the window moves to the right.

+

y

+

number

+

Yes

+

Distance that the window moves along the y-axis. A positive value indicates that the window moves downwards.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.moveTo(300, 300, (err, data)=>{ + if (err) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Window moved. Data:' + JSON.stringify(data)); + + }); + ``` + + +## resetSize7+ + +resetSize\(width: number, height: number, callback: AsyncCallback\): void + +Changes the size of this window. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

width

+

number

+

Yes

+

New width of the window.

+

height

+

number

+

Yes

+

New height of the window.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.resetSize(500, 1000, (err, data) => { + if (err) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Window size changed. Data:' + JSON.stringify(data)); + }); + ``` + + +## loadContent7+ + +loadContent\(path: string, callback: AsyncCallback\): void + +Loads content to the subwindow. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Path of the page to which the content will be loaded.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.loadContent("pages/page2/page2", (err, data) => { + if (err) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content. Data:' + JSON.stringify(data)); + }); + ``` + + +## hide7+ + +hide \(callback: AsyncCallback\): void + +Hides the subwindow. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.hide((err, data) => { + if (err) { + console.error('Failed to hide the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Subwindow hidden. Data:' + JSON.stringify(data)) + }) + ``` + + +## show7+ + +show\(callback: AsyncCallback\): void + +Shows the subwindow. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.show((err, data) => { + if (err) { + console.error('Failed to show the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the subwindow. Data: ' + JSON.stringify(data)) + }) + ``` + + +## isShowing7+ + +isShowing\(callback: AsyncCallback\): void + +Checks whether the subwindow is displayed. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<boolean>

+

Yes

+

Callback used to indicate whether the subwindow is displayed.

+
+ +- Example + + ``` + windowClass.isShowing((err, data) => { + if (err) { + console.error('Failed to check whether the subwindow is showing. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking whether the subwindow is showing. Cause:' + JSON.stringify(data)) + }) + ``` + + +## destroy7+ + +destroy\(callback: AsyncCallback\): void + +Destroys the subwindow. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.destroy((err, data) => { + if (err) { + console.error('Failed to destroy the subwindow. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the subwindow. Data:' + JSON.stringify(data)) + }) + ``` + + +## setOutsideTouchable7+ + +setOutsideTouchable\(touchable: boolean, callback: AsyncCallback\): void; + +Sets whether the area outside the subwindow is touchable. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

touchable

+

boolean

+

Yes

+

Whether the area outside the subwindow is touchable. The value true means that such an area is touchable, and false means the opposite.

+

callback

+

AsyncCallback<void>

+

Yes

+

Callback invoked to return the result.

+
+ +- Example + + ``` + windowClass.setOutsideTouchable(true, (err, data) => { + if (err) { + console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)) + }) + ``` + + +## on\('keyboardHeightChange'\) + +on\(type: string, callback: AsyncCallback\): void + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>This method is deprecated since API version 7. + +Enables listening for keyboard height changes. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type. Set it to keyboardHeightChange, which indicates listening for keyboard height changes.

+

callback

+

AsyncCallback<number>

+

Yes

+

Callback used to return the keyboard height.

+
+ +- Example + + ``` + var type= 'keyboardHeightChange'; + windowClass.on(type, (err, data) => { + if (err) { + console.error('Failed to enable the listener for keyboard height changes. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); + }); + ``` + + +## off\('keyboardHeightChange'\) + +off\(type: string, callback?: AsyncCallback\): void + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>This method is deprecated since API version 7. + +Disables listening for keyboard height changes. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listener type. Set it to keyboardHeightChange, which indicates a listener for keyboard height changes.

+

callback

+

AsyncCallback<number>

+

No

+

Callback used to return the keyboard height.

+
+ +- Example + + ``` + var type= 'keyboardHeightChange'; + windowClass.off(type); + ``` + + +## on\('keyboardHeightChange'|'windowSizeChange'7+|'systemAvoidAreaChange'7+\) + +on\(type: string, callback: Callback\): void; + +Enables listening. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type.

+
  • keyboardHeightChange: listening for keyboard height changes.
  • windowSizeChange7+: listening for window size changes.
  • systemAvoidAreaChange7+: listening for changes to the area where the window cannot be displayed.
+

callback

+

Callback<AvoidArea | Size | number>

+

Yes

+

Callback used to return the information.

+
+ +- Example + + ``` + var type = 'windowSizeChange'; + windowClass.on(type, (data) => { + console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data)); + }); + ``` + + +## off\('keyboardHeightChange'|'windowSizeChange'7+|'systemAvoidAreaChange'7+\) + +off\(type: string, callback?: Callback\): void; + +Disables listening. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Listening type.

+
  • keyboardHeightChange: listening for keyboard height changes.
  • windowSizeChange7+: listening for window size changes.
  • systemAvoidAreaChange7+: listening for changes to the area where the window cannot be displayed.
+

callback

+

Callback<AvoidArea | Size | number>

+

No

+

Callback used to return the information.

+
+ +- Example + + ``` + var type = 'windowSizeChange'; + windowClass.off(type); + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md new file mode 100644 index 0000000000000000000000000000000000000000..ff388df2f05e45d5831d4d72102bdfd6a04ae854 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -0,0 +1,1228 @@ +# Worker Startup + +>![](../../public_sys-resources/icon-note.gif) **NOTE:** +>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +``` +import worker from '@ohos.worker'; +``` + +## Required Permissions + +None + +## Attributes + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

parentPort

+

DedicatedWorkerGlobalScope

+

Yes

+

Yes

+

Object of the worker thread used to communicate with the host thread.

+
+ +## WorkerOptions + +Provides options that can be set for the worker to create. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

type

+

"classic"

+

Yes

+

Yes

+

Mode in which the worker executes the script.

+

name

+

string

+

Yes

+

Yes

+

Name of the worker.

+
+ +## Worker + +Before using the following methods, you must construct a worker instance. The **worker** class inherits from [EventTarget](#section256019311465). + +### constructor + +constructor\(scriptURL: string, options?: WorkerOptions\) + +A constructor used to create a worker instance. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

scriptURL

+

string

+

Yes

+

URL of the script to be executed by the worker. The script is stored in the workers directory, which is in the same directory as the pages directory of the new DevEco Studio project. If the workers directory does not exist, you need to create it.

+

options

+

WorkerOptions

+

No

+

Options that can be set for the worker.

+
+ +- Return values + + + + + + + + + + +

Name

+

Description

+

worker

+

Returns the worker instance created; returns undefined if the worker instance fails to be created.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js", {name:"first worker"}); + ``` + + +### postMessage + +postMessage\(message: Object, options?: PostMessageOptions\): void + +Sends a message to the worker thread. The data is transferred using the structured clone algorithm. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

Object

+

Yes

+

Data to be sent to the worker.

+

options

+

PostMessageOptions

+

No

+

ArrayBuffer instances that can be transferred. The transferList array cannot contain null.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js"); + worker.postMessage("hello world"); + + const worker = new worker.Worker("workers/worker.js"); + var buffer = new ArrayBuffer(8); + worker.postMessage(buffer, [buffer]); + ``` + + +### on + +on\(type: string, listener: EventListener\): void + +Adds an event listener to the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event to listen for.

+

listener

+

EventListener

+

Yes

+

Callback to invoke when an event of the specified type occurs.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.on("alert", (e)=>{ + console.log("alert listener callback"); + }) + ``` + + +### once + +once\(type: string, listener: EventListener\): void + +Adds an event listener to the worker and removes the event listener automatically after it is invoked once. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event to listen for.

+

listener

+

EventListener

+

Yes

+

Callback to invoke when an event of the specified type occurs.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js"); + worker.once("alert", (e)=>{ + console.log("alert listener callback"); + }) + ``` + + +### off + +off\(type: string, listener?: EventListener\): void + +Removes an event listener for the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event for which the event listener is removed.

+

listener

+

EventListener

+

No

+

Callback of the event listener to remove.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js"); + worker.off("alert"); + ``` + + +### terminate + +terminate\(\): void + +Terminates the worker thread to stop the worker from receiving messages. + +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.terminate() + ``` + + +### onexit + +onexit?: \(code: number\) =\> void + +Defines the event handler to be called when the worker exits. The handler is executed in the host thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

code

+

number

+

No

+

Code indicating the worker exit state.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.onexit = function(e) { + console.log("onexit") + } + ``` + + +### onerror + +onerror?: \(err: ErrorEvent\) =\> void + +Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

err

+

ErrorEvent

+

No

+

Error data.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.onerror = function(e) { + console.log("onerror") + } + ``` + + +### onmessage + +onmessage?: \(event: MessageEvent\) =\> void + +Defines the event handler to be called when the host thread receives a message created by itself and sent by the worker through the **parentPort.postMessage**. The event handler is executed in the host thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

MessageEvent

+

No

+

Message received.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.onmessage = function(e) { + console.log("onerror") + } + ``` + + +### onmessageerror + +onmessageerror?: \(event: MessageEvent\) =\> void + +Defines the event handler to be called when the worker receives a message that cannot be serialized. The event handler is executed in the host thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

MessageEvent

+

No

+

Error data.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.onmessageerror= function(e) { + console.log("onmessageerror") + } + ``` + + +## EventTarget + +### addEventListener + +addEventListener\(type: string, listener: EventListener\): void + +Adds an event listener to the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event to listen for.

+

listener

+

EventListener

+

Yes

+

Callback to invoke when an event of the specified type occurs.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); + }) + ``` + + +### removeEventListener + +removeEventListener\(type: string, callback?: EventListener\): void + +Removes an event listener for the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

type

+

string

+

Yes

+

Type of the event for which the event listener is removed.

+

callback

+

EventListener

+

No

+

Callback of the event listener to remove.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.removeEventListener("alert") + ``` + + +### dispatchEvent + +dispatchEvent\(event: Event\): boolean + +Dispatches the event defined for the worker. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

Event

+

Yes

+

Event to dispatch.

+
+ +- Return values + + + + + + + + + + +

Name

+

Description

+

boolean

+

Returns true if the event is dispatched successfully; returns false otherwise.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.dispatchEvent({type:"alert"}) + ``` + + +### removeAllListener + +removeAllListener\(\): void + +Removes all event listeners for the worker. + +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.removeAllListener({type:"alert"}) + ``` + + +## DedicatedWorkerGlobalScope + +Implements communication between the worker thread and the host thread. The **postMessage** API is used to send messages to the host thread, and the **close** API is used to terminate the worker thread. The **DedicatedWorkerGlobalScope** class inherits from [WorkerGlobalScope](#section12882825611). + +### postMessage + +postMessage\(message: Object, options?: PostMessageOptions\): void + +Sends a message to the host thread from the worker. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

message

+

Object

+

Yes

+

Data to be sent to the worker.

+

options

+

PostMessageOptions

+

No

+

ArrayBuffer instances that can be transferred. The transferList array cannot contain null.

+
+ +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.postMessage("hello world") + worker.onmessage = function(e) { + console.log("receive data from worker.js") + } + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort; + parentPort.onmessage = function(e){ + parentPort.postMessage("receive data from main.js") + } + ``` + + +### close + +close\(\): void + +Closes the worker thread to stop the worker from receiving messages. + +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort; + parentPort.onmessage = function(e) { + parentPort.close() + } + ``` + + +### onmessage + +onmessage?: \(event: MessageEvent\) =\> void + +Defines the event handler to be called when the worker thread receives a message sent by the host thread through **worker.postMessage**. The event handler is executed in the worker thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

MessageEvent

+

No

+

Message received.

+
+ +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + worker.postMessage("hello world") + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort; + parentPort.onmessage = function(e) { + console.log("receive main.js message") + } + ``` + + +### onmessageerror + +onmessageerror?: \(event: MessageEvent\) =\> void + +Defines the event handler to be called when the worker receives a message that cannot be deserialized. The event handler is executed in the worker thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

event

+

MessageEvent

+

No

+

Error data.

+
+ +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort; + parentPort.onmessageerror= function(e) { + console.log("worker.js onmessageerror") + } + ``` + + +## PostMessageOptions + +Specifies the object whose ownership needs to be transferred during data transfer. The object must be **ArrayBuffer**. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

transfer

+

Object[]

+

Yes

+

Yes

+

ArrayBuffer array used to transfer the ownership.

+
+ +## Event + +Defines the event. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

type

+

string

+

Yes

+

No

+

Type of the event.

+

timeStamp

+

number

+

Yes

+

No

+

Timestamp (accurate to millisecond) when the event is created.

+
+ +## EventListener + +Implements event listening. + +### \(evt: Event\): void | Promise + +Specifies the callback to invoke. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

evt

+

Event

+

Yes

+

Event class for the callback to invoke.

+
+ +- Return values + + + + + + + + + + +

Name

+

Description

+

void | Promise<void>

+

Returns no value or returns a Promise.

+
+ +- Example + + ``` + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js"); + worker.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); + }) + ``` + + +## ErrorEvent + +Provides detailed information about the exception occurred during worker execution. The **ErrorEvent** class inherits from [Event](#section1674694018507). + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

message

+

string

+

Yes

+

No

+

Information about the exception.

+

filename

+

string

+

Yes

+

No

+

File where the exception is located.

+

lineno

+

number

+

Yes

+

No

+

Number of the line where the exception is located.

+

colno

+

number

+

Yes

+

No

+

Number of the column where the exception is located.

+

error

+

Object

+

Yes

+

No

+

Type of the exception.

+
+ +## MessageEvent + +Holds the data transferred between worker threads. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

data

+

T

+

Yes

+

No

+

Data transferred between threads.

+
+ +## WorkerGlobalScope + +Defines the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#section256019311465). + +### Attributes + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

name

+

string

+

Yes

+

No

+

Worker name specified when there is a new worker.

+

self

+

WorkerGlobalScope & typeof globalThis

+

Yes

+

No

+

WorkerGlobalScope.

+
+ +### onerror + +onerror?: \(ev: ErrorEvent\) =\> void + +Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

ev

+

ErrorEvent

+

No

+

Error data.

+
+ +- Example + + ``` + // main.js + import worker from '@ohos.worker'; + const worker = new worker.Worker("workers/worker.js") + + // worker.js + import worker from "@ohos.worker"; + const parentPort = worker.parentPort + parentPort.onerror = function(e){ + console.log("worker.js onerror") + } + ``` + + diff --git a/en/application-dev/reference/apis/page-routing.md b/en/application-dev/reference/apis/page-routing.md deleted file mode 100644 index 690e16d583d9421555e0d8a9305dd7ef1ef53f17..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/page-routing.md +++ /dev/null @@ -1,306 +0,0 @@ -# Page Routing - -> **NOTICE:** ->Page routing APIs can be invoked only after page rendering is complete. Do not call the APIs in **onInit** and **onReady** when the page is still in the rendering phase. - -## Module to Import - -``` -import router from '@system.router'; -``` - -## Permission List - -None - -## router.push\(OBJECT\) - -Navigates to a specified page in the application based on the page URL and parameters. - -- Parameter - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

uri

-

string

-

Yes

-

URI of the destination page, in either of the following formats:

-
  • Absolute path of the page. The value is available in the pages list in the config.json file, for example:
    • pages/index/index
    • pages/detail/detail
    -
  • Particular path. If the URI is a slash (/), the home page is displayed.
-

params

-

Object

-

No

-

Data that needs to be passed to the destination page during navigation. After the destination page is displayed, it can use the passed data, for example, this.data1 (data1 is a key in params). If there is the same key (for example, data1) on the destination page, the passed data1 value will overwrite the original value on the destination page.

-
- -- Example - - ``` - // Example code for the current page - export default { - pushPage() { - router.push({ - uri: 'pages/routerpage2/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] - }, - }, - }); - } - } - // Example code for the routerpage2 page - export default { - data: { - data1: 'default', - data2: { - data3: [1, 2, 3] - } - }, - onInit() { - console.info('showData1:' + this.data1); - console.info('showData3:' + this.data2.data3); - } - } - ``` - - >**NOTE:** - >The page routing stack supports a maximum of 32 pages. - - -## router.replace\(OBJECT\) - -Replaces the current page with another one in the application and destroys the current page. - -- Parameter - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

uri

-

string

-

Yes

-

URI of the destination page, in either of the following formats:

-
  • Absolute path of the page. The value is available in the pages list in the config.json file, for example:
    • pages/index/index
    • pages/detail/detail
    -
  • Particular path. If the URI is a slash (/), the home page is displayed.
-

params

-

Object

-

No

-

Data that needs to be passed to the destination page during navigation. After the destination page is displayed, it can use the passed data, for example, this.data1 (data1 is a key in params). If there is the same key (for example, data1) on the destination page, the passed data1 value will overwrite the original value on the destination page.

-
- -- Example - - ``` - // Example code for the current page - export default { - replacePage() { - router.replace({ - uri: 'pages/detail/detail', - params: { - data1: 'message', - }, - }); - } - } - // Example code for the detail page - export default { - data: { - data1: 'default' - }, - onInit() { - console.info('showData1:' + this.data1) - } - } - ``` - - -## router.back\(OBJECT\) - -Returns to the previous page or a specified page. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

uri

-

string

-

No

-

URI of the page to return to. If the specified page does not exist in the page stack, the app does not respond. If this parameter is not set, the app returns to the previous page.

-
- -- Example - - ``` - // index page - router.push({ - uri: 'pages/detail/detail', - }); - - // detail page - router.push({ - uri: 'pages/mall/mall', - }); - - // Navigate from the mall page to the detail page through router.back(). - router.back(); - // Navigate from the detail page to the index page through router.back(). - router.back(); - // Return to the detail page through router.back(). - router.back({uri:'pages/detail/detail'}); - ``` - - > **NOTE:** - >In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. - - -## router.clear\(\) - -Clears all historical pages and retains only the current page at the top of the stack. - -- Parameter - - N/A - -- Example - - ``` - router.clear(); - ``` - - -## router.getLength\(\) - -Obtains the number of pages in the current stack. - -- Returned Value - - - - - - - - - - -

Type

-

Description

-

string

-

Number of pages in the stack. The maximum value is 32.

-
- -- Example - - ``` - var size = router.getLength(); - console.log('pages stack size = ' + size); - ``` - - -## router.getState\(\) - -Obtains information about the current page state. - -- Returned Value - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Description

-

index

-

number

-

Index of the current page in the stack.

-
NOTE:

The index starts from 1 from the bottom to the top of the stack.

-
-

name

-

string

-

Name of the current page, that is, the file name.

-

path

-

string

-

Path of the current page.

-
- -- Example - - ``` - var page = router.getState(); - console.log('current index = ' + page.index); - console.log('current name = ' + page.name); - console.log('current path = ' + page.path); - ``` - - diff --git a/en/application-dev/reference/apis/pop-up-window.md b/en/application-dev/reference/apis/pop-up-window.md deleted file mode 100644 index 0e3c9242de01a535c680a28425412686287ec915..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/pop-up-window.md +++ /dev/null @@ -1,188 +0,0 @@ -# Pop-up Window - -## Module to Import - -``` -import prompt from '@system.prompt'; -``` - -## Permission List - -None - -## prompt.showToast\(OBJECT\) - -Displays the toast dialog box. - -- Parameter - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

message

-

string

-

Yes

-

Text to display.

-

duration

-

number

-

No

-

Duration of the toast dialog box. The default value is 1500. The recommended value ranges from 1500 ms to 10000 ms.

-
NOTE:

A value less than 1500 is automatically changed to 1500. The maximum value is 10000 ms.

-
-

[bottom]5+

-

<length>

-

No

-

Distance between the dialog border and the bottom of the screen.

-
- -- Example - - ``` - prompt.showToast({ - message: 'Message Info', - duration: 2000, - }); - ``` - - -## prompt.showDialog\(OBJECT\) - -Displays the dialog box. - -- Parameter - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

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.

-

success

-

Function

-

No

-

Called when the dialog box is displayed. For the return value, see the value that will be returned when the dialog box is displayed.

-

cancel

-

Function

-

No

-

Called when the operation is cancelled.

-

complete

-

Function

-

No

-

Called when the dialog box is closed.

-
- - The following value will be returned when the dialog box is displayed. - - - - - - - - - - - - -

Parameter

-

Type

-

Description

-

index

-

number

-

Index of the selected button in the buttons array

-
- -- Example - - ``` - prompt.showDialog({ - title: 'Title Info', - message: 'Message Info', - buttons: [ - { - text: 'button', - color: '#666666', - }, - ], - success: function(data) { - console.log('dialog success callback,click button : ' + data.index); - }, - cancel: function() { - console.log('dialog cancel callback'); - }, - }); - ``` - - diff --git a/en/application-dev/reference/apis/resource-management.md b/en/application-dev/reference/apis/resource-management.md deleted file mode 100644 index 9c6ed7962d665a010e068e22531c2876d567a7b0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/resource-management.md +++ /dev/null @@ -1,1079 +0,0 @@ -# Resource Management - - -## Imported Modules - -``` -import resmgr from '@ohos.resmgr'; -``` - -## Permissions - -None. - -## Methods - -## getResourceManager - -Obtains the **ResourceManager** object of the current application. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<ResourceManager>

-

Yes

-

Indicates the callback containing the ResourceManager object.

-
- -**Return Values** - -None. - -**Example** - -``` -resmgr.getResourceManager((error, mgr) => { - // callback - mgr.getString(0x1000000, (error, value) => { - if (error != null) { - console.log(value); - } else { - console.log(value); - } - }); - - // promise - mgr.getString(0x1000000).then(value => { - console.log(value); - }).catch(error => { - console.log("getstring promise " + error); - }); -} - -``` - -## getResourceManager - -Obtains the **ResourceManager** object of the specified application. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

bundleName

-

string

-

Yes

-

Indicates the bundle name of the specified application.

-

callback

-

AsyncCallback<ResourceManager>

-

Yes

-

Indicates the callback containing the ResourceManager object.

-
- -**Return Values** - -None. - -**Example** - -``` -resmgr.getResourceManager("com.example.myapplication", (error, mgr) => { -} -``` - -## getResourceManager - -Obtains the **ResourceManager** object of the current application. - -**Parameters** - -None. - -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<ResourceManager>

-

Indicates that the ResourceManager object is returned in Promise mode.

-
- -**Example** - -``` -resmgr.getResourceManager().then(mgr => { - // callback - mgr.getString(0x1000000, (error, value) => { - if (error != null) { - console.log(value); - } else { - console.log(value); - } - }); - - // promise - mgr.getString(0x1000000).then(value => { - console.log(value); - }).catch(error => { - console.log("getstring promise " + error); - }); -}).catch(error => { - -}); -``` - -## getResourceManager - -Obtains the **ResourceManager** object of the specified application. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

bundleName

-

string

-

Yes

-

Indicates the bundle name of the specified application.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<ResourceManager>

-

Indicates that the ResourceManager object is returned in Promise mode.

-
- -**Example** - -``` -resmgr.getResourceManager("com.example.myapplication").then(mgr => { - -}).catch(error => { - -}); -``` - -## Enum - -## Direction - -Enumerates screen directions - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

DIRECTION_VERTICAL

-

0

-

Indicates the vertical direction.

-

DIRECTION_HORIZONTAL

-

1

-

Indicates the horizontal direction.

-
- -## DeviceType - -Enumerates device types. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

DEVICE_TYPE_PHONE

-

0x00

-

Indicates a phone.

-

DEVICE_TYPE_TABLET

-

0x01

-

Indicates a tablet.

-

DEVICE_TYPE_CAR

-

0x02

-

Indicates a head unit.

-

DEVICE_TYPE_PC

-

0x03

-

Indicates a PC.

-

DEVICE_TYPE_TV

-

0x04

-

Indicates a smart TV.

-

DEVICE_TYPE_WEARABLE

-

0x06

-

Indicates a wearable.

-
- -## ScreenDensity - -Enumerates screen density types. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Default Value

-

Description

-

SCREEN_SDPI

-

120

-

Indicates small screen density.

-

SCREEN_MDPI

-

160

-

Indicates medium screen density.

-

SCREEN_LDPI

-

240

-

Indicates large screen density.

-

SCREEN_XLDPI

-

320

-

Indicates extra-large screen density.

-

SCREEN_XXLDPI

-

480

-

Indicates extra-extra-large screen density.

-

SCREEN_XXXLDPI

-

640

-

Indicates extra-extra-extra-large screen density.

-
- -## Appendix - -## AsyncCallback - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter Type

-

Mandatory

-

Description

-

error

-

Error

-

No

-

Returns an error if an exception is thrown during execution; returns an empty value otherwise.

-

data

-

T

-

No

-

Returns a T object if the execution is successful; returns an empty value otherwise.

-
- -## Configuration - -Provides the device configuration. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter Type

-

Readable

-

Writable

-

Description

-

direction

-

Direction

-

Yes

-

No

-

Indicates the screen direction of the current device.

-

locale

-

string

-

Yes

-

No

-

Indicates the current system language, for example, zh-Hans-CN.

-
- -## DeviceCapability - -Provides the device capability. - -### Attributes - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Parameter Type

-

Readable

-

Writable

-

Description

-

screenDensity

-

ScreenDensity

-

Yes

-

No

-

Indicates the screen density of the current device.

-

deviceType

-

DeviceType

-

Yes

-

No

-

Indicates the type of the current device.

-
- -## ResourceManager - -Provides the capability of accessing application resources. - -### getString - -Obtains the character string corresponding to a specified resource ID in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

callback

-

AsyncCallback<string>

-

Yes

-

Indicates the asynchronous callback used to return the obtained character string.

-
- -**Return Values** - -None. - -### getString - -Obtains string resources associated with a specified resource ID in Promise mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Indicates the character string corresponding to the resource ID.

-
- -### getStringArray - -Obtains the array of character strings corresponding to a specified resource ID in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

callback

-

AsyncCallback<Array<string>>

-

Yes

-

Indicates the asynchronous callback used to return the obtained array of character strings.

-
- -**Return Values** - -None. - -### getStringArray - -Obtains the array of character strings corresponding to a specified resource ID in Promise mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<Array<string>>

-

Indicates the array of character strings corresponding to the specified resource ID.

-
- -### getMedia - -Obtains the content of the media file corresponding to a specified resource ID in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

callback

-

AsyncCallback<Array<Uint8Array>>

-

Yes

-

Indicates the asynchronous callback used to return the obtained media file content.

-
- -**Return Values** - -None. - -### getMedia - -Obtains the content of the media file corresponding to a specified resource ID in Promise mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<Array<Uint8Array>>

-

Indicates the content of the media file corresponding to the specified resource ID.

-
- -### getMediaBase64 - -Obtains the Base64 code of the image resource corresponding to the specified resource ID in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

callback

-

AsyncCallback<string>

-

Yes

-

Indicates the asynchronous callback used to return the obtained Base64 code of the image resource.

-
- -**Return Values** - -None. - -### getMediaBase64 - -Obtains the Base64 code of the image resource corresponding to the specified resource ID in Promise mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Indicates the Base64 code of the image resource corresponding to the specified resource ID.

-
- -### getConfiguration - -Obtains the device configuration in callback mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<Configuration>

-

Yes

-

Indicates the asynchronous callback used to return the obtained device configuration.

-
- -**Return Values** - -None. - -### getConfiguration - -Obtains the device configuration in Promise mode. - -**Parameters** - -None. - -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<Configuration>

-

Indicates the device configuration.

-
- -### getDeviceCapability - -Obtains the device capability in callback mode. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

AsyncCallback<DeviceCapability>

-

Yes

-

Indicates the asynchronous callback used to return the obtained device capability.

-
- -**Return Values** - -None. - -### getDeviceCapability - -Obtains the device capability in Promise mode. - -**Parameters** - -None. - -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<DeviceCapability>

-

Indicates the device capability.

-
- -**Return Values** - -None. - -### getPluralString - -Obtains the singular-plural character string represented by the ID string corresponding to the specified number in callback mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

num:

-

number

-

Yes

-

Indicates the number.

-

callback

-

AsyncCallback<string>

-

Yes

-

Indicates the asynchronous callback used to return the singular-plural character string represented by the ID string corresponding to the specified number.

-
- -**Return Values** - -None. - -### getPluralString - -Obtains the singular-plural character string represented by the ID string corresponding to the specified number in Promise mode. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

resId

-

number

-

Yes

-

Indicates the resource ID.

-

num:

-

number

-

Yes

-

Indicates the number.

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Indicates the singular-plural character string represented by the ID string corresponding to the specified number.

-
- diff --git a/en/application-dev/reference/apis/screen-brightness.md b/en/application-dev/reference/apis/screen-brightness.md deleted file mode 100644 index f1ad6c94e78b6e2ede49f8ca2e53767c7ca841d3..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/screen-brightness.md +++ /dev/null @@ -1,51 +0,0 @@ -# Screen Brightness - -## Modules to Import - -``` -import brightness from '@ohos.brightness.d.ts'. -``` - -## Functions - -## setValue\(value: number\) - -Sets the screen brightness. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

value

-

number

-

Yes

-

Brightness value, ranging from 0 to 255

-
- -**Return Values** - -None - -- Example - - ``` - import brightness from '@ohos.brightness.d.ts' - brightness.setValue(128); - ``` - - diff --git a/en/application-dev/reference/apis/system-attribute.md b/en/application-dev/reference/apis/system-attribute.md deleted file mode 100644 index d4d681bb83bad7eeb937e9b1404457b94f90ddbb..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/system-attribute.md +++ /dev/null @@ -1,462 +0,0 @@ -# System Attribute - -## Modules to Import - -``` -import parameter from '@ohos.systemparameter' -``` - -## Required Permissions - -None - -## Functions - -## getSync\(key: string, def?: string\) - -Gets the value of the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

No

-

Default value

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

string

-

System attribute value. If the specified key does not exist, the default value is returned. If no default value has been set, an empty string will be returned.

-
- -**Example** - -``` -try { - var info = parameter.getSync("test.parameter.key"); - console.log(JSON.stringify(info)); -}catch(e){ - console.log("getSync unexpected error: " + e); -} -``` - -## get\(key: string, callback: AsyncCallback\) - -Gets the value of the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

callback

-

AsyncCallback<string>

-

Yes

-

Callback function

-
- -**Return Values** - -None. - -**Example** - -``` -try { - parameter.get("test.parameter.key", function (err, data) { - if (err == undefined) { - console.log("get test.parameter.key value success:" + data) - } else { - console.log(" get test.parameter.key value err:" + err.code) - }}); -}catch(e){ - console.log("get unexpected error: " + e); -} -``` - -## get\(key: string, def: string, callback: AsyncCallback\) - -Gets the value of the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

Yes

-

Default value

-

callback

-

AsyncCallback<string>

-

Yes

-

Callback function

-
- -**Return Values** - -None. - -**Example** - -``` -try { - parameter.get("test.parameter.key", "default", function (err, data) { - if (err == undefined) { - console.log("get test.parameter.key value success:" + data) - } else { - console.log(" get test.parameter.key value err:" + err.code) - } - }); -}catch(e){ - console.log("get unexpected error:" + e) -} -``` - -## get\(key: string, def?: string\) - -Gets the value of the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

No

-

Default value

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Promise, which is used to obtain the result asynchronously

-
- -**Example** - -``` -try { - var p = parameter.get("test.parameter.key"); - p.then(function (value) { - console.log("get test.parameter.key success: " + value); - }).catch(function (err) { - console.log("get test.parameter.key error: " + err.code); - }); -}catch(e){ - console.log("get unexpected error: " + e); -} -``` - -## setSync\(key: string, value: string\) - -Sets a value for the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

value

-

string

-

Yes

-

System attribute value to set

-
- -**Return Values** - -None. - -**Example** - -``` -try { - parameter.setSync("test.parameter.key", "default"); -}catch(e){ - console.log("set unexpected error: " + e); -} -``` - -## set\(key: string, value: string, callback: AsyncCallback\) - -Sets a value for the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

Yes

-

Default value

-

callback

-

AsyncCallback<void>

-

Yes

-

Callback function.

-
- -**Return Values** - -None. - -**Example** - -``` -try { - parameter.set("test.parameter.key", "testValue", function (err, data) { - if (err == undefined) { - console.log("set test.parameter.key value success :" + data) - } else { - console.log("set test.parameter.key value err:" + err.code) - }}); -}catch(e){ - console.log("set unexpected error: " + e); -} -``` - -## set\(key: string, def?: string\) - -Sets a value for the attribute with the specified key. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

key

-

string

-

Yes

-

Key of the system attribute

-

def

-

string

-

No

-

Default value

-
- -**Return Values** - - - - - - - - - - -

Type

-

Description

-

Promise<string>

-

Promise, which is used to obtain the result asynchronously

-
- -**Example** - -``` -try { - var p = para.set("test.parameter.key", "testValue"); - p.then(function (value) { - console.log("set test.parameter.key success: " + value); - }).catch(function (err) { - console.log(" set test.parameter.key error: " + err.code); - }); -}catch(e){ - console.log("set unexpected error: " + e); -} -``` - diff --git a/en/application-dev/reference/apis/timer.md b/en/application-dev/reference/apis/timer.md deleted file mode 100644 index 59a115942ccbf825c05be15a63ba998df4b27bdb..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/timer.md +++ /dev/null @@ -1,210 +0,0 @@ -# Timer - -## Module to Import - -None - -## Permission List - -None - -## setTimeout\(handler\[, delay\[, ...args\]\]\) - -Sets a timer for the system to call a function after the timer goes off. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

handler

-

Function

-

Yes

-

Function to be called after the timer goes off.

-

delay

-

number

-

No

-

Number of milliseconds delayed before the execution. If this parameter is left empty, the default value 0 is used, which means that the execution starts immediately or as soon as possible.

-

...args

-

Array<any>

-

No

-

Additional parameter to pass to the handler after the timer goes off.

-
- -- Return Value - - **timeoutID**: timer ID - -- Example - - ``` - var timeoutID = setTimeout(function() { - console.log('delay 1s'); - }, 1000); - ``` - - -## clearTimeout\(timeoutID\) - -Cancels the timer created via **setTimeout\(\)**. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

timeoutID

-

number

-

Yes

-

ID of the timer to cancel, which is returned by setTimeout()

-
- -- Example - - ``` - var timeoutID = setTimeout(function() { - console.log('do after 1s delay.'); - }, 1000); - - clearTimeout(timeoutID); - ``` - - -## setInterval\(handler\[, delay\[, ...args\]\]\) - -Sets a repeating timer for the system to repeatedly call a function at a fixed interval. - -- Parameters - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

handler

-

Function

-

Yes

-

Function to be called repeatedly

-

delay

-

number

-

No

-

Number of milliseconds delayed before the execution

-

...args

-

Array<any>

-

No

-

Additional parameter to pass to the handler after the timer goes off

-
- -- Return Value - - **intervalID**: ID of the repeating timer - -- Example - - ``` - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - ``` - - -## clearInterval\(intervalID\) - -Cancels the repeating timer set via **setInterval\(\)**. - -- Parameter - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

intervalID

-

number

-

Yes

-

ID of the repeating timer to cancel, which is returned by setInterval().

-
- -- Example - - ``` - var intervalID = setInterval(function() { - console.log('do very 1s.'); - }, 1000); - - clearInterval(intervalID); - ``` - - diff --git a/en/application-dev/reference/apis/updater.md b/en/application-dev/reference/apis/updater.md deleted file mode 100644 index fbb89fa2c86d4a548c66f72f1357cd15aac32e01..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/updater.md +++ /dev/null @@ -1,313 +0,0 @@ -# Updater - -## Modules to Import - -``` -import client from 'libupdateclient.z.so' -``` - -## Required Permissions - -None - -## updater.getNewVersionInfo\(\) - -Obtains new version information. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

Function

-

No

-

AsyncCallback<NewVersionInfo>

-
- -**Return Values** - - - - - - - - - - - - -

Name

-

Type

-

Description

-

info

-

NewVersionInfo

-

New version information

-
- -**Example** - -``` -updater.getNewVersionInfo(info => { -console.log("getNewVersionInfo success " + info.status); -console.log(`info versionName = ` + info.result[0].versionName); -console.log(`info versionCode = ` + info.result[0].versionCode); -console.log(`info verifyInfo = ` + info.result[0].verifyInfo); -)}; -``` - -## updater.checkNewVersion\(\) - -Checks for a new version. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

Function

-

No

-

AsyncCallback<NewVersionInfo>

-
- -**Return Values** - - - - - - - - - - - - -

Name

-

Type

-

Description

-

info

-

NewVersionInfo

-

New version information

-
- -**Example** - -``` -updater.checkNewVersion(info => { -console.log("checkNewVersion success " + info.status); -console.log(`info versionName = ` + info.result[0].versionName); -console.log(`info versionCode = ` + info.result[0].versionCode); -console.log(`info verifyInfo = ` + info.result[0].verifyInfo); -)}; -``` - -## updater.download\(\) - -Downloads the new version and displays the download process. - -**Parameters** - -None - -**Return Values** - -None - -**Example** - -``` -updater.on("downloadProgress", progress => { -console.log("downloadProgress on" + progress); -console.log(`downloadProgress status: ` + progress.status); -console.log(`downloadProgress percent: ` + progress.percent); -)}; -updater.download(); -``` - -## updater.upgrade\(\) - -Starts an update. - -**Parameters** - -None - -**Return Values** - -None - -**Example** - -``` -updater.on("upgradeProgress", progress => { -console.log("downloadProgress on" + progress); -console.log(`downloadProgress status: ` + progress.status); -console.log(`downloadProgress percent: ` + progress.percent); -)}; -updater.upgrade(); -``` - -## updater.setUpdatePolicy\(\) - -Sets the update policy. - -**Parameters** - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

policy

-

UpdatePolicy

-

Yes

-

Update policy

-

callback

-

Function

-

Yes

-

AsyncCallback<number>

-
- -**Return Values** - - - - - - - - - - - - -

Name

-

Type

-

Description

-

result

-

number

-
  
- -**Example** - -``` -// Set the update policy. -let policy = { -autoDownload: false, -autoDownloadNet: true, -mode: 2, -autoUpgradeInterval: [ 2, 3 ], -autoUpgradeCondition: 2 -} -updater.setUpdatePolicy(policy, function(result) { -console.log("setUpdatePolicy ", result) -} -); -``` - -## updater.getUpdatePolicy\(\) - -Checks the update policy. - -**Parameters** - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

callback

-

Function

-

Yes

-

AsyncCallback<UpdatePolicy>

-
- -**Return Values** - - - - - - - - - - - - -

Name

-

Type

-

Description

-

policy

-

UpdatePolicy

-

Update policy

-
- -**Example** - -``` -updater.getUpdatePolicy(policy => { -console.log("getUpdatePolicy success", policy) -}); -``` - diff --git a/en/application-dev/reference/arkui-js/figures/aliceblue.png b/en/application-dev/reference/arkui-js/figures/aliceblue.png deleted file mode 100644 index 378000d344e90ab4db41869a4612daf6b60d66ab..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/aliceblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/antiquewhite.png b/en/application-dev/reference/arkui-js/figures/antiquewhite.png deleted file mode 100644 index 8e195633945b3387c46a7d295862351d4ff1fc64..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/antiquewhite.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/aqua.png b/en/application-dev/reference/arkui-js/figures/aqua.png deleted file mode 100644 index 3e6aaacfe1c26157294e6dedfeaa1488aeed12a3..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/aqua.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/aquamarine.png b/en/application-dev/reference/arkui-js/figures/aquamarine.png deleted file mode 100644 index c25a692065d473ccf9f5b6d36254787e2497fad6..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/aquamarine.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/azure.png b/en/application-dev/reference/arkui-js/figures/azure.png deleted file mode 100644 index 2e7cec00f9d186d76ff5cb12d47811084217cc1c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/azure.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/beige.png b/en/application-dev/reference/arkui-js/figures/beige.png deleted file mode 100644 index 21f20a4220aabf9449c707291633e7b3723fe378..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/beige.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/bisque.png b/en/application-dev/reference/arkui-js/figures/bisque.png deleted file mode 100644 index 7983d590a2c617c6cad68c90af6b12aa17518810..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/bisque.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/blanchedalmond.png b/en/application-dev/reference/arkui-js/figures/blanchedalmond.png deleted file mode 100644 index 04bcf099edface801be6074a33ff33a980c9b606..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/blanchedalmond.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/blueviolet.png b/en/application-dev/reference/arkui-js/figures/blueviolet.png deleted file mode 100644 index ca1edf2219980ab9c8533b9fda3219521c50533d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/blueviolet.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/burlywood.png b/en/application-dev/reference/arkui-js/figures/burlywood.png deleted file mode 100644 index 0d53a47b7eace81d5c7da88c59fee61e30c89681..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/burlywood.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/cadetblue.png b/en/application-dev/reference/arkui-js/figures/cadetblue.png deleted file mode 100644 index a59bc9cdb0f75ad79e4714d3593216021369c862..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/cadetblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/chartreuse.png b/en/application-dev/reference/arkui-js/figures/chartreuse.png deleted file mode 100644 index 3026d3c195598159232b4b1f08e9f198f4b4fa2c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/chartreuse.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/chocolate.png b/en/application-dev/reference/arkui-js/figures/chocolate.png deleted file mode 100644 index 02d5f4e31b020ea9f64e36a7b7cd50299cf3d7f2..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/chocolate.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/coral.png b/en/application-dev/reference/arkui-js/figures/coral.png deleted file mode 100644 index 8442c9b2258c79ee6b6a3d5963df5b792bbb1a16..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/coral.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/cornflowerblue.png b/en/application-dev/reference/arkui-js/figures/cornflowerblue.png deleted file mode 100644 index 3621ef6876dbd1103487aed8ff190e6a0204ffde..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/cornflowerblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/cornsilk.png b/en/application-dev/reference/arkui-js/figures/cornsilk.png deleted file mode 100644 index bf38fe45eaf254939b88b9d2a66635408060acf7..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/cornsilk.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/crimson.png b/en/application-dev/reference/arkui-js/figures/crimson.png deleted file mode 100644 index bca655617699ef8dc1265bf692a3170c7effe15b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/crimson.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/cyan.png b/en/application-dev/reference/arkui-js/figures/cyan.png deleted file mode 100644 index 3e6aaacfe1c26157294e6dedfeaa1488aeed12a3..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/cyan.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkblue.png b/en/application-dev/reference/arkui-js/figures/darkblue.png deleted file mode 100644 index b234a769d1a9f1f30c4d2127160cf067e9f71ad6..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkcyan.png b/en/application-dev/reference/arkui-js/figures/darkcyan.png deleted file mode 100644 index b780eb08852e8916ec6ff1a401ea6946c8d727cf..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkcyan.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkgoldenrod.png b/en/application-dev/reference/arkui-js/figures/darkgoldenrod.png deleted file mode 100644 index 26f2f228b47b8acb8adcddc3abf9156d6c29364e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkgoldenrod.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkgray.png b/en/application-dev/reference/arkui-js/figures/darkgray.png deleted file mode 100644 index f1abe2afcb7902557ac3c4f58abfdf333af03121..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkgray.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkgreen.png b/en/application-dev/reference/arkui-js/figures/darkgreen.png deleted file mode 100644 index 4c4c304b67c398f32c5fff516cdde377ca39c73d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkgreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkgrey.png b/en/application-dev/reference/arkui-js/figures/darkgrey.png deleted file mode 100644 index f1abe2afcb7902557ac3c4f58abfdf333af03121..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkgrey.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkkhaki.png b/en/application-dev/reference/arkui-js/figures/darkkhaki.png deleted file mode 100644 index 12085848c0f6472d53f7e6504c1924ea6f5a44c1..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkkhaki.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkmagenta.png b/en/application-dev/reference/arkui-js/figures/darkmagenta.png deleted file mode 100644 index 9ed54c6c5c5186fb43f24dab24f7689ae0d14a12..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkmagenta.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkolivegreen.png b/en/application-dev/reference/arkui-js/figures/darkolivegreen.png deleted file mode 100644 index 53081e06f458cfc1772de30f669180333b8d783d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkolivegreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkorange.png b/en/application-dev/reference/arkui-js/figures/darkorange.png deleted file mode 100644 index 6064f64867e3aca621244e1e6fdb16d3ab2ed748..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkorange.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkorchid.png b/en/application-dev/reference/arkui-js/figures/darkorchid.png deleted file mode 100644 index 6315d4654d04dd6b9b295fa1f8b37e8c550b17cf..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkorchid.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkred.png b/en/application-dev/reference/arkui-js/figures/darkred.png deleted file mode 100644 index c33d763d18f5108bf0eedba19c662d05af397ee9..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkred.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darksalmon.png b/en/application-dev/reference/arkui-js/figures/darksalmon.png deleted file mode 100644 index 57594c6855d4cdf1b37cc3e5354374c9dae0823b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darksalmon.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkseagreen.png b/en/application-dev/reference/arkui-js/figures/darkseagreen.png deleted file mode 100644 index 454b1796715794d51e2a1a4649bfafa1bfde80f0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkseagreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkslateblue.png b/en/application-dev/reference/arkui-js/figures/darkslateblue.png deleted file mode 100644 index 7dfc7ee8793298d19c939369ba980abd547982ff..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkslateblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkslategray.png b/en/application-dev/reference/arkui-js/figures/darkslategray.png deleted file mode 100644 index 5e23c304c4911dc0ef487dfeb8d7820aea5fb44b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkslategray.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkslategrey.png b/en/application-dev/reference/arkui-js/figures/darkslategrey.png deleted file mode 100644 index 5e23c304c4911dc0ef487dfeb8d7820aea5fb44b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkslategrey.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkturquoise.png b/en/application-dev/reference/arkui-js/figures/darkturquoise.png deleted file mode 100644 index 4e41450db5d70f6d10d6d7bf59daba33085c177e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkturquoise.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/darkviolet.png b/en/application-dev/reference/arkui-js/figures/darkviolet.png deleted file mode 100644 index 6f085565bd8c64d44bf58ce0969557515ec7ab97..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/darkviolet.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/deeppink.png b/en/application-dev/reference/arkui-js/figures/deeppink.png deleted file mode 100644 index 6348bb2b6ee281976f7d58159e4c33db29f542ad..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/deeppink.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/deepskyblue.png b/en/application-dev/reference/arkui-js/figures/deepskyblue.png deleted file mode 100644 index 0ac129028e67b43fcae8e3d5c1a539cc45ba6d21..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/deepskyblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/dimgray.png b/en/application-dev/reference/arkui-js/figures/dimgray.png deleted file mode 100644 index 1072a50f468dda3c90c889c31424b7c290eb1a13..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/dimgray.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/dimgrey.png b/en/application-dev/reference/arkui-js/figures/dimgrey.png deleted file mode 100644 index 1072a50f468dda3c90c889c31424b7c290eb1a13..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/dimgrey.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/dodgerblue.png b/en/application-dev/reference/arkui-js/figures/dodgerblue.png deleted file mode 100644 index fe422eecde9ec9f1fcac762bd81a23b3fa3abde7..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/dodgerblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/firebrick.png b/en/application-dev/reference/arkui-js/figures/firebrick.png deleted file mode 100644 index af32ecea68c1cef693bcfa379af5ac28f66c1e14..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/firebrick.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/floralwhite.png b/en/application-dev/reference/arkui-js/figures/floralwhite.png deleted file mode 100644 index 5ee9f7e893611dce988b8aa7ccfe3fab4b9d912f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/floralwhite.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/forestgreen.png b/en/application-dev/reference/arkui-js/figures/forestgreen.png deleted file mode 100644 index 7cfd4846ca697424582edbfed23ed93ef9e98138..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/forestgreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/fuchsia.png b/en/application-dev/reference/arkui-js/figures/fuchsia.png deleted file mode 100644 index 6823cbc9203b07abae455b4ee5c7692878c4be72..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/fuchsia.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/gainsboro.png b/en/application-dev/reference/arkui-js/figures/gainsboro.png deleted file mode 100644 index d1d37504e15eb6fccd6b1c8e985d37fcc8ba9875..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/gainsboro.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/ghostwhite.png b/en/application-dev/reference/arkui-js/figures/ghostwhite.png deleted file mode 100644 index 45467f3e6fc0866b6da0521911bdb5e7d740df29..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/ghostwhite.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/gold.png b/en/application-dev/reference/arkui-js/figures/gold.png deleted file mode 100644 index 91a276a7dffb4d98c507e9af6afa1912cca1fed2..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/gold.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/goldenrod.png b/en/application-dev/reference/arkui-js/figures/goldenrod.png deleted file mode 100644 index 04ab7decab16cb7341665c2a67e8d5655a7eed6a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/goldenrod.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/greenyellow.png b/en/application-dev/reference/arkui-js/figures/greenyellow.png deleted file mode 100644 index c89f746719790333bce2bde8c5b8d86102fdfc33..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/greenyellow.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/grey.png b/en/application-dev/reference/arkui-js/figures/grey.png deleted file mode 100644 index dfcb0c5e259b3f8d7375c21712249c1e847edd67..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/grey.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/honeydew.png b/en/application-dev/reference/arkui-js/figures/honeydew.png deleted file mode 100644 index 51fb00e10bb5c167506ddfae1689b58e368df340..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/honeydew.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/hotpink.png b/en/application-dev/reference/arkui-js/figures/hotpink.png deleted file mode 100644 index cbc1d312680f479e8c443476ea39eaf1e8a16e55..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/hotpink.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/indianred.png b/en/application-dev/reference/arkui-js/figures/indianred.png deleted file mode 100644 index 069f570291be858a1768b75719a4a6adbd1bdef8..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/indianred.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/indigo.png b/en/application-dev/reference/arkui-js/figures/indigo.png deleted file mode 100644 index db83d39f98583ee653ee39b0237eb55961e539c7..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/indigo.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/ivory.png b/en/application-dev/reference/arkui-js/figures/ivory.png deleted file mode 100644 index ff0aa71de78cb461a6602398ee915c677efdf3d4..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/ivory.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/khaki.png b/en/application-dev/reference/arkui-js/figures/khaki.png deleted file mode 100644 index 3fca22c329e9dc9ef73eee20757eac4ce7386842..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/khaki.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lavender.png b/en/application-dev/reference/arkui-js/figures/lavender.png deleted file mode 100644 index 44e4d991524bd0ef88a0dd10f204e022dd9d0621..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lavender.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lavenderblush.png b/en/application-dev/reference/arkui-js/figures/lavenderblush.png deleted file mode 100644 index 5b22707e37ec772dc08a961e557a937862210167..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lavenderblush.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lawngreen.png b/en/application-dev/reference/arkui-js/figures/lawngreen.png deleted file mode 100644 index 41be1a646e14511b5d177d11a7bce10deaee5bc9..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lawngreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lemonchiffon.png b/en/application-dev/reference/arkui-js/figures/lemonchiffon.png deleted file mode 100644 index d77ed21418dc3035feb9f9c8e15815e577d71a90..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lemonchiffon.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightblue.png b/en/application-dev/reference/arkui-js/figures/lightblue.png deleted file mode 100644 index 7cc96f8f6364b93923f0a88b895fe6b151080932..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightcoral.png b/en/application-dev/reference/arkui-js/figures/lightcoral.png deleted file mode 100644 index 515185ab1b3cf9aaba1204760dae19ab3c112b42..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightcoral.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightcyan.png b/en/application-dev/reference/arkui-js/figures/lightcyan.png deleted file mode 100644 index 6f929d8ab35b708978d8053047cb56bec4fa83bc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightcyan.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightgoldenrodyellow.png b/en/application-dev/reference/arkui-js/figures/lightgoldenrodyellow.png deleted file mode 100644 index 1b0ed50716d897398c1e9a741e08ff5f1b9fd9de..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightgoldenrodyellow.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightgray.png b/en/application-dev/reference/arkui-js/figures/lightgray.png deleted file mode 100644 index 0a5eb251a8d731dc6a9d8b1f31f904c42fd372c3..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightgray.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightgreen.png b/en/application-dev/reference/arkui-js/figures/lightgreen.png deleted file mode 100644 index f89943fc98661a6d2b78b5659c41483308a0c54b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightgreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightpink.png b/en/application-dev/reference/arkui-js/figures/lightpink.png deleted file mode 100644 index 6eb2d41877c85cccfb918b042bc13c81c58ec191..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightpink.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightsalmon.png b/en/application-dev/reference/arkui-js/figures/lightsalmon.png deleted file mode 100644 index d87462d1cdc9410e91ee050a53d58e71d1c5f312..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightsalmon.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightseagreen.png b/en/application-dev/reference/arkui-js/figures/lightseagreen.png deleted file mode 100644 index e863d7a1c3b9c1ca08bd182dce43c55a4866d59b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightseagreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightskyblue.png b/en/application-dev/reference/arkui-js/figures/lightskyblue.png deleted file mode 100644 index daa035cea33b810571c18de67e4ac887eeb11850..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightskyblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightslategray.png b/en/application-dev/reference/arkui-js/figures/lightslategray.png deleted file mode 100644 index 2dadb92ce56793e2dd693bfa7d99b0c1168130dc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightslategray.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightslategrey.png b/en/application-dev/reference/arkui-js/figures/lightslategrey.png deleted file mode 100644 index 2dadb92ce56793e2dd693bfa7d99b0c1168130dc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightslategrey.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightsteelblue.png b/en/application-dev/reference/arkui-js/figures/lightsteelblue.png deleted file mode 100644 index ac0521001d2513fd69e48ce61e1d1128b9d3a6dd..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightsteelblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lightyellow.png b/en/application-dev/reference/arkui-js/figures/lightyellow.png deleted file mode 100644 index d1ca7dd07fe7812ec1f87bf748595174569a5672..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lightyellow.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/lime.png b/en/application-dev/reference/arkui-js/figures/lime.png deleted file mode 100644 index 481c833482d38c5f564127c8f412fe3c0275fd24..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/lime.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/limegreen.png b/en/application-dev/reference/arkui-js/figures/limegreen.png deleted file mode 100644 index 63a8c6adc29d340634ed06a1006a0fb56c991a9d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/limegreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/linen.png b/en/application-dev/reference/arkui-js/figures/linen.png deleted file mode 100644 index 486baf6be50982404fd1c68a5bc51db45c62046a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/linen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/magenta.png b/en/application-dev/reference/arkui-js/figures/magenta.png deleted file mode 100644 index 6823cbc9203b07abae455b4ee5c7692878c4be72..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/magenta.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/maroon.png b/en/application-dev/reference/arkui-js/figures/maroon.png deleted file mode 100644 index 1324b43b3f5b8dd0548cf2069c4c532c5284c445..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/maroon.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumaquamarine.png b/en/application-dev/reference/arkui-js/figures/mediumaquamarine.png deleted file mode 100644 index 800bf296338fd01962f16a8863c37bfe515ce3be..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumaquamarine.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumblue.png b/en/application-dev/reference/arkui-js/figures/mediumblue.png deleted file mode 100644 index c0df3f4f7d99f0b8c39995133c71d944bc07ea4b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumorchid.png b/en/application-dev/reference/arkui-js/figures/mediumorchid.png deleted file mode 100644 index 664d13c38389361e61a45870899e2a6f0bfc835f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumorchid.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumpurple.png b/en/application-dev/reference/arkui-js/figures/mediumpurple.png deleted file mode 100644 index 848454297b67eb73ab641424badc438433e24479..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumpurple.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumseagreen.png b/en/application-dev/reference/arkui-js/figures/mediumseagreen.png deleted file mode 100644 index 984e7a561e661ecefca8b60d5ac239b67f96c98c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumseagreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumslateblue.png b/en/application-dev/reference/arkui-js/figures/mediumslateblue.png deleted file mode 100644 index 39cf9d01563cf63bee003a47cd88258e860a0757..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumslateblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumspringgreen.png b/en/application-dev/reference/arkui-js/figures/mediumspringgreen.png deleted file mode 100644 index 56db1024a714f821528656c64e12520311bae8f5..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumspringgreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumturquoise.png b/en/application-dev/reference/arkui-js/figures/mediumturquoise.png deleted file mode 100644 index b3c353b6a872d3597b767f4c216b2d16bfc2139b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumturquoise.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mediumvioletred.png b/en/application-dev/reference/arkui-js/figures/mediumvioletred.png deleted file mode 100644 index 00767e63c899eec52c2c732e834bca8d26d348ce..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mediumvioletred.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/midnightblue.png b/en/application-dev/reference/arkui-js/figures/midnightblue.png deleted file mode 100644 index ac66614c0f277cd722b3d090cb10efb973152b0f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/midnightblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mintcream.png b/en/application-dev/reference/arkui-js/figures/mintcream.png deleted file mode 100644 index 64fdda07447707816e8a6238939169f58a4ce58f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mintcream.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/mistyrose.png b/en/application-dev/reference/arkui-js/figures/mistyrose.png deleted file mode 100644 index 6f5fe69b5a5a62b2d2b719b2be0a17a501363918..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/mistyrose.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/moccasin.png b/en/application-dev/reference/arkui-js/figures/moccasin.png deleted file mode 100644 index 115cb4c96382681743381aeba099549dc24c2ae5..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/moccasin.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/navajowhite.png b/en/application-dev/reference/arkui-js/figures/navajowhite.png deleted file mode 100644 index a68e61ab120651294310c5e3632ce22d71917a52..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/navajowhite.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/navy.png b/en/application-dev/reference/arkui-js/figures/navy.png deleted file mode 100644 index 4e41c2cd90ba17798448d70b493ccceb3ac960f0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/navy.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/oldlace.png b/en/application-dev/reference/arkui-js/figures/oldlace.png deleted file mode 100644 index ecf361e4c749446160da1e8a07169b21d99f362a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/oldlace.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/olive.png b/en/application-dev/reference/arkui-js/figures/olive.png deleted file mode 100644 index 0d386fef5c4fa9faf1b29c7667c7392db250f2eb..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/olive.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/olivedrab.png b/en/application-dev/reference/arkui-js/figures/olivedrab.png deleted file mode 100644 index 639f16f8aaf261176b3bc760c2eb616ad2f4aa28..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/olivedrab.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/orangered.png b/en/application-dev/reference/arkui-js/figures/orangered.png deleted file mode 100644 index e72165fdf1b24d80f0abde742ad3d848497c6ea7..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/orangered.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/orchid.png b/en/application-dev/reference/arkui-js/figures/orchid.png deleted file mode 100644 index 9114031e04fc28be59e8c9567c0fcfe81a9cc5cb..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/orchid.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/palegoldenrod.png b/en/application-dev/reference/arkui-js/figures/palegoldenrod.png deleted file mode 100644 index 131584c72c082f40e2b466e2706c86a05df375e0..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/palegoldenrod.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/palegreen.png b/en/application-dev/reference/arkui-js/figures/palegreen.png deleted file mode 100644 index 891d52276622fd51893634ce26e08bd56f62b782..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/palegreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/paleturquoise.png b/en/application-dev/reference/arkui-js/figures/paleturquoise.png deleted file mode 100644 index a618da21cf6c6d32066286e594921c0fc75b5dba..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/paleturquoise.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/palevioletred.png b/en/application-dev/reference/arkui-js/figures/palevioletred.png deleted file mode 100644 index c88212b6818d6d18c77ee497cfcafaf661a70d52..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/palevioletred.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/papayawhip.png b/en/application-dev/reference/arkui-js/figures/papayawhip.png deleted file mode 100644 index 4b1948de8581602c6c5879c03d68c14f06eccd00..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/papayawhip.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/peachpuff.png b/en/application-dev/reference/arkui-js/figures/peachpuff.png deleted file mode 100644 index 1821f9c40ad9d24dc10dc662ecbe7936c9e10633..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/peachpuff.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/peru.png b/en/application-dev/reference/arkui-js/figures/peru.png deleted file mode 100644 index 3ca3e045717379bb09fa8d13ea0d42019bf546f2..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/peru.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/plum.png b/en/application-dev/reference/arkui-js/figures/plum.png deleted file mode 100644 index 1e0bad2b2bfed2559e53a8bc21162e6163ec8434..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/plum.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/powderblue.png b/en/application-dev/reference/arkui-js/figures/powderblue.png deleted file mode 100644 index 8b3eec4e46f6a29dc47694940ceaef1cfa1314af..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/powderblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/purple.png b/en/application-dev/reference/arkui-js/figures/purple.png deleted file mode 100644 index 8bc3583f82d21c8bec0c70b2da36ed05723fd9a7..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/purple.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/rebeccapurple.png b/en/application-dev/reference/arkui-js/figures/rebeccapurple.png deleted file mode 100644 index 6a64534a0a867d44cf81c8a34c9981b5fbaf5faf..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/rebeccapurple.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/rosybrown.png b/en/application-dev/reference/arkui-js/figures/rosybrown.png deleted file mode 100644 index adca00e684afb79ff4f21313d0586025576a8be1..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/rosybrown.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/royalblue.png b/en/application-dev/reference/arkui-js/figures/royalblue.png deleted file mode 100644 index 69cb300d4bc8decee06c7fb64b03a24287865a8f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/royalblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/saddlebrown.png b/en/application-dev/reference/arkui-js/figures/saddlebrown.png deleted file mode 100644 index 5d0ae86ad14ff863511a10ecc1a85b273e826dfc..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/saddlebrown.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/salmon.png b/en/application-dev/reference/arkui-js/figures/salmon.png deleted file mode 100644 index b80a6c31cdb287c35965c7841aa97711d79b371c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/salmon.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/sandybrown.png b/en/application-dev/reference/arkui-js/figures/sandybrown.png deleted file mode 100644 index c952585d8032733700b57ce1a919d71ce9a4b58b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/sandybrown.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/seagreen.png b/en/application-dev/reference/arkui-js/figures/seagreen.png deleted file mode 100644 index 858c4187d3a2874f651adc09dcae9a32f8407d86..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/seagreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/seashell.png b/en/application-dev/reference/arkui-js/figures/seashell.png deleted file mode 100644 index c0b21ed6b44c2f756458137f931873f540c16e5f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/seashell.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/sienna.png b/en/application-dev/reference/arkui-js/figures/sienna.png deleted file mode 100644 index bdb02fdda28a155e2f622eeea2ff820144780e50..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/sienna.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/silver.png b/en/application-dev/reference/arkui-js/figures/silver.png deleted file mode 100644 index 0491d350277cd67d7774e3761164b9dd7038a117..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/silver.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/skyblue.png b/en/application-dev/reference/arkui-js/figures/skyblue.png deleted file mode 100644 index 1c4f9ae52153198f8690a1066fe66ba8c7bd1ee1..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/skyblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/slateblue.png b/en/application-dev/reference/arkui-js/figures/slateblue.png deleted file mode 100644 index 87915df37741dacfe9448bfebccf5a88d3ca2a76..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/slateblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/slategray-48.png b/en/application-dev/reference/arkui-js/figures/slategray-48.png deleted file mode 100644 index 6e4476c4791e37d4681f8e12313ae1cad0887c1b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/slategray-48.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/slategray.png b/en/application-dev/reference/arkui-js/figures/slategray.png deleted file mode 100644 index 6e4476c4791e37d4681f8e12313ae1cad0887c1b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/slategray.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/snow.png b/en/application-dev/reference/arkui-js/figures/snow.png deleted file mode 100644 index 283cf90b3828b36af6fb3a746e806f6715053310..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/snow.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/springgreen.png b/en/application-dev/reference/arkui-js/figures/springgreen.png deleted file mode 100644 index 93825b7fe53a0794751ee4aa3ca46300c404835e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/springgreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/steelblue.png b/en/application-dev/reference/arkui-js/figures/steelblue.png deleted file mode 100644 index a9aba5f67b94427168fade014542532431e28a2e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/steelblue.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/tan.png b/en/application-dev/reference/arkui-js/figures/tan.png deleted file mode 100644 index b162dbf0a6c890a03ea1aa0b28bdb454651b697c..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/tan.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/teal.png b/en/application-dev/reference/arkui-js/figures/teal.png deleted file mode 100644 index 93299fc38d761e5251673210c364f6825e319153..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/teal.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/thistle.png b/en/application-dev/reference/arkui-js/figures/thistle.png deleted file mode 100644 index d62fc7767f7b2e0e8d0d7fed57e30bdf6a6a332f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/thistle.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/tomato.png b/en/application-dev/reference/arkui-js/figures/tomato.png deleted file mode 100644 index 6d795f1618b1546c94266548069eccf9e9af2e01..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/tomato.png and /dev/null differ diff --git "a/en/application-dev/reference/arkui-js/figures/\345\215\241\347\211\207\350\275\254\345\234\272.gif" b/en/application-dev/reference/arkui-js/figures/transition.gif similarity index 100% rename from "en/application-dev/reference/arkui-js/figures/\345\215\241\347\211\207\350\275\254\345\234\272.gif" rename to en/application-dev/reference/arkui-js/figures/transition.gif diff --git a/en/application-dev/reference/arkui-js/figures/turquoise.png b/en/application-dev/reference/arkui-js/figures/turquoise.png deleted file mode 100644 index a33c4fce8448e2127b21e277437195ce0002766b..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/turquoise.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/violet.png b/en/application-dev/reference/arkui-js/figures/violet.png deleted file mode 100644 index e9a0799a203fdd7bd41fa5175585dc170a20156e..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/violet.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/wheat.png b/en/application-dev/reference/arkui-js/figures/wheat.png deleted file mode 100644 index 8a5c7039b580128e75299672dc5438151dcf3572..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/wheat.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/whitesmoke.png b/en/application-dev/reference/arkui-js/figures/whitesmoke.png deleted file mode 100644 index 6dc88e656c293c2e65939e4a793684488dfc81be..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/whitesmoke.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/figures/yellowgreen.png b/en/application-dev/reference/arkui-js/figures/yellowgreen.png deleted file mode 100644 index f89e20a55ba1e81f2cbda2bd0241edefadbe7149..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-js/figures/yellowgreen.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-js/js-components-common-events.md b/en/application-dev/reference/arkui-js/js-components-common-events.md index 85add526686aabc72fea09fe65629b89f916d8b5..8424b92f3b3b9735c03d8cc6d7f89f11b5ce64d6 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-events.md +++ b/en/application-dev/reference/arkui-js/js-components-common-events.md @@ -321,9 +321,16 @@ Different from private events, universal events can be bound to most components.

Touch force.

- +

identifier8+

+ +

number

+ +

Unique identifier of a touch point on the screen. The value remains unchanged across the events triggered by finger movement on the screen.

+ + + **Table 4** Attributes of the SwipeEvent object \(inherited from BaseEvent\) @@ -474,4 +481,3 @@ export default { } } ``` - diff --git a/en/application-dev/reference/arkui-js/js-components-common-transition.md b/en/application-dev/reference/arkui-js/js-components-common-transition.md index 6d00ab174a1922043a505b5d0d1933973a2d808b..55f2c7f3b7a2f8f0b83bfd3a0d89548bc5af7a44 100644 --- a/en/application-dev/reference/arkui-js/js-components-common-transition.md +++ b/en/application-dev/reference/arkui-js/js-components-common-transition.md @@ -5,6 +5,7 @@ **Table 1** Transition of shared elements + -

Name

Type

@@ -270,7 +271,7 @@ export default { } ``` -![](figures/卡片转场.gif) +![](figures/transition.gif) ## Page Transition Styles diff --git a/en/application-dev/reference/arkui-ts/figures/000000-49.png b/en/application-dev/reference/arkui-ts/figures/000000-49.png deleted file mode 100644 index 58293d5e874f2aa36ecaf7282ca9e4736318092f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/000000-49.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/blue-50.png b/en/application-dev/reference/arkui-ts/figures/blue-50.png deleted file mode 100644 index e370a44cf043fc34bd8891f57faad2cd2ca05707..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/blue-50.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/brown-51.png b/en/application-dev/reference/arkui-ts/figures/brown-51.png deleted file mode 100644 index 0d22570503febc7a7dcba0d1e870f49f32fe489a..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/brown-51.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/green-53.png b/en/application-dev/reference/arkui-ts/figures/green-53.png deleted file mode 100644 index bc28f5056c679e189543c8ad6fba67fb56db7655..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/green-53.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/grey-52.png b/en/application-dev/reference/arkui-ts/figures/grey-52.png deleted file mode 100644 index dfcb0c5e259b3f8d7375c21712249c1e847edd67..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/grey-52.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/orange-54.png b/en/application-dev/reference/arkui-ts/figures/orange-54.png deleted file mode 100644 index 9c43caf5fdfd466eafc37b793f509a6bde2b885d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/orange-54.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/pink-55.png b/en/application-dev/reference/arkui-ts/figures/pink-55.png deleted file mode 100644 index 5c5e360f249a2002ba68ad9b94bd7f66f5d6aab1..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/pink-55.png and /dev/null differ diff --git "a/en/application-dev/reference/arkui-ts/figures/\345\203\217\347\264\240\345\215\225\344\275\215.gif" b/en/application-dev/reference/arkui-ts/figures/pixel-units.gif similarity index 100% rename from "en/application-dev/reference/arkui-ts/figures/\345\203\217\347\264\240\345\215\225\344\275\215.gif" rename to en/application-dev/reference/arkui-ts/figures/pixel-units.gif diff --git a/en/application-dev/reference/arkui-ts/figures/red-56.png b/en/application-dev/reference/arkui-ts/figures/red-56.png deleted file mode 100644 index 309d1c46f8bc396df5eaed381a5ffa2f0389d602..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/red-56.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/white-57.png b/en/application-dev/reference/arkui-ts/figures/white-57.png deleted file mode 100644 index 56d32d4cd371c5374b133cb81c9c077aaf7b110d..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/white-57.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/yellow-58.png b/en/application-dev/reference/arkui-ts/figures/yellow-58.png deleted file mode 100644 index b54dbc2391d1a8f16312dd02dc3d65a35ea2626f..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/yellow-58.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/ts-pixel-units.md b/en/application-dev/reference/arkui-ts/ts-pixel-units.md index 5431d9bd6a2f49330ac9829155e2d90438631804..bf2e33a832aa658c8c632d58265f198cb5fcc6cb 100644 --- a/en/application-dev/reference/arkui-ts/ts-pixel-units.md +++ b/en/application-dev/reference/arkui-ts/ts-pixel-units.md @@ -121,5 +121,5 @@ struct Example { } ``` -![](figures/像素单位.gif) +![](figures/pixel-units.gif) diff --git a/en/application-dev/ui/ui-js-animate-attribute-style.md b/en/application-dev/ui/ui-js-animate-attribute-style.md index f5543107059e874743e97fb4ae482d62c31ca927..9afae8fdce62fe1e89180f004cf64d246dddec8c 100644 --- a/en/application-dev/ui/ui-js-animate-attribute-style.md +++ b/en/application-dev/ui/ui-js-animate-attribute-style.md @@ -1,6 +1,6 @@ # Attribute Style Animation -In [Keyframes](../js-reference/js-based-web-like-development-paradigm/js-components-common-methods.md#table1491078445), dynamically set the width and height of the parent component to scale the component. Set the **scale** attribute for child components to scale the parent and child components at the same time. Then, set the **opacity** attribute to display or hide parent and child components. +In [Keyframes](../reference/arkui-js/js-components-common-methods.md#table1491078445), dynamically set the width and height of the parent component to scale the component. Set the **scale** attribute for child components to scale the parent and child components at the same time. Then, set the **opacity** attribute to display or hide parent and child components. ``` diff --git a/en/application-dev/ui/ui-js-animate-dynamic-effects.md b/en/application-dev/ui/ui-js-animate-dynamic-effects.md index 2e3e2fd77c5e3fb76d716653f7d5253d39e16eed..a80f849b282d1fec713c62bd7347c3d4ac9a6e01 100644 --- a/en/application-dev/ui/ui-js-animate-dynamic-effects.md +++ b/en/application-dev/ui/ui-js-animate-dynamic-effects.md @@ -7,7 +7,7 @@ You can set the interpolator to implement the animation effect. For details, see ## Creating an Animation Object -Use **createAnimator** to create an animation object and set the animation attributes with the [options](../js-reference/js-based-web-like-development-paradigm/js-components-common-methods.md#table587915341817) parameter. +Use **createAnimator** to create an animation object and set the animation attributes with the [options](../reference/arkui-js/js-components-common-methods.md#table587915341817) parameter. ``` diff --git a/en/application-dev/ui/ui-ts-overview.md b/en/application-dev/ui/ui-ts-overview.md index 3644c112335dfd439132bd8678e11aa459941918..c86f7f50be7634106ea74bb90bc2904bdbf6f712 100644 --- a/en/application-dev/ui/ui-ts-overview.md +++ b/en/application-dev/ui/ui-ts-overview.md @@ -1,10 +1,10 @@ # Overview -The HUAWEI ArkUI that uses the TypeScript-based declarative development paradigm is a simplified, high-performance UI development framework for cross-device applications. +The TypeScript-based declarative development paradigm of ArkUI is a simplified, high-performance UI development framework for cross-device applications. ## Basic Capabilities -In the HUAWEI ArkUI that uses the TypeScript-based declarative development paradigm, the programming mode is closer to natural semantics. You can intuitively describe the UI without caring about how the framework implements UI drawing and rendering, leading to simplified and efficient development. The UI capabilities are provided from three dimensions: component, animation, and state management. It also provides system capability APIs to allow for effortless invocation of system capabilities. +In ArkUI that uses the TypeScript-based declarative development paradigm, the programming mode is closer to natural semantics. You can intuitively describe the UI without caring about how the framework implements UI drawing and rendering, leading to simplified and efficient development. The UI capabilities are provided from three dimensions: component, animation, and state management. It also provides system capability APIs to allow for effortless invocation of system capabilities. - **Out-of-the-box components** diff --git a/en/contribute/OpenHarmony-Log-guide.md b/en/contribute/OpenHarmony-Log-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..af4ba6c5756ae36cc8a16c580c21c4d66519e0dc --- /dev/null +++ b/en/contribute/OpenHarmony-Log-guide.md @@ -0,0 +1,236 @@ +# Logging Guide + +## Introduction +In OpenHarmony, HiLog is used to export logs to the log services. Logs record user operations and system running statuses. Logs are an important part of a system, and quality logs are a must for system development. + +Logging has a significant negative impact on system performance. Therefore, it is necessary to make logging reasonably simple. Do not log unnecessary information to overwhelm developers. + +## Log Level + +- **[Rule] Use the appropriate log level based on actual conditions.** + +**Note:** The log level must match the log content. The following log levels are available: + +FATAL: indicates that a program or functionality is about to crash and the fault cannot be rectified. + +ERROR: indicates a program or functional error that affects the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data. + +WARN: indicates a severe, unexpected fault that has little impact on users and can be rectified by the programs themselves or through simple operations. + +INFO: used to record key service process nodes and exceptions (for example, no network signal or login failure) that occur during service running. These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions. + +DEBUG: used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults. DEBUG logs are not recorded in official versions by default. They are available in debug versions or in official versions with the debug function enabled. + +## Log Content + +- **[Rule] Describe the log content in fluent English (grammatically correct and clear description with no typos).** + +**Note:** The log content must be clear and concise so that developers can know what happened by reading the log, instead of analyzing the related code. A syntax- and semantics-compliant log also helps the log analysis tool automatically parse the log. Example: + +A log recording "1234" is meaningless to anyone except the coder themselves. + +A log recording "Error happened" does not indicate where the error occurred or the cause of the error. Such a log is not helpful for fault locating. + +- **[Rule] Do not log privacy information.** + +**Note:** Privacy information, such as hardware serial numbers, personal accounts, passwords, and identities, should not be logged. The scope of the privacy information complies with national and regional policies. + +- **[Rule] Do not log service-irrelevant information.** + +**Note:** Do not log any information irrelevant to the service code, such as the issue number, requirement number, department name, developer name, employee ID, name abbreviation, weather, and mood. + +- **[Rule] Do not log repeated information.** + +**Note:** Do not print logs with the same content in different places. It would hinder developers in locating the code during fault locating. + +- **[Rule] Do not call service interface functions in logs.** + +**Note:** Logging should not affect the normal service process. Generally, the impact of log code on the service logic is ignored during fault locating or code walk-through. + +- **[Rule] Do not commit logs used during development and debugging to the code repository.** + +**Note:** To speed up fault locating, you may print a line of logs for each step in the code or print various variables (which may include privacy information). +You must delete these code lines before committing the final code to the code repository. + +- **[Recommendation] Display the log content in one line.** + +**Note:** A line usually contains about 100 characters. Try your best not to include more than 160 characters in a log. + +## When to Print + +- **[Rule] Do not print logs in the normal process of high-frequency code.** + +**Note:** Do not print logs for frequently called interface functions in big data processing, high-frequency software and hardware interrupt processing, protocol data stream processing, multimedia audio and video stream processing, display screen refresh processing, and other scenarios where the code keeps running as long as the system does not sleep. However, you can print logs in their error branches. Logs added during development and debugging must be cleared or disabled when code is committed to the code repository. + +- **[Rule] Restrict the logging frequency for logs that may be recorded repeatedly.** + +**Note:** If it is proved that some log records may occur multiple times, you are advised to restrict the logging frequency to avoid a large number of log copies with identical (or very similar) information. + +- **[Rule] Print logs for events that are unlikely to happen.** + +**Note:** According to Murphy's Law, anything that can go wrong will go wrong. Always print logs for points that are unlikely to happen. + +- **[Recommendation] Generate log strings during logging.** + +**Note:** Log strings should be generated as late as possible, best at the time when the log is printed. In this way, the strings will not be generated when the log function is disabled, therefore minimizing the system overhead. + +## Log Format + + +- **[Rule] Log events in the who-does-what format.** + +- **[Rule] Log status changes in the format of state\_name:s1->s2, reason:msg.** + +- **[Rule] Log parameter values in the format of name1=value1, name2=value2...**. + +- **[Rule] Log successful code execution using the statement "xxx successful".** + +- **[Rule] Log code execution failures using the statement "xxx failed. Please xxx." Include possible solutions in the logs.** + + Example: "Connection to the server failed. Please check network configuration." + +## Guide for Printing Common Logs + +### Process Logs + + +- **[Recommendation] Log key service process nodes, including the service start point, key condition branch, error processing point, and service end point.** + +### Database Logs + +- **[Recommendation] Log database operations and related information.** + +**Note:** Common database operations include +Create, Read, Update, Delete (CRUD). The initiator, type, and result (successful or failed) of each operation should be logged. However, the detailed content of the operation and operation result should not be logged to prevent user privacy leakage. The number of returned results can be logged. + +- **[Recommendation] Record the operation duration in database operation logs for performance-sensitive services.** + +**Note:** For performance-sensitive services, database operations (including reading and writing data) are key performance nodes, and the operation duration should be logged and used as a reference for performance profiling. + +- **[Recommendation] Log database job information.** + +**Note:** Log the job name, execution content, start time, end time, and execution result. + +### File Logs +- **[Recommendation] Log operations on files and related information.** + +**Note:** Common file operations include creating, opening, reading, writing, closing, and deleting files as well as obtaining file attributes. The initiator, type, and result of each operation should be logged. However, the file content should not be logged to prevent user privacy leakage or system vulnerability exposure. The system file name and file handle value can be logged, but the user file name should not. + +- **[Recommendation] Print only one log for batch file operations.** + +**Note:** For example, if files are deleted in batches, do not record a log for each file deletion. Instead, log the number of deleted files. If the directory where a deleted file is located is created by the system, log the directory name as well. + +### Key Object/Object Pool Logs + +**Note:** A key object/object pool may be a class or struct, a queue or stack data structure, or a simple variable of the primitive data type. It plays a key role in the system and is used for system scheduling control, status recording, and information transfer. + +- **[Recommendation] Log the operations, results, and status changes of key objects.** + +**Note:** Object operations include creating, loading, unloading, and releasing objects. For key object operations, log the operation subject, type, and result. For status operations, log the values before and after the status change. + +### Thread Logs + +- **[Recommendation] Log thread operations and related information.** + +**Note:** Thread operations include creating, starting, pausing, and terminating threads. Record the operation type, operation result, thread number, and thread name in the log. (A thread name must be set for important threads.) + +- **[Recommendation] Logs must be recorded when a thread enters an infinite loop or deadlock.** + +**Note:** A mechanism must be provided for detecting deadlocks or infinite loops that occur in threads with logic such as lock waiting, asynchronous processing, and cyclic processing, and logs must be recorded when an error occurs. + +- **[Recommendation] Log message processing information for message processing threads.** + +**Note:** Log the information such as the message name, processing result, and processing duration. For high-frequency messages, you can record logs only when an error occurs during message processing. + +### Concurrency Control Logs + +**Note:** Concurrency control objects may be locks, critical sections, and semaphores. + +- **[Recommendation] Log operations on concurrency control objects and related information.** + +**Note:** Concurrency control operations include creating, occupying, releasing, and waiting. Log information such as the operation type, operation object name, operation result, and operation location. + +### Shared Memory Logs + +**Note:** Shared memory is a common inter-process communication method in software systems. It is used to share or transfer data between modules. The data stored in the shared memory may be configuration data, database data, and the like. + +- **[Recommendation] Log operations on the shared memory and related information.** + +**Note:** The operations on the shared memory include creating, deleting, setting, querying, and destroying data. Log the operator, operation type, and operation result. + +### Interface Interaction Logs + + +There are internal and external system interfaces. Internal interfaces refer to the interfaces between subsystems and modules within the system. These interfaces include inter-module message sending interfaces, IPC interfaces, and RPC interfaces. + +- **[Recommendation] Record interface interaction information.** + +**Note:** Interface interaction information includes the interface caller, message content, processing result, and return value. User privacy information must be excluded from the message content and return value. + +### State Machine Logs + +- **[Recommendation] Log state machine operations and state change information.** + +**Note:** The operations on a state machine include creating, starting, ending, and destroying the state machine as well as changing its state. The state machine is usually driven by external conditions (such as messages and resources). State change information must be logged, such as the state names before and after the state change and the external conditions that cause the change. + +### Other OS Resources +The other OS resources refer to resources that are not mentioned in the preceding sections, such as sockets and timers. OS resources such as files and threads are mentioned before and are not covered in this part. + +- **[Recommendation] Log the process and result of socket connection establishment, connection maintenance, disconnection, and causes.** + +- **[Recommendation] Log the timer startup, reset, destruction, and timeout processes.** + +- **[Recommendation] Comply with the preceding logging principles when using other similar OS resources.** + +## HiLog API Usage Specifications + + +- **[Rule] Each service domain must have an independent domain ID.** + +**Note:** Before using the HiLog API to print logs, every service domain must apply for a domain ID from the DFX. The domain ID is used to measure and control the quality of a single service log. You can use the domain ID to filter out your own service logs for analysis. Do not use domain IDs of others. For test code, use the domain ID 0xD000F00. + +Range of the domain IDs: **0xD000001\-0xD00FFFF** + +- **[Recommendation] Use the domain ID allocated to your domain based on a certain layer and module granularity.** + +**Note:** A domain ID is a 32-bit integer expressed in 16-bit format. The domain ID is the format of 0xD0xxxyy, where D0 is the domain ID, the most significant 12 bits of ***xxx*** are the value allocated by the DFX, and the least significant 8 bits of ***yy*** are for internal use in the service domain. Domain IDs allocated among your service domain must be able to locate your internal organizations or modules and reflect their log quality. The DFX conducts logging control based on the domain IDs to prevent the logging of a single module from affecting other modules in the same service domain. For example, the BT service domain is further divided as follows by module: + + + APP | BT-App1 BT-App2 + --------------------------------------- + Framework | BT-Service1 BT-Service2 + --------------------------------------- + HAL | BT-HAL + --------------------------------------- + Kernel | BT-Driver1 BT-Driver2 + +Therefore, domain IDs allocated to BT can be further divided as follows: +| Domain Name| Domain ID | +|----|----| +| BT | 0xD000100 | +| BT-App1 | 0xD000101 | +| BT-App2 | 0xD000102 | +| BT-Service1 | 0xD000103 | +| BT-Service2 | 0xD000104 | +| BT-HAL | 0xD000105 | +| BT-Driver1 | 0xD000106 | +| BT-Driver2 | 0xD000107 | + +- **[Rule] The log service controls the log traffic of each service. Changing the default traffic threshold must be approved by the DFX.** + +**Note:** The default log traffic threshold of each domain is **2048 KB/s** for an official version and **10240 KB/s** for a trial version. Any change to the default threshold must be approved by the DFX. + +- **[Rule] Correctly set the log formatting privacy tags {public} and {private}**. + +**Note:** Privacy parameter IDs {public} and {private} indicate whether the log content of each parameter contains sensitive privacy information. The HiLog API automatically outputs the content of the {public} parameter in plaintext and filters the content of the {private} parameter using <private>. Set privacy parameter IDs only after you analyze the log content. Example: + +Source code: + + + HiLog.info(LABEL, "Device Name:%{public}s, IP:%{private}s.", DeviceName, ip); + + +Log output: + + + 11-11 09:19:00.932 1513 1513 E 00500/Settings: MyPad001, IP: diff --git a/en/contribute/OpenHarmony-c-coding-style-guide.md b/en/contribute/OpenHarmony-c-coding-style-guide.md index b75448dba5ec529d326259f723581ded0dcf1ba7..db98d92b2b3eff87a9019556eb886f40fbe79f28 100755 --- a/en/contribute/OpenHarmony-c-coding-style-guide.md +++ b/en/contribute/OpenHarmony-c-coding-style-guide.md @@ -1,8 +1,8 @@ -# C Coding Style Guide +# C Coding Style Guide ## Purpose -Rules are not perfect. Disabling useful features in specific situations may affect code implementation. However, the rules are formulated "to help most programmers to get more benefits". If a rule is found unhelpful or difficult to follow in team coding, please send your feedback to us so we can improve the rule accordingly. Before referring to this guide, you are expected to have the following basic capabilities for C rather than being a beginner who wants to learn about C. +Rules are not perfect. They might disable useful features in specific situations and therefore affect code implementation. However, the purpose of developing rules is to get more benefits for most programmers. If a rule cannot be followed in your team operation, we can improve the rule together. Before referring to this coding style guide, you are expected to have the following basic capabilities of the C programming language: 1. Understand the ISO standard of C. 2. Be familiar with the basic features of C. @@ -15,65 +15,72 @@ Code must meet the requirements for **readability**, **maintainability**, **secu ## Conventions **Rule**: Conventions that must be followed during programming. -**Suggestion**: Conventions that must be considered during programming. +**Rec**: Conventions that must be considered during programming. -It is necessary to understand the reason for these conventions and to try and comply with them, no matter if they are rules or recommendations. +It is necessary to understand the reason for these conventions and try to comply with them, no matter if they are rules or recommendations. ## Exceptions The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for their existence. -Exceptions destroy code consistency. Try to avoid them. Exceptions to 'Rules' should be very rare. +Try to avoid exceptions because they affect the code consistency. Exceptions to 'Rules' should be very rare. The style consistency principle is preferred in the following case: -**When you modify open source or third-party code. The existing code specifications prevail.** +**When you modify open-source or third-party code, comply with their respective code specifications.** # 1 Naming Names include file, function, variable, type, and macro names. Naming is considered the most difficult and important thing in software development. -The name of an identifier must be clear, well defined, and easy to understand, adapting to reading habit. +The name of an identifier must be clear, well defined, easy to understand, and accounting for reading habits. The unified naming style is the most direct expression of the consistency principle. ## General Conventions **CamelCase** -Camel case is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, and with no intervening spaces or punctuation. -This style has two alternatives depending on the case of the first letter: **UpperCamelCase and lowerCamelCase** +CamelCase is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, and with no intervening spaces or punctuation. +There are two conventions: **UpperCamelCase and lowerCamelCase**. -### Rule 1.1 Name identifiers in camel case style. +**Unix\_like** +Unix\_like is also known as the snake style. In the Unix\_like style, words contain only lowercase letters and are separated by underscores (\_). +Example: 'test_result' + +### Rule 1.1 Name identifiers in the CamelCase style. | Type| Naming Style |----------|---------- -| Function, struct, enumeration, union| UpperCamelCase +| Function, struct, enum, union| UpperCamelCase | Variable, function parameter, macro parameter, struct body, union member| lowerCamelCase -| Macro, constant, enumerated value, goto tag| All capitalized, separated with underscores (\_) +| Macro, constant, enumerated value, goto tag| All capitalized, separated by underscores (\_) Note: -The `constant` in the above table refers to the variable of the basic data type, enumeration, and string type of the const modifier under the global scope, excluding array, struct and union. -The `variable` in the above table refers to variables other than the constant definition, all using lowercase. +**Constant** in the above table refers to the variable that is of the basic data type, enum type, and string type and modified by **const** under the global scope, excluding arrays, structs, and unions. +**Variable** indicates the variables excluding those defined in **Constant**. These variables use the lowerCamelCase style. +Unix\_like can be used for Linux or Unix friendly code. +For code that is using the Unix\_like style, you can continue using this style. +The same naming style must be used for the same function, struct, or union. -### Rec 1.1 The larger the scope, the more accurate the name should be. +### Rec 1.1 Use more accurate names for identifiers with a large scope. -C is different from C++. There is no namespace or class. Therefore, the names of identifiers in the global scope must not conflict with each other. -Names of global functions, global variables, macros, types, and enumerations must be accurately described and unique in the global scope. +Different from C++, C does not have namespace or class.Therefore, the names of identifiers in the global scope must not conflict with each other. +Names of global functions, global variables, macros, types, and enums must be accurately described and unique in the global scope. Example: ```c -int GetCount(void); // Bad: inaccurate description. +int GetCount(void); // Bad: inaccurate description int GetActiveConnectCount(void); // Good ``` -For accurate naming, a module prefix can be added if necessary. +For purposes of accurate naming, a module prefix can be added if necessary. The module prefix and the naming body can be connected by following the CamelCase style. Example: ```c -int PrefixFuncName(void); // OK: CamelCase, with no prefix in the format, but prefix in the content. +int PrefixFuncName(void); // OK: CamelCase, a prefix in the content, but not in the format -enum XxxMyEnum { // OK. +enum XxxMyEnum { // OK ... }; ``` @@ -82,24 +89,24 @@ enum XxxMyEnum { // OK. ### Rec 1.2 Use lowercase file names. -File names naming are allowed only with lowercase letters, numbers, and underscores (\_). +Only lowercase letters, numbers, and underscores (\_) are allowed in file names. File names should be as short, accurate, and unambiguous as possible. -The reason for using lowercase file names is that different systems process file names in different ways (for example, Microsoft DOS and Windows OS are not case sensitive, but Unix/Linux and Mac systems are by default). +The reason for using lowercase file names is that different systems process file names in different ways. (For example, file names in MS-DOS and Windows are not case sensitive, but those in Unix/Linux and macOS are case sensitive by default). Good example: `dhcp_user_log.c` Bad examples: -`dhcp_user-log.c`: It is not recommended you separate names with '-'. +`dhcp_user-log.c`: It is not recommended that you separate words with the hyphen (-). `dhcpuserlog.c`: The words are not separated, causing poor readability. ## Function Naming -Functions are named in UpperCamelCase style. +Functions are named in the UpperCamelCase style. -### Rec 1.3 Name functions that comply with reading habits. +### Rec 1.3 Name functions to comply with reading habits. -The "verb + object" structure can be used for action related function names. For example: +The "verb + object" structure can be used for action related function names. Example: ```c AddTableEntry() // OK @@ -107,7 +114,7 @@ DeleteUser() // OK GetUserInfo() // OK ``` -An adjective or a prefix "is" can be used in a function returning a Boolean value. For example: +An adjective or a prefix "is" can be used in a function returning a Boolean value. Example: ```c DataReady() // OK @@ -126,10 +133,10 @@ GetTotalCount() // OK Variables are named in the lowerCamelCase style. This includes global variables, local variables, parameters in the function declaration or definition as well as parameters in function-like macro. -### Rule 1.2 Add the 'g\_' prefix to global variables. Do not add this prefix to static variables in a function. +### Rule 1.2 Add the 'g_' prefix to global variables, but not to static variables in a function. -Global variables should be used as little as possible, and special attention should be paid to their use. Prefixes are used for visual prominence, prompting developers to be more careful about using global variables. -The naming rule of global static variables is the same as that of global variables. The name of a static variable in a function is the same as that of a common local variable. +Global variables should be used as little as possible, and special attention should be paid to their use. This prefix highlights global variables so that developers can be more careful when handling them. +Global static variables and global variables are named in the same way. Static variables in functions and common local variables are named in the same way. ```c int g_activeConnectCount; @@ -141,18 +148,18 @@ void Func(void) } ``` -Notes: The nature of a constant is also a global variable, but it does not apply to current rule if the naming style is all uppercase and connected by underline. +Notes: Constants are also global variables in essence. However, if constants are named using uppercase letters separated by underscores (\_), the current rule does not apply. ### Rec 1.4 Keep local variables short and to the point. The name of a local variable should be short on the premise that meanings can be expressed through context. -The following is an example: +Example: ```c int Func(...) { - enum PowerBoardStatus powerBoardStatusOfSlot; // Not good: Long redundant local variable. + enum PowerBoardStatus powerBoardStatusOfSlot; // Not good: Long redundant local variable powerBoardStatusOfSlot = GetPowerBoardStatus(slot); if (powerBoardStatusOfSlot == POWER_OFF) { ... @@ -176,7 +183,7 @@ int Func(...) ``` Similarly, "tmp" can be used to address any type of temporary variable. -A short variable name should be used with caution, but sometimes a single character variable is allowed, for example, a counter variable in a loop statement. +A short variable name should be used with caution, but sometimes a single-character variable is allowed, for example, a counter variable in a loop statement. ```c int i; @@ -198,7 +205,7 @@ int Mul(int a, int b) ## Type Naming Types are named in the UpperCamelCase style. -The type can be a structure, a union, or an enumeration. +The type can be a struct, a union, or an enum. Example: @@ -215,7 +222,7 @@ union Packet { }; enum BaseColor { - RED, // Note: The enumeration is in UpperCamelCase style while the enumerated values adopt the macro naming style. + RED, // Note: The enum is in the UpperCamelCase style whereas the enumerated values adopt the macro naming style. GREEN, BLUE }; @@ -223,14 +230,14 @@ enum BaseColor { typedef int (*NodeCmpFunc)(struct Node *a, struct Node *b); ``` -When you use typedef to set an alias for a struct, a union or an enum type, try to use anonymous type. +When you use `typedef` to set an alias for a struct, a union, or an enum, try to use the anonymous type. If you need self-nesting pointers, you can add a 'tag' prefix or an underscore suffix. ```c typedef struct { // Good: The anonymous struct is used because self-nesting is not required. int a; int b; -} MyType; // Struct alias with UpperCamelCase. +} MyType; // The struct alias uses the UpperCamelCase style. ​```c typedef struct tagNode { // Good: Add the 'tag' prefix or use 'Node_'. @@ -239,14 +246,18 @@ typedef struct tagNode { // Good: Add the 'tag' prefix or use 'Node_'. } Node; // UpperCamelCase. ``` -## Macros, Constants, and Enumeration Naming +## Macro, Constant, and Enum Naming -Macros and enumerated values are capitalized and are separated with underscores (\_). -Constants are recommended to be capitalized and be separated with underscores (\_). Also, as global const variables, they can be named with global variable style. -The constants here are defined as global const variables of basic data type, enumeration, and string type. +Use uppercase letters separated by underscores (\_) for macro names and enumerated values. +You are advised to use uppercase letters separated with underscores (\_) for constant names. Global const variables can be named with the same style of global variables. +The constants here are defined as global const variables of the basic data type, enum type, or string type. -Function-like macros, can be named the same way as functions, using the UpperCamelCase naming style. -However, this approach makes the macros look the same as functions. It is confusing and needs special attention. +Use uppercase letters separated by underscores (\_) for function-like macros. +Exceptions: +1. Functions that use macros to implement generic functions, for example, macros that implement functions such as list and map, can be named in the same way as functions, using the UpperCamelCase style. +2. A function-like macro that is used to replace a function in the earlier version can be named in the same way as functions, using the UpperCamelCase style. +3. Macros for printing logs can be named in the same way as functions, using the UpperCamelCase style. +Note: Function-like macros named in the UpperCamelCase style must be marked as macros in the API description. Macro example: @@ -258,7 +269,7 @@ Macro example: ```c #ifdef SOME_DEFINE void Bar(int); -#define Foo(a) Bar(a) // The function-like macro is named as a function style. +#define Foo(a) Bar(a) // The function-like macro is named in the same way as a function. #else void Foo(int); #endif @@ -269,34 +280,34 @@ Constant example: ```c const int VERSION = 200; // OK. -const enum Color DEFAULT_COLOR = BLUE; // OK. +const enum Color DEFAULT_COLOR = BLUE; // OK -const char PATH_SEP = '/'; // OK. +const char PATH_SEP = '/'; // OK -const char * const GREETINGS = "Hello, World!"; // OK. +const char * const GREETINGS = "Hello, World!"; // OK ``` Non-constant example: ```c -// Structure type does not meet the definition of constant. +// A struct that does not meet the definition of constants const struct MyType g_myData = { ... }; // OK: Name it in lowerCamelCase style. -// Array type does not meet the definition of constant. +// An array that does not meet the definition of constants const int g_xxxBaseValue[4] = { 1, 2, 4, 8 }; // OK: Name it in lowerCamelCase style. int Foo(...) { - // The scope does not meet the definition of constant. + // A local const variable that does not meet the definition of constants const int bufSize = 100; // OK: Name it in lowerCamelCase style. ... } ``` -Enumeration example: +Enum example: ```c -// Note: The enumeration type name is in the UpperCamelCase style, while enumerated values are all capitalized and separated with underscores (_). +// Note: The enum type name is in the UpperCamelCase style, whereas the enumerated value is in uppercase letters separated by underscores (\_). enum BaseColor { RED, GREEN, @@ -304,19 +315,16 @@ enum BaseColor { }; ``` -### Rec 1.5 Do not name temporary variables in function-like macros and pollute the external scope. - -First, **use function-like macros as little as possible.** +### Rec 1.5 Avoid temporary variables in function-like macros from polluting external scopes. -When a function-like macro needs to define local variables, to avoid naming conflicts with local variables in external functions, - -an underline is a good solution. Example: +**If possible, use a function instead of a function-like macro. Define a function-like macro only when necessary.** +When defining local variables for a function-like macro, use double underscores at the end to avoid name conflicts with local variables in external functions. Example: ```c #define SWAP_INT(a, b) do { \ - int tmp_ = a; \ + int tmp__ = a; \ a = b; \ - b = tmp_; \ + b = tmp__; \ } while (0) ``` @@ -324,17 +332,17 @@ an underline is a good solution. Example: ## Line Length -### Rec 2.1 Ensure that each line is no more than 120 characters in length. +### Rule 2.1 Include 120 characters or less in each line. -The line width of the code should not be too long, otherwise it is not conducive to reading. -The line length requirement indirectly guides developers in shortening function and variable names, reducing nesting, and improving readability. -It is strongly recommended that the number of characters per line do not exceed **120** unless readability is significantly improved as a result and no information is hidden. -While the resolution of modern monitors is very high, long lines will increase the difficulty of reading comprehension, which is against the principles of "clear" and "concise" defined in this document. +A longer line makes it more difficult for reading. +To meet the line length requirement, you can shorten the names of functions and variables and reduce the number of nesting layers. This improves code readability. +Unless a long line is necessary to maintain readability and present complete information, steer your document clear of long lines. +Even on a high-resolution monitor, a long line increases the difficulty of reading. Strive for clearness and conciseness. -The following scenarios should not be wrapped, and can be treated as exceptions: +Exceptions: -- Line breaks can cause strings truncated and hard to retrieved (grep), such as command lines or URLs. Codes or comments that contain these can be treated as exceptions appropriately. -- '#include', '#error' statements are allowed to exceed the line width requirement, but you should try to avoid this. +- For code lines or comments, the use of the line feed causes content truncation and increases the search difficulty (grep). +- The #include and #error statements are allowed to exceed the line length requirement. However, you should try to avoid this. Example: @@ -346,23 +354,23 @@ Example: ## Indentation -### Rule 2.1 Use spaces to indent and indent four spaces at a time. +### Rule 2.2 Use spaces to indent and indent four spaces at a time. -Only spaces can be used for indentation. **4** spaces are indented each time. Do not use the Tab character to indent. -Currently, almost all integrated development environments (IDEs) and code editors support automatically converting a Tab input to **4** spaces. Please set your code editor to support indentation with spaces, if it is not the default. +Only spaces can be used for indentation. Four spaces are indented each time. Do not use the Tab character to indent. +Currently, almost all integrated development environments (IDEs) and code editors support automatic conversion of a Tab input to fours spaces. Configure your code editor to support indentation with spaces. ## Braces -### Rule 2.2 Use the K\&R indentation style. +### Rule 2.3 Use the K\&R indentation style. **K\&R style** While wrapping a line, the left brace of the function starts a new line and takes a single line. Other left braces are placed at the end of the line along with the statement. -The right brace takes a single line, unless it is followed by the rest of the same statement, such as 'while' in the 'do' statement, or 'else'/'else if' of the 'if' statement, or a comma or semicolon. +The right brace takes a single line, unless it is followed by the rest of the same statement, such as `while` in the `do` statement, `else` or `else if` in the `if` statement, a comma, or a semicolon. -For example: +Example: ```c -struct MyType { // Good: Follow the statement to the end, and indent one space. +struct MyType { // Good: The left brace is placed at the end of the line along with the statement, and one space is used for indentation. ... }; // Good: The right brace is followed by the semicolon. @@ -370,7 +378,7 @@ int Foo(int a) { // Good: The left brace of the function starts a new line, and nothing else is placed on the line. if (...) { ... - } else { // Good: The 'else' statement follows the right brace. + } else { // Good: The right brace is followed by the `else` statement. ... } // Good: The right brace takes a single line. } @@ -378,36 +386,36 @@ int Foo(int a) ## Function Declaration and Definition -### Rule 2.3 The return type and function name of the function declaration and definition must be on the same line. The function parameter list must be aligned appropriately if it needs to be wrapped. +### Rule 2.4 Keep the return type and function name of the function declaration or definition in the same line, and align the function parameter list appropriately if it needs to be wrapped. When a function is declared and defined, the return value type of the function should be in the same line as the function name. When the function parameter list is wrapped, it should be aligned appropriately. The left parenthesis of a parameter list is always in the same line as the function name. The right parenthesis always follows the last parameter. -The following is an example of line breaks: +Example: ```c -ReturnType FunctionName(ArgType paramName1, ArgType paramName2) // Good:All in one line +ReturnType FunctionName(ArgType paramName1, ArgType paramName2) // Good: All in one line { ... } -ReturnType VeryVeryVeryLongFunctionName(ArgType paramName1, // The line length cannot accommodate all parameters and thus a line break is required. - ArgType paramName2, // Good:Aligned with the previous line. +ReturnType VeryVeryVeryLongFunctionName(ArgType paramName1, // Each added parameter starts on a new line because the line length limit is exceeded. + ArgType paramName2, // Good: Aligned with the previous line ArgType paramName3) { ... } -ReturnType LongFunctionName(ArgType paramName1, ArgType paramName2, // Subject to line length, a line break is required. - ArgType paramName3, ArgType paramName4, ArgType paramName5) // Good: After the line break, 4 spaces are used for indentation. +ReturnType LongFunctionName(ArgType paramName1, ArgType paramName2, // Parameters are wrapped because the line length limit is exceeded. + ArgType paramName3, ArgType paramName4, ArgType paramName5) // Good: 4 spaces are used for indentation. { ... } -ReturnType ReallyReallyReallyReallyLongFunctionName( // The line length cannot accommodate the first parameter, and thus a line break is required. - ArgType paramName1, ArgType paramName2, ArgType paramName3) // Good: After the line break, 4 spaces are used for indentation. +ReturnType ReallyReallyReallyReallyLongFunctionName( // The line length cannot accommodate even the first parameter, and a line break is required. + ArgType paramName1, ArgType paramName2, ArgType paramName3) // Good: 4 spaces are used for indentation. { ... } @@ -415,40 +423,40 @@ ReturnType ReallyReallyReallyReallyLongFunctionName( // The line leng ## Function Calls -### Rule 2.4 The parameter list should be aligned appropriately when the parameter list requires a line break. +### Rule 2.5 Align the parameter list appropriately if it needs to be wrapped. -When the function is called, if the function parameter list is wrapped, it should be aligned appropriately. +In a function call, if the function parameter list is wrapped, it should be aligned appropriately. The left parenthesis is always followed by a function name, and the right parenthesis always follows the last parameter. -The following is an example of line breaks: +Example: ```c -ReturnType result = FunctionName(paramName1, paramName2); // Good:Function parameters are placed in one line. +ReturnType result = FunctionName(paramName1, paramName2); // Good: Function parameters are placed in one line. ReturnType result = FunctionName(paramName1, - paramName2, // Good:Aligned with the above parameters. + paramName2, // Good: Aligned with the above parameters paramName3); ReturnType result = FunctionName(paramName1, paramName2, - paramName3, paramName4, paramName5); // Good:After the line break, 4 spaces are used for indentation. + paramName3, paramName4, paramName5); // Good: 4 spaces are used for indentation. -ReturnType result = VeryVeryVeryLongFunctionName( // The line length cannot accommodate the first parameter, and thus a line break is required. - paramName1, paramName2, paramName3); // After the line break, 4 spaces are used for indentation. +ReturnType result = VeryVeryVeryLongFunctionName( // The line length cannot accommodate the first parameter, and therefore line feed is used. + paramName1, paramName2, paramName3); // 4 spaces are used for indentation. ``` -If the parameters in a function call are associated with each other, the parameters are grouped for better understanding, rather than strictly adhering to formatting requirements. +If the parameters in a function call are associated with each other, you can group the parameters for better understanding, rather than strictly adhering to the formatting requirements. ```c -// Good:The parameters in each line represent a group of data structures with a strong correlation. They are placed on one line for ease of understanding. +// Good: The parameters in each line represent a group of data structures with a strong correlation.They are placed on one line for ease of understanding. int result = DealWithStructureLikeParams(left.x, left.y, // Indicates a group of parameters. right.x, right.y); // Indicates another group of related parameters. ``` ## Conditional Statements -### Rule 2.5 Conditional statements must use braces. +### Rule 2.6 Use braces for conditional statements. -We require that all conditional statements use braces, even if there is only one statement. +Use braces to enclose conditional statements, even if there is only one statement. Reason: - Logic is intuitive and easy to read. @@ -461,21 +469,21 @@ if (objectIsNotExist) { // Good: Braces are added to a single-line condi } ``` -### Rule 2.6 Do not place 'if', 'else' and 'else if' in the same line. +### Rule 2.7 Do not place `if`, `else`, and `else if` in the same line. -In a conditional statement, if there are multiple branches, they should be written in different lines. +In a conditional statement, branches, if any, should be written in different lines. -The correct format: +Good example: ```c if (someConditions) { ... -} else { // Good: The 'else' is in a different line of 'if'. +} else { // Good: The `else` statement is in a different line of `if`. ... } ``` -The following is a case that does not comply with the specifications: +Bad example: ```c if (someConditions) { ... } else { ... } // Bad: They are in the same line. @@ -483,9 +491,9 @@ if (someConditions) { ... } else { ... } // Bad: They are in the same line. ## Loops -### Rule 2.7 Use braces in loop statements. +### Rule 2.8 Use braces for loop statements. -Similar to the condition expression, we require that the for and while loop conditional statements contain braces, even if there is only one loop. +Use braces to enclose the `for` and `while` statements, even if there is only one loop. ```c for (int i = 0; i < someRange; i++) { // Good: Braces are used. @@ -494,7 +502,7 @@ for (int i = 0; i < someRange; i++) { // Good: Braces are used. ``` ```c -while (condition) { } // Good: The while loop body is empty. And braces are used. +while (condition) { } // Good: The entire loop body is empty. And braces are used. ``` ```c @@ -511,14 +519,14 @@ for (int i = 0; i < someRange; i++) ``` ```c -while (condition); // Bad: Using semicolons will make people misunderstand which code is a part of the while statement. +while (condition); // Bad: The semicolon may be treated as part of the `while` statement. ``` -## Switch Statements +## `switch` Statements -### Rule 2.8 Indent the case or default statement in a switch statement block. +### Rule 2.9 Indent the `case` or `default` statement in a `switch` statement block. -The indentation style of the switch statement is as follows: +Use the following indentation style for the `switch` statement: ```c switch (var) { @@ -546,16 +554,15 @@ default: // Bad: 'default' not indented ## Expressions -### Rec 2.2 Keep a consistent expression line break style and ensure that operators are placed at the end of the line. +### Rec 2.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of the line. -A long expression that does not meet the line length requirement must be wrapped appropriately. Generally, the expression is wrapped at an operator of a lower priority or a hyphen, and the operator or hyphen is placed at the end of the line. -The operator and hyphen are placed at the end of the line, indicating that the operation is to be continued. +A long expression that does not meet the line length requirement must be wrapped appropriately. Generally, the expression is wrapped after a lower-priority operator or a hyphen, and the operator or hyphen is placed at the end of the line, indicating that the operation is to be continued. Example: ```c -// Pretend that the following first line does not meet the line length requirement. -if ((currentValue > MIN) && // Good: After the line break, the Boolean operator is placed at the end of the line. +// Assume that the first line does not meet the line length requirement. +if ((currentValue > MIN) && // Good: The Boolean operator is placed at the end of the line. (currentValue < MAX)) { DoSomething(); ... @@ -565,7 +572,7 @@ int result = reallyReallyLongVariableName1 + // Good: The plus sign is placed reallyReallyLongVariableName2; ``` -After an expression is wrapped, ensure that the lines are properly aligned or indented by 4 spaces. See the following example. +After an expression is wrapped, ensure that the lines are properly aligned or indented by 4 spaces. Example: ```c int sum = longVaribleName1 + longVaribleName2 + longVaribleName3 + @@ -577,32 +584,32 @@ int sum = longVaribleName1 + longVaribleName2 + longVaribleName3 + ## Variable Assignment -### Rule 2.9 Multiple variable definitions and assignment statements cannot be written on one line. +### Rule 2.10 Do not write multiple variable definitions or assignment statements in one line. -It is best to have only one variable initialization statement on each line. It is easier to read and understand. +It is recommended that each line contain only one variable initialization statement, which is easier to read and understand. ```c int maxCount = 10; bool isCompleted = false; ``` -The following is an example that does not comply with the specifications: +Bad example: ```c -int maxCount = 10; bool isCompleted = false; // Bad: Multiple initialization statements are placed on the same line. -int x, y = 0; // Bad: Variable definitions need to be placed on different lines. Each definition occupies one line. +int maxCount = 10; bool isCompleted = false; // Bad: Multiple initialization statements are placed in one line. +int x, y = 0; // Bad: Multiple variable definitions are placed in one line.Each definition occupies one line. int pointX; int pointY; ... -pointX = 1; pointY = 2; // Bad: Multiple variable assignment statements are placed on the same line. +pointX = 1; pointY = 2; // Bad: Multiple variable assignment statements are placed in one line. ``` -Exception: -If multiple variables with strong correlation are defined and do not need to be initialized, you can define the variables in a line to reduce repeated information so that the code is more compact. +Exceptions: +If multiple variable definitions have strong correlation and do not need to be initialized, you can define the variables in a line for code compactness. ```c -int i, j; // Good: Multiple variables that are defined and do not need to be initialized immediately can be written in one line. +int i, j; // Good: Multiple variable definitions that do not need to be initialized are written in one line. for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { ... @@ -614,16 +621,16 @@ for (i = 0; i < row; i++) { Initialization is applicable to structs, unions, and arrays. -### Rule 2.10 Indent when initiating a new line, or make a reasonable alignment. +### Rule 2.11 Use indentation or make a reasonable alignment for a new line. -When a structure or array is initialized, if a line break is made, ensure that the line is indented with 4 spaces. -From the readability point of view, make a reasonable alignment. +For the struct or array initialization, use 4 spaces for indentation if a line break is made. +From better readability, make a reasonable alignment. ```c // Good: No line break for a short line. int arr[4] = { 1, 2, 3, 4 }; -// Good: A line break here makes the readability better. +// Good: A line break makes better readability. const int rank[] = { 16, 16, 16, 16, 32, 32, 32, 32, 64, 64, 64, 64, 32, 32, 32, 32 @@ -635,12 +642,12 @@ Refer to the following format: ```c int a[][4] = { - { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, // OK. + { 1, 2, 3, 4 }, { 2, 2, 3, 4 }, // OK { 3, 2, 3, 4 }, { 4, 2, 3, 4 } }; int b[][8] = { - { 1, 2, 3, 4, 5, 6, 7, 8 }, // OK. + { 1, 2, 3, 4, 5, 6, 7, 8 }, // OK { 2, 2, 3, 4, 5, 6, 7, 8 } }; ``` @@ -648,7 +655,7 @@ int b[][8] = { ```c int c[][8] = { { - 1, 2, 3, 4, 5, 6, 7, 8 // OK. + 1, 2, 3, 4, 5, 6, 7, 8 // OK }, { 2, 2, 3, 4, 5, 6, 7, 8 } @@ -657,12 +664,12 @@ int c[][8] = { Note: -- If the left brace is placed at the end of the line, the corresponding right brace should be placed into a new line. +- If the left brace is placed at the end of the line, the corresponding right brace shoud be placed into a new line. - If the left brace is followed by the content, the corresponding right brace should also follow the content. -### Rule 2.11 When struct and union members are initialized, each member is initialized on a separate line. +### Rule 2.12 Initialize each member in a separate line during struct and union member initialization. -The C99 standard supports the initialization of the struct and union members in their definition. This is called the designated initializer. If initialization is performed in this way, each member is initialized in a separate line. +The C99 standard supports the initialization of the struct and union members in their definition. This is called the designated initializer. In such a way, each member should be initialized in a separate line. ```c struct Date { @@ -671,7 +678,7 @@ struct Date { int day; }; -struct Date date = { // Good: When the designated initializer is used, each member is initialized on a separate line. +struct Date date = { // Good: When the designated initializer is used, each member is initialized in a separate line. .year = 2000, .month = 1, .day = 1 @@ -680,104 +687,75 @@ struct Date date = { // Good: When the designated initializer is used, each m ## Pointers -### Rec 2.3 The pointer type asterisk "\*" follows the variable name or the type. Do not leave spaces on both sides and always use at least one space. +### Rec 2.2 Ensure that the asterisk (\*) in the pointer type is followed by the variable name or follows the type. There must be a space before or after the asterisk. -When you declare or define a pointer variable or return a pointer type function, "\*" can be placed on the left or right, adhering to the type or name. Do not leave spaces on both sides. And do not leave out spaces altogether. +When you declare or define a pointer variable or return a pointer type function, the asterisk can be placed on the left (following the type) or right (followed by the variable name). There must be only one space before or after the asterisk. ```c -int *p1; // OK. -int* p2; // OK. +int *p1; // OK +int* p2; // OK -int*p3; // Bad: No spaces. -int * p4; // Bad: Spaces on both sides. +int*p3; // Bad: No space +int * p4; // Bad: Space on both sides ``` Choose a style and stay consistent. -When using style that "\*" follows type, avoid declaring multiple variables with pointer in a line. +If you use the asterisk to follow the type, do not declare multiple variables with pointers in a line. ```c -int* a, b; // Bad: It is easy to misinterpret b as a pointer. +int* a, b; // Bad: b may be treated as a pointer. ``` -When using style that "\*" follows variable, there may be situations that cannot be followed. -Do not follow when it cannot. Style consistency first. +Do not use the asterisk followed by the variable name if this style is not suitable in all cases. +Keep style consistency first. ```c -char * const VERSION = "V100"; // OK. -int Foo(const char * restrict p); // OK. +char * const VERSION = "V100"; // OK +int Foo(const char * restrict p); // OK ``` -"\*" never follows 'const' or 'restrict' keywords anytime. +Do not use the asterisk to follow the `const` or `restrict` keywords. ## Compilation Preprocessing -### Rule 2.12 The number sign (#) must be placed at the beginning of a line for compilation preprocessing and can be indented in nested compilation preprocessing. +### Rule 2.13 Place the number sign (#) at the beginning of a line for compilation preprocessing. In nested compilation preprocessing, the number sign (#) can be indented. The number sign (#) must be placed at the beginning of a line for compilation preprocessing, even if the code is embedded in the function body. - -```c -#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) // Good: "#" is at the beginning of the line. -#define ATOMIC_X86_HAS_CMPXCHG16B 1 // Good: "#" is at the beginning of the line. -#else -#define ATOMIC_X86_HAS_CMPXCHG16B 0 -#endif - -int FunctionName(void) -{ - if (someThingError) { - ... -#ifdef HAS_SYSLOG // Good: "#" is at the beginning of the line even though it's in a function body. - WriteToSysLog(); -#else - WriteToFileLog(); -#endif - } -} -``` - -Nested preprocessing statements starting with "#" can be indented and aligned based on indentation requirements to different layers. - -```c -#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) - #define ATOMIC_X86_HAS_CMPXCHG16B 1 // Good: Statements are layered, facilitating reading. -#else - #define ATOMIC_X86_HAS_CMPXCHG16B 0 -#endif -``` +Try your best not to use compilation preprocessing macros. If they are needed in deed, they should be managed by dedicated personnel in a unified manner. ## Whitespace -### Rule 2.13 Ensure that horizontal whitespace is used to highlight keywords, important information and avoid unnecessary whitespace. +### Rule 2.14 Use horizontal whitespaces to highlight keywords and important information, and avoid unnecessary whitespaces. Horizontal spaces should be used to highlight keywords and important information. Do not add spaces at the end of each line of code. The general rules are as follows: -- Add spaces after keywords such as if, switch, case, do, while, and for. +- Add spaces after keywords such as `if`, `switch`, `case`, `do`, `while`, and `for`. - Do not add spaces after the left parenthesis or before the right parenthesis. - Add a space before and after each binary operator (= + - \< > \* / % \| \& \^ \<= >= == !=). - Do not add a space after any unary operator (\& \* + - ~!). -- A space is required before and after each ternary operator (? :). +- Add a space before and after each ternary operator (? :). - Add spaces before and after the colon of bit field description. -- There is no space between ++/-- and variables. -- There is no space before and after the struct member operator (. ->). +- Do not add spaces between ++/-- and variables. +- Do not add spaces before and after the struct member operator (. ->). - Adding or not adding spaces inside the brace must be consistent. -- Do not add spaces before commas, semicolons, colons (without the colon in the ternary operator or the bit field description); Add spaces after them. -- There is no space between the parentheses of the function parameter list and the function name. -- There is no space between the parenthesis of the type cast and the object being converted. -- There is no space between the square bracket of the array and the array name. +- Do not add spaces before commas, semicolons, or colons (excluding the colon in the ternary operator or the bit field description). Add spaces after them. +- Do not add spaces between the parentheses of the function parameter list and the function name. +- Do not add spaces between the parenthesis of the type cast and the object being converted. +- Do not add spaces between the square bracket of the array and the array name. - Spaces at the end of the line can be omitted. -For spaces inside the braces, the following are **recommended**: +For spaces inside the braces, the following **recommendations** are available: -- In general, spaces should be added after the left brace or before the right brace. -- For empty, or a single identifier, or a single literal constant, spaces are not required. Such as: '{}', '{0}', '{NULL}', '{"hi"}'. -- Spaces between consecutively nested multiple parentheses, spaces are not required. Such as: '{{0}}', '{{ 1, 2 }}'. Bad example: '{ 0, {1}}'. It is not a continuous nested scene, and the spaces inside the outermost braces are inconsistent. +- It is recommended that spaces be added after the left brace and before the right brace. +- For an empty constant or a constant with a single identifier or a single word, spaces are not required, for example, '{}', '{0}', '{NULL}', '{"hi"}'. +- Spaces between consecutively nested multiple parentheses are not required, for example, '{{0}}', '{{ 1, 2 }}'. '{ 0, {1}}' is a bad example, since it is not a consecutively nested scene and the spaces inside the outermost braces are inconsistent. In normal cases: ```c int i = 0; // Good: When the variable is initialized, there should be spaces before and after the =. Do not leave a space before the semicolon. -int buf[BUF_SIZE] = {0}; // Good: During array initialization, spaces in curly braces are optional. +int buf[BUF_SIZE] = {0}; // Good: For array initialization, spaces in curly braces are optional. int arr[] = { 10, 20 }; // Good: A space is added before and after the brace. ``` @@ -785,7 +763,7 @@ Function definition and call: ```c int result = Foo(arg1,arg2); - ^ // Bad: There should be a space after the comma. + ^ // Bad: There is no space after the comma. int result = Foo( arg1, arg2 ); ^ ^ // Bad: No space should be added to either side in the parentheses. @@ -794,42 +772,42 @@ int result = Foo( arg1, arg2 ); Pointer and address-of operator: ```c -x = *p; // Good: There is no space between the operator * and the pointer p. -p = &x; // Good: There is no space between the operator & and the variable x. +x = *p; // Good: There is no space between the operator (*) and the pointer p. +p = &x; // Good: There is no space between the operator (&) and the variable x. x = r.y; // Good: When a member variable is accessed through the operator (.), no space is added. -x = r->y; // Good: When a member variable is accessed through the operator (.), no space is added. +x = r->y; // Good: When a member variable is accessed through the operator (->), no space is added. ``` Operator: ```c -x = 0; // Good: A space must be added before and after the assignment operator (=). -x = -5; // Good: Do not add spaces before the minus sign (-) and the number. -++x; // Good: Do not add spaces before the minus sign (-) and the number. +x = 0; // Good: There is a space before and after the assignment operator (=). +x = -5; // Good: There is no space between the minus sign (-) and the number. +++++x; // Good: There is no space between ++/-- and the variable. x--; -if (x && !y) // Good: A space must be added before and after the Boolean operator. Do not leave spaces between the ! operator and variables. -v = w * x + y / z; // Good: A space must be added before and after binary operators. -v = w * (x + z); // Good: No space is required before and after the expression in the parentheses. +if (x && !y) // Good: There is a space before and after the Boolean operator, and there is no space between the operator (!) and variable. +v = w * x + y / z; // Good: There is a space before and after binary operators. +v = w * (x + z); // Good: There is no space before and after the expression in the parentheses. ``` Loops and conditional statements: ```c -if (condition) { // Good: A space is added between the if keyword and the parenthesis and no space is added before or after the conditional statement inside the parentheses. +if (condition) { // Good: A space is added between the `if` keyword and the parenthesis, and no space is added before or after the conditional statement inside the parentheses. ... -} else { // Good: A space is added between the else keyword and the curly brace. +} else { // Good: A space is added between the `else` keyword and the curly brace. ... } -while (condition) {} // Good: A space is added between the while keyword and the parenthesis. No space is added before or after the conditional statement inside the parentheses. +while (condition) {} // Good: A space is added between the `while` keyword and the parenthesis, and no space is added before or after the conditional statement inside the parentheses. -for (int i = 0; i < someRange; ++i) { // Good: A space is added between the for keyword and the parenthesis, and after the semicolons (;). +for (int i = 0; i < someRange; ++i) { // Good: A space is added between the `for` keyword and the parenthesis, and after the semicolons (;). ... } -switch (var) { // Good: A space is added after the switch keyword. - case 0: // Good: No space is added between the case conditional statement and the colon. +switch (var) { // Good: A space is added after the `switch` keyword. + case 0: // Good: No space is added between the `case` conditional statement and the colon (:). ... break; ... @@ -839,9 +817,9 @@ switch (var) { // Good: A space is added after the switch keyword. } ``` -Note: Current integrated development environments (IDEs) and code editors can be set to automatically delete spaces at the end of a line. Please configure your editor as such. +Note: The current IDE and code editor can be set to delete spaces at the end of a line. Configure your editor correctly. -### Rec 2.4 Arrange blank lines reasonably keep the code compact. +### Rec 2.3 Arrange blank lines reasonably to keep the code compact. Reduce unnecessary blank lines so that more code can be displayed for easy reading. The following rules are recommended: @@ -890,22 +868,28 @@ Comments help readers quickly understand code. Therefore, **comments should be p The comments must be concise, clear, and unambiguous, ensuring that the information is complete and not redundant. **Comments are as important as code.** -When writing a comment, you need to step into the reader's shoes and use comments to express what the reader really needs. Comments are used to express the function and intention of code, rather than repeating code. -When modifying the code, ensure that the comments are consistent. It is impolite to only modify code and not update the comments. It destroys the consistency between code and comments, and may confuse or even mislead readers. +When writing a comment, you need to step into the reader's shoes and use comments to express what the reader really needs. Comments are used to express the code functionality and intention, rather than repeating code. +When modifying the code, ensure that the comments are consistent. It is impolite to only modify code and not update the comments. This destroys the consistency between code and comments, and may cause confusion or even misleading. + +Comment code in fluent **English**. -Comment code in fluent English. +Comments must be added in the following scenarios (including but not limited to the listed scenarios): +1. Functions in the external interface header file provided by the module +2. Global variables being defined +3. Core algorithms +4. A function that contains more than 50 lines ## Comment Style In C code, both `/*` `*/` and `//` can be used. -Comments can be classified into different types depending on purpose and position, such as file header comments, function header comments, and general comments. +Comments can be classified into different types depending on the purpose and position, such as file header comments, function header comments, and general comments. Comments of the same type must keep a consistent style. -Note: The sample code used in this article sees extensive use of the '//' post-comment. This is only to aid understanding, and does not mean that this comment style is better. +Note: The sample code used in this article sees extensive use of the '//' post-comment. This is only for better understanding, and does not mean that this comment style is better. ## File Header Comments -### Rule 3.1 File header comments must contain the copyright license. +### Rule 3.1 Include the copyright license in the file header comments. /\* @@ -924,7 +908,7 @@ Note: The sample code used in this article sees extensive use of the '//' post-c ## Function Header Comments -### Rule 3.2 Empty function header comments with no content are forbidden. +### Rule 3.2 Do not use empty function header comments with no content. Not all functions need function header comments. Function header comments must be added for any information that cannot be expressed just with function prototype. @@ -958,7 +942,7 @@ int Func2(void); Use function names to describe functions, and only add function header comments if necessary. Do not write useless or redundant function headers. Do not write empty function headers with no content. -The function header comment content is **optional** any may include the following: function description, return value, performance constraint, usage, memory convention, algorithm implementation, and reentering requirements. +The following content is **optional** in the function header comment: function description, return value, performance constraint, usage, memory convention, algorithm implementation, and reentering requirement. In the function interface declaration in the external header file of the module, the function header comment should clearly describe important and useful information. Example: @@ -966,7 +950,7 @@ Example: ```c /* * The number of written bytes is returned. If -1 is returned, the write operation fails. - * Note that, the memory buffer is released by the caller. + * Note that the memory buffer is released by the caller. */ int WriteString(char *buf, int len); ``` @@ -987,13 +971,13 @@ Problems in the preceding example are as follows: - The 'Parameter' and 'Return value' headings have no content. - The function name has redundant information. -- The most important thing, the notice to release the buffer, is not clearly stated. +- It does not clearly state the party that should release the buffer. ## Code Comments -### Rule 3.3 Code comments are placed above or to the right of the corresponding code. +### Rule 3.3 Place code comments above or to the right of the code. -### Rule 3.4 There must be a space between the comment character and the comment content. At least one space is required between the comment and code if the comment is placed to the right of code. +### Rule 3.4 Add a space between the comment character and the comment content, and one space between the comment and code if the comment is placed to the right of the code. Comments placed above code should be indented to the same level as the code. Select and use one of the following styles: @@ -1011,7 +995,7 @@ DoSomething(); **Use '/\*' '\*/' to start the comment.** ```c -/*Single-line comment */ +/* Single-line comment */ DoSomething(); /* @@ -1049,25 +1033,12 @@ The correct method is to delete unnecessary code. If necessary, consider porting Here, commenting out refers to the removal of code from compilation without actually deleting it. This is done by using /\* \*/, //, #if 0, #ifdef NEVER\_DEFINED, and so on. -### Rec 3.1 No TODO, TBD, or FIXME comment is allowed in code delivered to a customer. - -TODO and TBD comments are used to describe required improvements and supplements. -FIXME comments are used to describe defects that need fixing. -They should have a standardized style, which facilitates text search. For example: - -```c -// TODO(): Supplement to XX -// FIXME: XX defect -``` - -During version development, this type of comments can be used for highlighting, and must be processed and deleted before delivery. +### Rec 3.1 Provide comments if `break` or `return` is not added to the end of the `case` statement block (fall-through). -### Rec 3.2 If 'break' or 'return' is not added to the end of the case statement block (fall-through), comments must be provided. +Sometimes, the same thing is needed for multiple `case` tags. When a `case` statement ends without `break` or `return`, the statement in the next `case` tag will be executed.This is called "fall-through". +In this case, add comments for the "fall-through" to clearly express your intention, or at least explicitly specify the "fall-through". -Sometimes, the same thing is needed for multiple case tags. When a case statement ends without 'break' or 'return', the statement in the next case tag will be executed. This is called "fall-through". -In this case, you need to add comments for the "fall-through" to clearly describe your intention. - -For example, explicitly specify the "fall-through”: +For example, to explicitly specify the "fall-through": ```c switch (var) { @@ -1084,7 +1055,7 @@ switch (var) { } ``` -If the case statement is empty, the comment explaining the "fall-through" can be omitted. +If the `case` statement is empty, no comment is required to explain the "fall-through". ```c switch (var) { @@ -1100,26 +1071,26 @@ switch (var) { # 4 Header Files -**For the C language, the design of the header file reflects most of the system design.** +**For the C programming language, the design of the header file reflects most of the system design.** The correct use of the header file makes code more readable, reduces file size, and speeds up compilation and build performance. -This chapter summarizes some methods from the perspective of programming specifications to help you properly plan header files. +The following programming specifications aim to help you properly plan header files. ## Header File Responsibility A header file is an external interface of a module or file. -The interface declaration for most functions (except inline functions), is more suitable in the header file, than as interface implementations. -Header responsibility should be simple. A complex header file will make dependencies complex and cause long compilation times. +The interface declaration for most functions (except inline functions) is suitable in the header file. Interface implementations are not allowed in the header file. +Header responsibility should be simple. A complex header file will make dependencies complex and cause a long compilation time. -### Rec 4.1 Each .c file must have a corresponding .h file, which is used to declare the interfaces that need to be disclosed externally. +### Rec 4.1 For each .c file, provide a corresponding .h file, which is used to declare the interfaces that need to be provided externally. -Generally, each .c file has a corresponding .h file (Not necessarily the same name.), which is used to store the function declarations, macro definitions, and type definitions that are to be exposed externally. +Generally, each .c file has a corresponding .h file (not necessarily with the same name), which is used to store the function declarations, macro definitions, and type definitions that are to be exposed externally. If a .c file does not need to open any interface externally, it should not exist. -Exception: the entry point of the program (for example, the file where the main function is located), unit test code, and dynamic library code. +Exceptions: the entry point of the program (for example, the file where the main function is located), unit test code, and dynamic library code. Example: -foo.h content +Content of **foo.h**: ```c #ifndef FOO_H @@ -1130,7 +1101,7 @@ int Foo(void); // Good: Declare an external interface in the header file. #endif ``` -foo.c content +Content of **foo.c**: ```c static void Bar(void); // Good: The declaration of the internal function is placed in the header of the .c file, declaring its static scope. @@ -1146,19 +1117,19 @@ static void Bar(void) } ``` -Internally used functions declarations, macros, enumerations, structures, and others should not be placed in header files. +Internally used functions declarations, macros, enums, structs, and others should not be placed in header files. In some products, one .c file corresponds to two .h files. One is used to store external public interfaces, and the other is used to store definitions and declarations among others for internal use to limit the number of code lines in the .c file. -This style is not recommended. It is used only because the .c file is too large. It should be split into another file instead. +This style is not recommended. It is used only because the .c file is too large. You should consider splitting the .c file first. In addition, if private definitions and declarations are placed in independent header files, they technically cannot avoid inclusion. -This rule, in turn, is not necessarily correct. For example: +This rule, in turn, is not necessarily correct. Example: Some simple header files, such as the command ID definition header file, do not need to have the corresponding .c file. If a set of interface protocols has multiple instances and the interface is fixed, one .h file can have multiple .c files. ### Rec 4.2 Use .h as the extension of the header file, rather than other unconventional extensions, for example, .inc. -Some products use .inc as the header file name extension, which does not comply with the C language. A header file using .inc as the file name extension usually indicates a private header file. However, in practice, this recommendation is not followed properly. An .inc file is generally contained in multiple .c files. This document does not recommend that private definitions be stored in header files. For details, see [Rec 4.1](#a4-1). +Some products use .inc as the header file name extension, which does not comply with the C programming language.A header file using .inc as the file name extension usually indicates a private header file. However, in practice, this recommendation is not followed properly. An .inc file is generally contained in multiple .c files. It is not recommended that private definitions be stored in header files. For details, see [Rec 4.1](#a4-1). ## Header File Dependency @@ -1168,7 +1139,7 @@ Generally, an unstable module depends on a stable module. When the unstable modu Dependency direction is as follows: Products depend on the platform, and the platform depends on the standard library. In addition to unstable modules depending on stable modules, each module depends on the interface. In this way, in case of any internal implementation changes to one module, users do not need to recompile another module. -This assumes that the interface itself is the most stable. +It is assumed that the interface is the most stable. ### Rule 4.1 Forbid cyclic dependency of header files. @@ -1177,34 +1148,33 @@ For a unidirectional dependency: a.h contains b.h, b.h contains c.h, and c.h doe The cyclic dependency of header files reflects an obviously unreasonable architecture design, which can be avoided through optimization. -### Rule 4.2 The header file must have the internal #include protection character (#define protection). +### Rule 4.2 Include the internal #include protection character (#define protection) in the header file. To prevent header files from being included multiple times, all header files should be protected by #define. Do not use #pragma once. When defining a protection character, comply with the following rules: -- The protection character uses a unique name. It is recommended to consider the file path and name below the top layer of the project code tree. +- Use a unique name for the protection character in the format of subsystem\_component\_file. - Do not place code or comments before or after the protected part, except for file header comments. -Assume that the path to timer.h of the timer module is `timer/include/timer.h`. If the protection character resembles 'TIME\_H', it is not unique. Add a path, for example: - +Assume that the **timer.h** file of the timer component of the util subsystem is stored in the **timer/include/timer.h** directory. If `TIME_H` is used as the protection character, name conflicts may occur. Use the following protection characters instead: ```c -#ifndef TIMER_INCLUDE_TIMER_H -#define TIMER_INCLUDE_TIMER_H +#ifndef UTIL_TIMER_TIMER_H +#define UTIL_TIMER_TIMER_H ... -#endif +#endif // UTIL_TIMER_TIMER_H ``` -### Rule 4.3 Do not reference external function interfaces and variables by using declaration. +### Rule 4.3 Do not reference external function interfaces and variables by using declaration. You can use the interfaces provided by other modules or files only by using header files. Using external function interfaces and variables with an extern declaration may cause inconsistency between declarations and definitions when external interfaces are changed. In addition, this kind of implicit dependency may cause architecture corruption. Cases that do not comply with specifications: -a.c content +Content of **a.c**: ```c extern int Foo(void); // Bad: Reference external functions by using the extern declaration. @@ -1216,10 +1186,10 @@ void Bar(void) ``` It should be changed to: -a.c content +Content of **a.c**: ```c -#include "b.h" // Good: Use the interface providing the interface. +#include "b.h" // Good: Use the interfaces provided by another .c file by including the header file. void Bar(void) { int i = Foo(); @@ -1227,13 +1197,13 @@ void Bar(void) } ``` -b.h content +Content of **b.h**: ```c int Foo(void); ``` -b.c content +Content of **b.c**: ```c int Foo(void) @@ -1243,18 +1213,18 @@ int Foo(void) ``` In some scenarios, if internal functions need to be referenced with no intrusion to the code, the extern declaration mode can be used. -For example: +Example: When performing unit testing on an internal function, you can use the extern declaration to reference the tested function. When a function needs to be stubbed or patched, the function can be declared using extern. -### Rule 4.4 Do not include header files in extern "C". +### Rule 4.4 Do not include header files in extern "C". -If a header file is included in extern "C", extern "C" may be nested. Some compilers restrict the nesting of extern "C". If there are too many nested layers, compilation errors may occur. +If a header file is included in extern "C", extern "C" may be nested. Some compilers restrict the number of nesting layers of extern "C". Too many nesting layers may cause compilation errors. -extern "C" usually occurs in mixed programming using both C and C++. If the extern "C" includes a header file, the original intent behind the header file may be hindered. For example, when the linkage specifications are modified incorrectly. +extern "C" usually occurs in mixed programming using both C and C++. If extern "C" includes a header file, the original intent behind the header file may be hindered, for example, when linkage specifications are changed incorrectly. -For example, assume that there are two header files a.h and b.h. -a.h content +Assume that there are two header files: **a.h** and **b.h**. +Content of **a.h**: ```c ... @@ -1266,7 +1236,7 @@ void A(int) #endif ``` -b.h content +Content of **b.h**: ```c ... @@ -1282,7 +1252,7 @@ void B(void); #endif ``` -Using the C++ preprocessor to expand b.h, the following information is displayed: +When you use the C++ preprocessor to expand **b.h**, the following information is displayed: ```c extern "C" { @@ -1291,42 +1261,42 @@ extern "C" { } ``` -In the a.h file, the function Foo is intended to be a C++ free function following the C++ specifications. However, in the b.h file, because `#include "a.h"` is placed inside `extern "C"`, the linking specification of function Foo is changed incorrectly. +In the **a.h** file, the **Foo** function is intended to be a C++ free function following the C++ specifications. However, in the **b.h** file, because `#include "a.h"` is placed inside `extern "C"`, the linking specification of the **Foo** function is changed incorrectly. -Exception: In the C++ compilation environment, if you want to reference a header file written in pure C, a non-intrusive approach is to exclude the C header file from `extern "C"`. +Exceptions: In the C++ compilation environment, if you want to reference a header file written in pure C, a non-intrusive approach is to exclude the C header file from `extern "C"`. # 5 Functions -Functions help avoid repeated code and increase reusability. In addition, functions act to layer code and reduce code complexity, hiding implementation details, making programs more modular, and facilitating reading and maintenance. +Functions help avoid repeated code and increase reusability. Functions are layered to reduce complexity and hide implementation details, making programs more modular and facilitating code reading and maintenance. -The function should be concise and short. +Functions should be concise and short. One function completes only one thing. ## Function Design -Writing clean functions and organizing code effectively is the essence of good function design. The code should be simple and not conceal the designer's intention, using clean abstractions and straightforward control statements to organize the function naturally. +The essence of function design is to write clean functions and organize code effectively.The code should be simple and not conceal the designer's intention, using clean abstractions and straightforward control statements to organize the function naturally. -### Rule 5.1 Avoid long functions and ensure that functions contain no more than 50 lines (not including blank lines and comments). +### Rule 5.1 Avoid long functions and ensure that functions contain no more than 50 lines (excluding blank lines and comments). -A function should fit on one screen, (be no longer than 50 lines), do only one thing, and do it well. +A function should be able to be displayed on one screen (fewer than 50 lines). It does only one thing and does it well. -Large functions are often caused by the fulfillment of more than one purpose by the function, or over complication when parts could be abstracted. +A long function usually means that it aims to implement complex functionalities or contains excess details. -Exception: +Exceptions: Considering the code's aggregation and functionality, some functions may exceed 50 lines, but only if the code is readable and concise. These exceptions should be minimal, such as specific algorithm processing. Even if a large function works well in the moment, once someone modifies it, new problems may occur. It may even cause bugs that are difficult to discover. -It is recommended that you split it into several simpler and easier to manage functions, facilitating reading and modification of code. +It is recommended that you split the code into several functions that are simpler and easier to manage so that others can easily read and modify the code. ### Rule 5.2 Avoid nesting a code block more than four times within a function. -The nested code block depth of a function refers to the layered depth of a code control block (created by statements such as: if, for, while, and switch). -Each layer of nesting increases the brain power required to read the code, because you need to maintain a "stack" in your mind comprised of each conditional statement, loop, and so on. -Code should be broken down functionally to prevent the reader from remembering too much context at a time. +The nested code block depth of a function refers to the layered depth of a code control block (created by statements such as `if`, `for`, `while`, and `switch`). +Each layer of nesting increases the difficulty in reading the code. +Further functional decomposition should be done for better understanding. -Using `guardian statements`, (a short conditional return), can effectively reduce the nesting layers of if statements. For example: -The original code nesting level is 3: +Using `guard clauses` can effectively reduce the nesting layers of the `if` statements. Example: +Three nesting layers are used originally: ```c int Foo(...) @@ -1341,7 +1311,7 @@ int Foo(...) } ``` -Refactored code using the `guardian statement`, the nesting level is 2: +Two nesting layers after code reconstruction using `guard clauses`: ```c int Foo(...) @@ -1359,8 +1329,8 @@ int Foo(...) } ``` -Exception: -Considering the code's aggregation and functionality, some functions may exceed 4 times nested, but only if the code is readable and concise. +Exceptions: +Considering the code's aggregation and functionality, some functions may contain 4 or more nesting layers, but only if the code is readable and concise. These exceptions should be rare. ### Rec 5.1 Process all returned error codes. @@ -1371,7 +1341,7 @@ Example: ```c char fileHead[128]; -ReadFileHead(fileName, fileHead, sizeof(fileHead)); // Bad: The returned value is not checked. +ReadFileHead(fileName, fileHead, sizeof(fileHead)); // Bad: The return value is not checked. DealWithFileHead(fileHead, sizeof(fileHead)); // The 'fileHead' is possibly invalid. ``` @@ -1388,7 +1358,7 @@ if (ret != OK) { // Good: Ensure that the 'fileHead' is written. DealWithFileHead(fileHead, sizeof(fileHead)); // Process the file header. ``` -Note that when the return value of a function is ignored and instead void is returned frequently, consider whether the return value of the function is designed reasonably. +If the return value of a function is ignored and `void` is returned frequently, check whether the return value of the function is designed properly. Only if the caller of a function really doesn't need a return value, should you design the function to return `void`. ## Function Parameters @@ -1397,14 +1367,26 @@ Only if the caller of a function really doesn't need a return value, should you Using return values rather than output parameters improves readability and usually provides the same or better performance. -Readability can be improved by naming functions such as GetXxx, FindXxx, or directly using a single noun, to directly return the corresponding object. +Readability can be improved by naming functions such as GetXxx, FindXxx, IsXxx, OnXxx, or directly using a single noun, to directly return the corresponding object. + +Exceptions: +1. When multiple values are returned, you can design an output parameter for the function. +2. If memory allocation is involved, you can design an output parameter. The caller passes the allocated memory as an output parameter, and memory allocation is not performed in the function. -### Rec 5.3 Use strongly typed parameters and avoid using void\* +### Rec 5.3 Define function parameters in the sequence of input, output, and input/output parameters. + +You are advised to define function parameters in the sequence of input, output, and input/output parameters. + +### Rule 5.3 Provide a release function if allocation of resources, such as memory, locks, and queues, is involved. + +Resources should be released from where they are applied for. If a function applies for resources, the module must provide resource functions. + +### Rec 5.4 Use strongly typed parameters. Do not use void\*. While different languages have their own views on strong typing and weak typing, it is generally believed that C/C++ is a strongly typed language. Since we use such a strongly typed language, we should keep this style. The advantage of this strongly typed style is to prevent evasive errors by catching errors at the compilation stage. -Strong types help the compiler find more errors for us. Pay attention to the usage of the `FooListAddNode` function in the following code: +Strong types help the compiler find more errors.Pay attention to the usage of the `FooListAddNode` function in the following code: ```c struct FooNode { @@ -1429,7 +1411,7 @@ void MakeTheList(...) BarNode *bar; ... - FooListAddNode(bar); // Wrong: In this example, the foo parameter was supposed to be passed, but the bar parameter is incorrectly passed instead. No error is reported immediately and issues may occur as a result. + FooListAddNode(bar); // Wrong: In this example, the bar parameter rather than the foo parameter is passed.No error is reported immediately and issues may occur as a result. } ``` @@ -1444,14 +1426,14 @@ void FooListAddNode(FooNode *foo) } ``` -Exception: For some generic interfaces, you can use the input parameter `void *` to pass different types of pointers. +Exceptions: For some generic interfaces, you can use the input parameter `void *` to pass different types of pointers. -### It is the caller's responsibility to check the validity of internal function parameters of a module. +### Rec 5.5 It is the caller's responsibility to check the validity of internal function parameters of a module. -Validity checks must be performed on data received from external modules to protect programs against illegal input. +Validity check must be performed on parameters passed from external modules to protect programs from being damaged by invalid input data. When calling internal functions, by default, the caller is responsible for ensuring the validity of any returned data. If the callee takes responsibility for checking data validity, checks may be performed multiple times and redundant code is generated. This is not concise. -The caller ensures the validity of any received data. This type of contractual programming can make logic simpler and code more readable. +When the caller ensures the validity of any received data, this contractual programming makes logic simpler and code more readable. Example: ```c @@ -1460,7 +1442,7 @@ int SomeProc(...) int data; bool dataOK = GetData(&data); // Get data. - if (!dataOK) { // Check the result of the previous step ensuring data validity. + if (!dataOK) { // Check the result of the previous step to ensure data validity. return -1; } @@ -1470,7 +1452,7 @@ int SomeProc(...) void DealWithData(int data) { - if (data < MIN || data > MAX) { // Bad: The caller has already ensured the validity of the data. + if (data < MIN || data > MAX) { // Bad: The caller has already ensured data validity. return; } @@ -1478,7 +1460,7 @@ void DealWithData(int data) } ``` -### Rec 5.5 The pointer argument of a function should be declared as 'const' if it is not used to modify the pointed object. +### Rec 5.5 Declare the pointer argument of a function as 'const' if it is not used to modify the pointed object. The const pointer argument, which restricts the function from modifying the object through the pointer, makes code stronger and safer. @@ -1488,9 +1470,9 @@ Example: In the example of the strncmp in the 7.21.4.4 of the C99 standard, the int strncmp(const char *s1, const char *s2, size_t n); // Good: The invariant parameter is declared as const. ``` -Note: Whether or not the pointer parameter is to be declared as 'const' depends on the function design, not on whether there is a "modify object" action in the function entity. +Note: Whether to declare the pointer parameter as `const` depends on the function design, but not on whether there is a "modify object" action in the function entity. -### Rec 5.6 Ensure that the number of parameters in a function is less than or equal to 5. +### Rec 5.6 Include no more than 5 parameters in a function. If a function has too many parameters, the function is easy to be affected by changes in external code, hindering maintenance. Too many function parameters will also increases the workload for testing. @@ -1503,18 +1485,18 @@ The number of parameters in a function must not exceed 5. If the number of param An inline function is a function optimization method introduced by C99. Function inlining can eliminate the overhead of function calls; thanks to inlining, combination with the called code is implemented, so that the compiler can achieve further code optimization from a larger perspective. The inline function is similar to a function-like macro. For details, see [Rec 6.1](#a6-1). -### Rec 5.7 Ensure that the inline function contains no more than 10 lines (non-blank and non-comment). +### Rec 5.7 Include no more than 10 lines in an inline function (excluding blank lines and comments). -Defining a function as an inline function generally aims to improve performance, but it does not always improve performance. If the function body is short, function inlining can effectively reduce the size of the target code and improve the function execution efficiency. +Defining a function as an inline function generally aims to improve performance, though it may fail to do so.If the function body is short, function inlining can effectively reduce the size of the target code and improve the function execution efficiency. Vice versa, if the function body is large, inlining will cause expansion of the target code, especially when there are many call points. It is recommended that inline functions be controlled to within **10** lines. -Do not abuse inline functions to improve performance. Avoid premature optimization. In general, a function can be defined as an inline function only when actual test data proves that the inlining achieves higher performance. Functions such as setter and getter functions, that are short and called frequently can be defined as inline functions. +Do not abuse inline functions to improve performance. Avoid premature optimization. In general, a function can be defined as an inline function only when actual test data proves that the inlining achieves higher performance. Functions such as setter and getter functions, which are short and called frequently, can be defined as inline functions. ### Rule 5.3 Define inline functions that will be called by multiple source files in the header file. Inline functions are unfolded in compilation. Therefore, the inline function definition must be visible in each source file that calls this function. -As shown in the following code, inline.h has only the declaration of the `SomeInlineFunc` function but no definition. The other.c file includes inline.h. As a result, inlining fails when `SomeInlineFunc` is called. +As shown in the following code, **inline.h** contains the declaration of the `SomeInlineFunc` function but not the definition. The **other.c** file includes **inline.h**. As a result, inlining fails when `SomeInlineFunc` is called. inline.h @@ -1541,7 +1523,7 @@ int OtherFunc(void) } ``` -Due to this restriction, if multiple source files need to call the same inline function, the definition of the inline function needs to be placed in the header file. +Due to this restriction, if multiple source files need to call the same inline function, the definition of the inline function must be placed in the header file. The inline function implementation in **gnu89** differs from that in the **C99** standard. For compatibility, you can declare the function as **static inline**. # 6 Macros @@ -1560,17 +1542,17 @@ A function-like macro is a macro (as shown in the following example) similar to } while (0) ``` -### Use functions instead of function-like macros. +### Rec 6.1 Use functions instead of function-like macros. -Before defining a function-like macro, consider whether it can be replaced with a function. If so, you are advised to replace macros with functions. +Before defining a function-like macro, consider whether it can be replaced with a function. If yes, you are advised to use a function for replacement. The disadvantages of the function-like macro are as follows: - Function-like macros haves no type check, which is not as strict as the function call check. For the example code, see [Below](#macro_lack_of_type_check__example). - If macro parameters are not calculated during macro expansion, unexpected results may be generated. For details, see [Rule 6.1](#r6-1) and [Rule 6.3](#r6-3). -- The macro has no independent scope. When it is used together with control flow statements, unexpected results described in [Rule 6.2](#r6-2) may be generated. -- There are high skill requirements on the proper use of macros (see the following rules), for example, the usage of `#` and parentheses affects readability. +- A macro has no independent scope. When it is used together with control flow statements, unexpected results described in [Rule 6.2](#r6-2) may be generated. +- There are high skill requirements on the proper use of macros (for example, the usage of `#` and wide use of parentheses), which reduces readability. - Extensions of some macros can only be implemented by specific compilers in specific scenarios, such as `statement expression` of `gcc`, reducing the portability. -- After the macro is expanded at the pre-compilation stage, it is invisible during subsequent compilation, linking, and debugging. Macros that contain multiple lines are expanded into a line. Function-like macros are difficult to debug, interrupt, and locate in the case of bugs. +- After the macro is expanded during precompilation, it is invisible during subsequent compilation, linking, and debugging. Besides, macros that contain multiple lines are expanded into a line. - Macros containing a large number of statements must be expanded at each call point. If there are many call points, the code will be expanded. Example code of a function-like macro lacking type check: @@ -1601,19 +1583,19 @@ MACRO: max of a(1) and b(-1) is -1 FUNC : max of a(1) and b(-1) is 1 ``` -The function does not have the preceding macro disadvantages. However, compared with macros, the biggest disadvantage is that the execution efficiency is not as high (increasing the overhead of function calls and the difficulty of compiler optimization). +The function does not have the preceding macro disadvantages. However, compared with macros, the biggest disadvantage of functions is its low execution efficiency (increasing the overhead of function calls and the difficulty of compiler optimization). Therefore, the C99 standard introduces inline functions (gcc introduces inline functions ahead of this standard). The inline function is similar to the macro, as it is also expanded at the call point. The difference is that inline functions are expanded during compilation. Inline functions have the advantages of both functions and macros: - Strict type checking is performed for inline functions and functions. -- The parameter of an inline function/function is calculated only once. +- Each input parameter of an inline function or function is calculated only once. - Inline functions are unfolded in place and there is no overhead for function calls. - Inline functions are better optimized than standard functions. For performance-sensitive code, consider using inline functions instead of function-like macros. -Functions and inline functions cannot completely replace function-like macros, because function-like macros are more suitable for certain scenarios. +Functions and inline functions cannot completely replace function-like macros, since function-like macros are more suitable for certain scenarios. For example, in a log scenario, using a function-like macro with variable parameters and default parameters is more convenient. ```c @@ -1621,7 +1603,7 @@ int ErrLog(const char *file, unsigned long line, const char *fmt, ...); #define ERR_LOG(fmt, ...) ErrLog(__FILE__, __LINE__, fmt, ##__VA_ARGS__) ``` -### Rule 6.1 When a macro is defined, macro parameters must use complete parentheses. +### Rule 6.1 Use complete parentheses for macro parameters when defining a macro. The macro parameter is replaced by text only when the macro is expanded. The value is calculated when the macro is compiled. After the text replacement, the statements contained in the macro are combined with called code. The expression after combination may result in a different result than expected, especially when the macro parameter is in an expression. @@ -1629,7 +1611,7 @@ The expression after combination may result in a different result than expected, The following is an incorrect format: ```c -#define SUM(a, b) a + b // Bad. +#define SUM(a, b) a + b // Bad ``` When the macro is used, the execution result is inconsistent with the expected result. @@ -1637,7 +1619,7 @@ When the macro is used, the execution result is inconsistent with the expected r This problem can be solved by adding parentheses to the entire expression, as shown in the following: ```c -#define SUM(a, b) (a + b) // Bad. +#define SUM(a, b) (a + b) // Bad ``` However, this method has the following problems: @@ -1646,7 +1628,7 @@ However, this method has the following problems: To solve this problem, add parentheses to each macro parameter, as shown in the following: ```c -#define SUM(a, b) (a) + (b) // Bad. +#define SUM(a, b) (a) + (b) // Bad ``` The third scenario is as follows: `SUM(2, 8) * 10` . The result after the extension is `(2) + ((8) * 10)`, which is inconsistent with the expected result `(2 + 8) * 10`. @@ -1657,7 +1639,7 @@ In conclusion, the correct format is as follows: #define SUM(a, b) ((a) + (b)) // Good. ``` -But avoid abusing parentheses. As shown in the following, adding parentheses to a single identifier or a positive number is meaningless. +Avoid abusing parentheses. As shown in the following, adding parentheses to a single identifier or a positive number is meaningless. ```c #define SOME_CONST 100 // Good: No parentheses needed for a single positive number. @@ -1668,8 +1650,8 @@ But avoid abusing parentheses. As shown in the following, adding parentheses to Notes: -- Macro parameters in '#', '##' operation do not need parentheses. -- Macro parameters which participating in string splicing do not need parentheses. +- Do not add parentheses to macro parameters when they are involved in the '#' or '##' operation. +- Do not add parentheses to macro parameters when they are used for string concatenation. - If a macro parameter is used as a separate part in one side of an assignment expression (including +=, -=, etc.), parentheses are not required. - If a macro parameter is used as a separate part in comma expressions, functions or macro call lists, parentheses are not required. @@ -1680,25 +1662,25 @@ Example: #define HELLO_STR(obj) "Hello, " obj // No parentheses for 'obj' -#define ADD_3(sum, a, b, c) (sum = (a) + (b) + (c)) // 'a', 'b', and 'c' need parentheses, while 'sum' does not. +#define ADD_3(sum, a, b, c) (sum = (a) + (b) + (c)) // 'a', 'b', and 'c' need parentheses, whereas 'sum' does not. -#define FOO(a, b) Bar((a) + 1, b) // 'a' needs parentheses, while 'b' does not. +#define FOO(a, b) Bar((a) + 1, b) // 'a' needs parentheses, whereas 'b' does not. ``` -### Rule 6.2 Implementation statements of function-like macros that contain multiple statements must be placed in a do-while(0). +### Rule 6.2 Place implementation statements of function-like macros that contain multiple statements in a `do-while(0)`. -Macros do not have code blocks. Macros do not have code blocks. When a macro is expanded at the call point, the expressions and variables defined in the macro are integrated into the calling code. As a result, variable name conflict and segmentation of macro statements may occur. Use do-while(0) to add a boundary to the macro so that the macro has an independent scope. In addition, a single statement can be formed by combining the macro with a semicolon (;) to avoid this problem. +Macros do not have code blocks. When a macro is expanded at the call point, the expressions and variables defined in the macro are integrated into the calling code. As a result, variable name conflict and segmentation of macro statements may occur. Use `do-while(0)` to add a boundary to the macro so that the macro has an independent scope. In addition, a single statement can be formed by combining the macro with a semicolon (;) to avoid this problem. -The following macro is incorrect: +Incorrect example: ```c -// Not Good. +// Not Good #define FOO(x) \ (void)printf("arg is %d\n", (x)); \ DoSomething((x)); ``` -When the macro is called as shown in the following example code, the for loop only executes the first statement of the macro, and the next statement of the macro is executed only after the loop ends. +When the macro is called as shown in the following example code, the `for` loop only executes the first statement of the macro, and the next statement of the macro is executed only after the loop ends. ```c for (i = 1; i < 10; i++) @@ -1724,21 +1706,21 @@ else FOO(20); ``` -The correct format is to wrap the executed body using a do-while(0), as shown in the following: +The correct format is to wrap the executed body using a `do-while(0)`, as shown in the following: ```c -// Good. +// Good #define FOO(x) do { \ (void)printf("arg is %d\n", (x)); \ DoSomething((x)); \ } while (0) ``` -Exception: +Exceptions: - Macros that contain 'break' or 'continue' statements can be treated as exceptions. Do use these macros carefully. -- An exception can be made when the macro contains an incomplete statement. For example, use a macro to encapsulate the conditional part of the for loop. -- An exception can be a non-multiple statement, or a single if/for/while/switch statement. +- An exception can be made when the macro contains an incomplete statement. For example, use a macro to encapsulate the conditional part of the `for` loop. +- An exception can be a non-multiple statement, or a single `if`, `for`, `while`, or `switch` statement. ### Rule 6.3 Do not pass expressions with side effects to a function-like macro. @@ -1765,11 +1747,11 @@ a++; // Result: a = 6, which is added only once. In addition, if the macro parameter contains a function call, the function may be called repeatedly after the macro is expanded. If the function execution results are the same, it is a waste; if the results are different, the execution result may not meet the expected value. -### Rec 6.2 Exercise caution when you use the statements such as return, goto, continue, and break in a function-like macro definition. +### Rec 6.2 Exercise caution when you use the statements such as `return`, `goto`, `continue`, and `break` in a function-like macro definition. -In a macro, the process changing statements, such as return, goto, continue, and break. While they can simplify the code, they hide the real process, which hinders understanding and causes resource leakage. +Although process changing statements, such as `return`, `goto`, `continue`, and `break`, in a macro can simplify the code, they hide the real process, which hinders understanding and easily causes resource leakage. -First, the macro encapsulation of the statement 'return' can easily lead to excessive encapsulation and use. +First, the macro encapsulation of the `return` statement can easily lead to excessive encapsulation and use. As shown in the following code, the judgment of `status` is a part of the main process. After being encapsulated in macros, the purpose is not intuitive. The `RETURN_IF` macro is ignored, causing a confused understanding. ```c @@ -1787,15 +1769,15 @@ As shown in the following code, the judgment of `status` is a part of the main p } while (0) ret = InitModuleA(a, b, &status); -LOG_AND_RETURN_IF_FAIL(ret, "Init module A failed!"); // OK. +LOG_AND_RETURN_IF_FAIL(ret, "Init module A failed!"); // OK RETURN_IF(status != READY, ERR_NOT_READY); // Bad: The most important logic is not obvious. ret = InitModuleB(c); -LOG_AND_RETURN_IF_FAIL(ret, "Init module B failed!"); // OK. +LOG_AND_RETURN_IF_FAIL(ret, "Init module B failed!"); // OK ``` -Second, if return is encapsulated in a macro, it may also cause a memory leak. Example is as follows: +Second, if `return` is encapsulated in a macro, it may also cause a memory leak. Example: ```c #define CHECK_PTR(ptr, ret) do { \ @@ -1813,17 +1795,17 @@ mem2 = MemAlloc(...); CHECK_PTR(mem2, ERR_CODE_XXX); // Wrong: Memory leak. ``` -If `mem2` fails to apply for memory, the `CHECK_PTR` will return a message instead of releasing `mem1`. +If `mem2` fails to apply for memory, `CHECK_PTR` will return a message instead of releasing `mem1`. Besides, the name of the `CHECK_PTR` macro is not good. The macro name only reflects the check action and does not specify the result. Readers can see that a failure is returned when the pointer is null only after viewing the macro implementation. It's not inherently obvious. -In summary: It is not recommended to encapsulate statements that change control flow, such as return, goto, continue, and break in macro definitions. -However, these macros can be used such as return value judgment as an exception. +In summary, it is not recommended to encapsulate process changing statements, such as `return`, `goto`, `continue`, and `break`, in macro definitions. +However, these macros can be used in special scenarios, such as return value judgment. -Note: **Macro names must contain descriptive keywords if statements that will change control flow such as return, goto, continue, and break are used.** +Note: **Macro names must contain descriptive keywords if process changing statements, such as `return`, `goto`, `continue`, and `break`, are used.** -### Rec 6.3 Ensure that function-like macros contain no more than 10 lines (not including blank lines and comments). +### Rec 6.3 Include no more than 10 lines in a function-like macro (excluding blank lines and comments). -A big problem of the function-like macro is that it is more difficult to debug and locate than the function, especially when the macro is too long. +A function-like macro is more difficult to debug and locate than a function, especially when the macro is too long. Macro expansion will also lead to more compiled code. It is recommended that function-like macros contain no more than 10 lines. # 7 Variables @@ -1887,7 +1869,7 @@ For example, the PCLint tool reports a warning for the following two examples. ### Rule 7.3 Forbid invalid and redundant variable initialization. -If the initial value is not determined before initialization is performed, it is not concise but not secure, which may introduce problems that are more difficult to discover. +If the initial value is not determined before initialization is performed, it is not concise or secure and may cause problems that are more difficult to discover. Common redundant initialization: @@ -1940,7 +1922,7 @@ The C99 does not limit the definition position of local variables to before the This concise approach not only limits the scope of the variable scope, but also solves the problem of how to initialize the variable when it is defined. If this compilation environment is supported, you are advised to define local variables in this way. -**Exception:** +**Exceptions:** **As 'Secure Coding Standard' required, pointers, resource variables, and boolean variables can be treated as exceptions of this rule.** ### Rule 7.4 Do not use magic numbers. @@ -1978,9 +1960,9 @@ There are special cases: for example, the expression `if (MIN < v && v < MAX)` i You do not need to worry about accidentally writing '==' as '=' because a compilation alarm will be generated for `if (v = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that that code is readable. -### A full expression containing an increment (++) or decrement (--) operator should have no other using of the variable. +### Do not reference a variable again in an expression containing an increment (++) or decrement (--) operator. -In an expression containing a variable increment or decrement operation, if the variable is referenced again, the result is not explicitly defined in the C standard, which may vary between compilers or different versions of the same compiler. +In an expression containing a variable increment or decrement operator, if the variable is referenced again, the result is not explicitly defined in the C standard, which may vary between compilers or different compiler versions. For better portability, you should not make any assumptions about the operation sequence not defined in any standards. Note that this problem cannot be solved by using parentheses because it is not a problem of priority. @@ -2024,12 +2006,12 @@ c = (a & 0xFF) + b; /* Parentheses are required while using bit operators. * ## Statements -### Rule 8.2 The switch statement must have a 'default' branch. +### Rule 8.2 Provide a 'default' branch for the `switch` statement. In most cases, the 'default' branch exists in the switch statement to ensure that there is a default processing action when the case tag is missing. -Exception: -If the switch condition variable is of the enumeration type and the case branches cover all values, then the default branch is redundant. +Exceptions: +If the switch condition variable is of the enum type and the case branches cover all values, then the default branch is redundant. A modern compiler can check whether the case branch of some enumerated values is missing in the switch statement. A warning will be displayed. ```c @@ -2050,11 +2032,11 @@ switch (color) { } ``` -### Rec 8.3 Exercise caution when using the goto statement. +### Rec 8.3 Exercise caution when using the `goto` statement. -The goto statement destroys the structure of the program, so you'd better not use the goto statement unless you really need it. You can only jump to statements following the goto statement, and only within the one function. +The `goto` statement destroys the program. Avoid using it if possible. You can only jump to statements following the `goto` statement, and only within the one function. -The goto statement is used to implement function return to a single point within a function. +The `goto` statement is used to implement function return to a single point within a function. If a function has a large number of identical logics that cannot be encapsulated, for example, repeated file execution, the processed part of code after the file operation failure (for example, closing the file handle and releasing memory that is dynamically applied for) is usually placed in the last part of the function body. And the goto statement is placed right before these. In this way, the code becomes clear and concise. It can also be encapsulated in functions or macros, but doing so makes code less straightforward. Example: @@ -2113,4 +2095,4 @@ unsigned short int exam; ch = -1; exam = ch; // Bad: Compilers does not generate any warnings. In this case, the value of exam is 0xFFFF. -``` \ No newline at end of file +``` diff --git a/en/contribute/OpenHarmony-cpp-coding-style-guide.md b/en/contribute/OpenHarmony-cpp-coding-style-guide.md index a95ae1b7c83951dbb46794038d7276ee57317e2f..9a6fbad31c0a49d51fe503c0b4ec08cc745c1f9d 100755 --- a/en/contribute/OpenHarmony-cpp-coding-style-guide.md +++ b/en/contribute/OpenHarmony-cpp-coding-style-guide.md @@ -1,61 +1,61 @@ # C++ Coding Style Guide -## Purpose -Rules are not perfect. Disabling useful features in specific situations may affect code implementation. However, the rules are formulated "to help most programmers to get more benefits". If a rule is found unhelpful or difficult to follow in team coding, please send your feedback to us so we can improve the rule accordingly. -Before referring to this guide, you are expected to have the following basic capabilities for C++. It is not for a beginner that wants to learn about C++. +## Purpose +Rules are not perfect. They might disable useful features in specific situations and therefore affect code implementation. However, the purpose of developing rules is to get more benefits for most programmers. If a rule cannot be followed in your team operation, we can improve the rule together. +Before referring to this coding style guide, you are expected to have the following basic capabilities of the C++programming language: 1. Have a general knowledge of ISO standards for C++. 2. Be familiar with the basic features of C++, including those of C++ 03/11/14/17. -3. Have a general knowledge of the C++ Standard Library. +3. Have a general knowledge of the C++ standard library. ## General Principles Code must meet the requirements for readability, maintainability, security, reliability, testability, efficiency, and portability while ensuring functionality correctness. -## Key Points +## Key Points 1. C++ programming style, such as naming and typesetting. 2. C++ modular design, including how to design header files, classes, interfaces, and functions. 3. Best practices of C++ features, including constants, type casting, resource management, and templates. 4. Best practices of modern C++, including conventions that can improve code maintainability and reliability in C++ 11/14/17. +5. This coding style guide is preferentially applicable to C++17. +## Conventions +**Rule**: Conventions that must be followed during programming. -## Conventions -**Rule**: a regulating principle that must be followed during programming. +**Rec**: Conventions that must be considered during programming. -**Recommendation**: a guideline that must be considered during programming. +This document is applicable to standard C++ versions (C++ 03/11/14/17) unless otherwise specified. -This document is applicable to standard C++ versions (C++ 03/11/14/17) unless otherwise specified in the rule. - -## Exceptions -It is necessary to understand the reason for each rule or recommendation and to try and comply with them. +## Exceptions +It is necessary to understand the reason for these conventions and try to comply with them, no matter if they are rules or recommendations. However, some rules and recommendations have exceptions. The only acceptable exceptions are those that do not violate the general principles and provide appropriate reasons for the exception. Try to avoid exceptions because they affect the code consistency. Exceptions to 'Rules' should be very rare. The style consistency principle is preferred in the following case: -When you modify external open source or third-party code, the existing code specifications prevail. +When you modify open-source or third-party code, comply with their respective code specifications. # 2 Naming ## General Naming Rules __CamelCase__ -CamelCase is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, with no intervening spaces or punctuation. -There are two conventions: UpperCamelCase and lowerCamelCase. +CamelCase is the practice of writing compound words or phrases so that each word or abbreviation in the phrase begins with a capital letter, and with no intervening spaces or punctuation. +There are two conventions: UpperCamelCase and lowerCamelCase. | Type | Naming Style | | ---------------------------------------- | ---------------------------------------- | -| Class Type, Struct Type, Enumeration Type, and Union Type Definitions, Scope Name | UpperCamelCase | -| Functions (Including Global Functions, Scope Functions, and Member Functions) | UpperCamelCase | -| Global Variables (Including Variables of the Global and Namespace Scopes, Namespace Variables, and Class Static Variables), Local Variables, Function Parameters, and Class, Struct, and Union Member Variables | lowerCamelCase | -| Macro, Constant, Enumerated Value, goto Tag | All caps, separated with underscores (`_`) | +| Class, struct, enumeration, union, scope name| UpperCamelCase | +| unctions (including global functions, scope functions, and member functions) | UpperCamelCase | +| Global variables (including variables of the global and namespace scopes, and class static variables), local variables, function parameters, and class, struct, and union member variables | lowerCamelCase | +| Macro, constant, enumerated value, goto tag| All capitalized, separated by underscores (\_)| Note: -**Constant** indicates the variables of the basic, enumeration, or character string type modified by const or constexpr in the global scope, the namespace scope, and the scope of a static member of a class. +**Constant** in the above table refers to the variable that is of the basic data type, enumeration type, and string type and modified by **const** or **constexpr** under the global scope, the namespace scope, and the scope of a static member of a class, excluding arrays and other variables. **Variable** indicates the variables excluding those defined in **Constant**. These variables use the lowerCamelCase style. -## File Names -### Recommendation 2.2.1 Use .cpp as the C++ file name extension and .h as the header file name extension. -It is recommended that you use .h as the name extension of a header file so that the header file can be directly compatible with C and C++. -It is recommended that you use .cpp as the name extension of an implementation file. In this way, you can directly distinguish C++ code from C code. +## File Naming +### Rule 2.2.1 Use .cpp as the C++ file name extension and .h as the header file name extension. +It is recommended that you use .h as the file name extension of a header file so that the header file is compatible with C and C++. +It is recommended that you use .cpp as the file name extension of an implementation file. In this way, you can easily distinguish C++ code from C code. At present, there are some other file name extensions used by programmers: @@ -66,8 +66,8 @@ If your project team uses a specific file name extension, you can continue to us This document uses .h and .cpp extensions. -### Recommendation 2.2.2 Keep C++ file names the same as the class name. -The names of the C++ header file and the C++ implementation file must be the same as the class name. Use the CamelCase or Kernel style and keep the style consistent. +### Rule 2.2.2 Keep C++ file names the same as the class name. +The names of the C++ header file and the C++ implementation file must be the same as the class name. Use the unix\_like style and keep the style consistent. For example, if there is a class named DatabaseConnection, the corresponding file names are as follows: - database_connection.h @@ -75,8 +75,8 @@ For example, if there is a class named DatabaseConnection, the corresponding fil The naming rules of struct, namespace, and enumeration definition files are similar to the rules above. -## Function Names -Functions are named in UpperCamelCase. Generally, the verb or verb-object structure is used. +## Function Naming +Functions are named in the UpperCamelCase style. Generally, the verb or verb-object structure is used. ```cpp class List { public: @@ -90,12 +90,12 @@ namespace Utils { } ``` -## Type Names +## Type Naming Types are named in the UpperCamelCase style. -All types, such as classes, structs, unions, typedefs, and enumerations, use the same conventions. For example: +All types, such as classes, structs, unions, typedefs, and enumerations, use the same conventions. Example: ```cpp -// classes, structs and unions +// Classes, structs, and unions class UrlTable { ... class UrlTableTester { ... struct UrlTableProperties { ... @@ -104,13 +104,13 @@ union Packet { ... // typedefs typedef std::map PropertiesMap; -// enums +// Enums enum UrlTableErrors { ... ``` For namespace naming, UpperCamelCase is recommended. ```cpp -// namespace +// Namespaces namespace OsUtils { namespace FileUtils { @@ -121,9 +121,9 @@ namespace FileUtils { ``` -### Recommendation 2.4.1 Do not abuse typedef or #define to alias basic types. -Unless otherwise specified, do not use typedef or #define to redefine a basic value type. -The basic types found in the `` header file are preferable. +### Rec 2.4.1 Do not abuse typedef or #define to set alias for the basic data types. +Unless otherwise specified, do not use typedef or #define to redefine basic data types. +The basic data types found in the `` header file are preferable. | Signed Type | Unsigned Type | Description | | ----------- | ------------- | ---------------------------------------- | @@ -134,8 +134,8 @@ The basic types found in the `` header file are preferable. | intptr_t | uintptr_t | The signed or unsigned integer type large enough to hold a pointer. | -## Variable Names -General variables are named in lowerCamelCase, including global variables, function parameters, local variables, and member variables. +## Variable Naming +General variables, including global variables, function parameters, local variables, and member variables, are named in the lowerCamelCase style. ```cpp std::string tableName; // Good: Recommended style. std::string tablename; // Bad: Forbidden style. @@ -143,10 +143,10 @@ std::string path; // Good: When there is only one word, lowerCamelCase (al ``` ### Rule 2.5.1 Add the prefix 'g_' to global variables. Do not add a prefix to a static variable. -Global variables should be used as little as possible, and special attention should be paid to the use of global variables. This prefix highlights global variables so that developers can be more careful when handling them. +Global variables should be used as little as possible, and special attention should be paid to their use. This prefix highlights global variables so that developers can be more careful when handling them. - Global static variables and global variables are named in the same way. -- Static variables and common local variables in functions are named in the same way. -- Static member variables and common member variables of classes are named in the same way. +- Static variables in functions and common local variables are named in the same way. +- Static member variables in classes and common member variables are named in the same way. ```cpp int g_activeConnectCount; @@ -158,24 +158,24 @@ void Func() } ``` -### Rule 2.5.2 Name member variables in classes based on the three styles of the lowerCamelCase and maintain a uniform coding style for a product or project. +### Rule 2.5.2 Name member variables in classes in the unix\_like style. ```cpp class Foo { private: - std::string fileName_; // Add the _ postfix, similar to the K&R naming style. + std::string fileName_; // Add the underscore (\_) as the suffix, similar to the K&R naming style. }; ``` Use the lowerCamelCase style and do not add prefixes or suffixes to name a member variable of the struct or union type. Keep the naming style consistent with that for a local variable. -## Macro, Constant, and Enumeration Names -For macros and enumerated values, use all caps separated with underscores (`_`). -In the global scope, constants of named and unnamed namespaces and static member constants should be capitalized and separated with underscores (`_`). Local constants and ordinary const member variables use the lowerCamelCase naming style. +## Macro, Constant, and Enum Naming +Use uppercase letters separated by underscores (\_) for macro names and enumerated values. +In the global scope, constants of named and unnamed namespaces and static member constants should be capitalized and separated with underscores (\_).Local constants and ordinary const member variables use the lowerCamelCase naming style. ```cpp -#define MAX(a, b) (((a) < (b))? (b): (a)) // Though examples of Macro names are made, you are not advised to use macros to implement this function. +#define MAX(a, b) (((a) < (b))? (b): (a)) // Example of naming a macro only. -enum BaseColor { // Note: Enumerated types are named in the UpperCamelCase style, while their values are all capitalized and separated with underscores (_). +enum BaseColor { // Note: The enum type name is in the UpperCamelCase style, whereas the enumerated value is in uppercase letters separated by underscores (\_). RED, DARK_RED, GREEN, @@ -199,12 +199,12 @@ namespace Utils { ## Line Length -### Recommendation 3.1.1 Each line of code should contain a maximum of 120 characters. -** Note: **It is recommended that the number of characters in each line not exceed 120. It is recommended that the number of characters in each line not exceed 120. If the line of code exceeds the permitted length, wrap the line appropriately. +### Rule 3.1.1 Include 120 characters or less in each line. +If the line of code exceeds the permitted length, wrap the line appropriately. -Exception: -- If a one-line comment contains a command or URL of more than 120 characters, you can keep the line for ease in using copy, paste, and search using the grep command. -- The length of an `#include` statement can contain a long path exceeding 120 characters, but this should be avoided if possible. +Exceptions: +- If a line of comment contains a command or URL of more than 120 characters, you can keep the line for easy copy, paste, and search using the grep command. +- The #include and #error statements are allowed to exceed the line length requirement. However, you should try to avoid this. - The error information in preprocessor directives can exceed the permitted length. Put the error information of preprocessor directives in one line to facilitate reading and understanding even if the line contains more than 120 characters. ```cpp @@ -217,22 +217,22 @@ Exception: ### Rule 3.2.1 Use spaces to indent and indent 4 spaces at a time. Only spaces can be used for indentation. Four spaces are indented each time. Do not use the Tab character to indent. -Currently, almost all IDEs support automatic expansion of a Tab to 4 spaces upon pressing the tab key. Please configure your IDE to do so. +Currently, almost all integrated development environments (IDEs) support automatic conversion of a Tab input to four spaces. Configure your IDE to support indentation with spaces. ## Braces -### Rule 3.3.1 Use the K&R indentation writing style. +### Rule 3.3.1 Use the K&R indentation style. __K&R style__ -When a line break is required, the left brace of a function (excluding the lambda statement) starts a new line. One space should be placed between the statement and the brace. -The right brace starts a new line and nothing else is placed on the line, unless it is followed by the remaining part of the same statement, for example, "while" in the do statement, "else" or "else if" in the if statement, a comma, and a semicolon. +While wrapping a line, the left brace of the function (excluding the lambda statement) starts a new line and takes a single line. Other left braces are placed at the end of the line along with the statement. +The right brace takes a single line, unless it is followed by the rest of the same statement, such as `while` in the `do` statement, `else` or `else if` in the `if` statement, a comma, or a semicolon. -For example: +Example: ```cpp -struct MyType { // Follow the statement to the end, and indent one space. +struct MyType { // The left brace is placed at the end of the line along with the statement, and one space is used for indentation. ... }; int Foo(int a) -{ // The left brace of the function starts a new line, nothing else is placed on the line. +{ // The left brace of the function starts a new line, and nothing else is placed on the line. if (...) { ... } else { @@ -259,13 +259,13 @@ private: }; ``` -## Function Declarations and Definitions +## Function Declarations and Definitions -### Rule 3.4.1 The return type and the function name of a function declaration or definition must be on the same line. When the length of the function parameter list exceeds the permitted length, a line break is required and parameters must be aligned appropriately. -When a function is declared or defined, the return value type of the function should be on the same line as the function name. If the line length permits, the function parameters should be placed on the same line. Otherwise, the function parameters should be wrapped and properly aligned. -The left parenthesis of a parameter list should always be on the same line as the function name. The right parenthesis always follows the last parameter. +### Rule 3.4.1 Keep the return type and function name of the function declaration or definition in the same line, and align the function parameter list appropriately if it needs to be wrapped. +When a function is declared and defined, the return value type of the function should be in the same line as the function name. When the function parameter list is wrapped, it should be aligned appropriately. +The left parenthesis of a parameter list is always in the same line as the function name. The right parenthesis always follows the last parameter. -The following is an example of line breaks: +Example: ```cpp ReturnType FunctionName(ArgType paramName1, ArgType paramName2) // Good: All are in the same line. { @@ -409,10 +409,10 @@ default: // Bad: default is not indented. ## Expressions -### Recommendation 3.9.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of a line. +### Rec 3.9.1 Keep a consistent line break style for expressions and ensure that operators are placed at the end of a line. A long expression that does not meet the line length requirement must be wrapped appropriately. Generally, the expression is wrapped at an operator of a lower priority or a connector, and the operator or connector is placed at the end of the line. Placing these at the end of a line indicates that the operation is to be continued on the next line. -For example: +Example: // Assume that the first line exceeds the length limit. ```cpp @@ -472,7 +472,7 @@ const int rank[] = { ``` ## Pointers and References -### Recommendation 3.12.1 The pointer type `*` follows a variable name or type. There can be only one space to the side of it. +### Rec 3.12.1 The pointer type `*` follows a variable name or type. There can be only one space to the side of it. Pointer naming: There can be only one space next to `*`. ```cpp int* p = NULL; // Good @@ -487,7 +487,7 @@ Exception: When a variable is modified by const or restrict, `*` cannot follow t const char * const VERSION = "V100"; ``` -### Recommendation 3.12.2 The reference type `&` follows a variable name or type. There can be only one space to the side of it. +### Rec 3.12.2 The reference type `&` follows a variable name or type. There can be only one space to the side of it. Reference naming: There can be only one space around `&`. ```cpp int i = 8; @@ -502,39 +502,45 @@ int & p = i; // Bad int&p = i; // Bad ``` -## Preprocessor Directives -### Rule 3.13.1 The number sign (#) that starts a preprocessor directive must be at the beginning of the line and can be indented in nested preprocessor directives. -The number sign (#) that starts a preprocessor directive must be at the beginning of the line even through the preprocessor directive is inside a function. - -```cpp -#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) // Good: "#" is at the beginning of the line. -#define ATOMIC_X86_HAS_CMPXCHG16B 1 // Good: "#" is at the beginning of the line. -#else -#define ATOMIC_X86_HAS_CMPXCHG16B 0 -#endif - +## Compilation Preprocessing +### Rule 3.13.1 Place a number sign (#) at the beginning of a line for compilation preprocessing. In nested compilation preprocessing, the number sign (#) can be indented. +The number sign (#) must be placed at the beginning of a line for compilation preprocessing, even if the code is embedded in the function body. + +### Rule 3.13.2 Do not use macros. +Macros do not obey scope, type system, and other rules, and may easily lead to issues. Avoid macro definitions wherever possible. If you must use macros, give them unique names. +In C++, there are many ways to avoid using macros: +- Use `const` or `enum` to define constants that are easy to understand. +- Use namespaces to avoid name conflicts. +- Use the `inline` function to avoid function call overhead. +- Use the `template` function to handle multiple types. +Macros can be used in scenarios such as header guards, conditional compilation, and logging. + +### Rule 3.13.3 Do not use macros to represent constants. +Macros involve simple text replacement, which is completed during preprocessing. When an error occurs, the macro value is reported without the macro name. During tracing and debugging, the macro name is not displayed either. Besides, macros do not have type checking or scopes. + +### Rule 3.13.4 Do not use function-like macros. +Before defining a function-like macro, consider whether it can be replaced with a function. If yes, you are advised to use a function for replacement. +The disadvantages of the function-like macro are as follows: +- Function-like macros have no type check, which is not as strict as the function call check. +- If macro parameters are not evaluated during macro expansion, unexpected results may occur. +- A macro has no independent scope. +- There are high skill requirements on the proper use of macros (for example, the usage of `#` and wide use of parentheses), which reduces readability. +- Extensions of some macros can only be implemented by specific compilers in specific scenarios, such as `statement expression` of `gcc`, reducing the portability. +- After the macro is expanded during precompilation, it is invisible during subsequent compilation, linking, and debugging. Besides, macros that contain multiple lines are expanded into a line. Function-like macros are difficult to debug, set breakpoints, and locate in case of bugs. +- Macros containing a large number of statements must be expanded at each call point. If there are many call points, the code will be expanded. + +Unlike macros, functions do not have these disadvantages. However, the biggest disadvantage of functions is low execution efficiency (increasing the overhead of function calls and the difficulty of compiler optimization). +In light of this, you can use inline functions when necessary. Similar to macros, inline functions are expanded at the call point. The difference is that inline functions are expanded during compilation. + +Inline functions have the advantages of both functions and macros: +- Strict type checking is performed for inline functions. +- Parameters are evaluated only once for inline functions. +- Inline functions are expanded in place and there is no overhead for function calls. +- Inline functions are better optimized than standard functions. +For performance-sensitive code, consider using inline functions instead of standard functions. -int FunctionName() -{ - if (someThingError) { - ... -#ifdef HAS_SYSLOG // Good: Even in the function body, "#" is at the beginning of the line. - WriteToSysLog(); -#else - WriteToFileLog(); -#endif - } -} -``` -The nested preprocessor directives starting with `#` can be indented and aligned based on a standardized style. - -```cpp -#if defined(__x86_64__) && defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16) - #define ATOMIC_X86_HAS_CMPXCHG16B 1 // Good: wrapped for easier comprehension -#else - #define ATOMIC_X86_HAS_CMPXCHG16B 0 -#endif -``` +Exceptions: +In logging scenarios, only function-like macros can be used to keep information such as the file name (__FILE__) and line number (__LINE__) of the call point. ## Whitespace ### Rule 3.14.1 Ensure that horizontal spaces are used to highlight keywords and important information, and avoid unnecessary whitespace. @@ -682,7 +688,7 @@ switch (value) Note: Currently, all IDEs support automatic deletion of spaces at the end of a line. Please configure your IDE correctly. -### Recommendation 3.14.1 Use blank lines only when necessary to keep code compact. +### Rec 3.14.1 Use blank lines only when necessary to keep code compact. There must be as few blank lines as possible so that more code can be displayed for easy reading. Recommendations: - Add blank lines according to the correlation between lines. @@ -809,7 +815,11 @@ Note: Example code in this document uses comments in the `//` format only to bet */ ## Function Header Comments -### Rule 4.3.1 Function header comments with no content are forbidden. +### Rule 4.3.1 Write function header comments for public functions. +Public functions are interfaces provided by classes for external systems. To use public functions, the caller must understand the functionalities, parameter value ranges, return values, and precautions of the functions. +Write function header comments for the function value range, return value, and precautions, since they cannot be self-explained. + +### Rule 4.3.2 Function header comments with no content are forbidden. Not all functions need function header comments. For information that cannot be described by function signatures, add function header comments. @@ -911,7 +921,7 @@ int bar = 200; /* Comment on the right */ ``` It is more appealing sometimes when the comment is placed on the right of code and the comments and code are aligned vertically. After the alignment, ensure that the comment is 1–4 spaces away from the widest line of code. -For example: +Example: ```cpp const int A_CONST = 100; /* Related comments of the same type can be aligned vertically. */ @@ -925,10 +935,10 @@ The correct method is to delete unnecessary code directly. If necessary, conside Here, commenting out refers to the removal of code from compilation without actually deleting it. This is done by using /* */, //, #if 0, #ifdef NEVER_DEFINED, and so on. -### Recommendation 4.4.1 Delivered code cannot contain a TODO/TBD/FIXME comment. +### Rec 4.4.1 Delivered code cannot contain a TODO/TBD/FIXME comment. TODO/TBD comments are used to describe required improvements and supplements. FIXME comments are used to describe defects that need fixing. -They should have a standardized style, which facilitates text search. For example: +They should have a standardized style, which facilitates text search. Example: ```cpp // TODO(): XX @@ -942,12 +952,12 @@ A header file is an external interface of a module or file. The design of a head The interface declaration for most functions is more suitable placed in the header file, but implementation (except inline functions) cannot be placed in the header file. Functions, macros, enumerations, and structure definitions that need to be used in .cpp files cannot be placed in the header file. The header responsibility should be simple. An overly complex header file will make dependencies complex and cause long compilation times. -### Recommendation 5.1.1 Each .cpp file should have a .h file with the same name. It should be used to declare the classes and interfaces that need to be exposed externally. +### Rec 5.1.1 Each .cpp file should have a .h file with the same name. It should be used to declare the classes and interfaces that need to be exposed externally. Generally, each .cpp file has a corresponding .h file. This .cpp file is used to store the function declarations, macro definitions, and class definitions that are to be exposed. If a .cpp file does not need to open any interface externally, it should not exist. Exception: __An entry point (for example, the file where the main function is located), unit tests, and dynamic libraries __ -For example: +Example: ```cpp // Foo.h @@ -1059,7 +1069,7 @@ int Fun() } ``` In some scenarios, if internal functions need to be referenced with no intrusion to the code, the extern declaration mode can be used. -For example: +Example: When performing unit testing on an internal function, you can use the extern declaration to reference the tested function. When a function needs to be stubbed or patched, the function can be declared using extern. @@ -1106,10 +1116,10 @@ extern "C" { According to the author of a.h, the function Foo is a C++ free function following the "C++" link specification. However, because `#include "a.h"` is placed inside `extern "C"` in b.h, the link specification of function Foo is changed incorrectly. -Exception: +Exceptions: In the C++ compilation environment, if you want to reference the header file of pure C, the C header files should not contain `extern "C"`. The non-intrusive approach is to include the C header file in `extern "C"`. -### Recommendation 5.2.1 Use `#include` instead of a forward declaration to include header files. +### Rec 5.2.1 Use `#include` instead of a forward declaration to include header files. A forward declaration is for the declaration of classes, functions, and templates and is not meant for its definition. - Advantages: @@ -1129,7 +1139,7 @@ Therefore, we should avoid using forward declarations as much as possible. Inste ## Namespaces -### Recommendation 6.1.1 For code that does not need to be exported from the .cpp file, you are advised to use an unnamed namespace for encapsulation or use static to modify the variables, constants, or functions that need hiding. +### Rec 6.1.1 For code that does not need to be exported from the .cpp file, you are advised to use an unnamed namespace for encapsulation or use static to modify the variables, constants, or functions that need hiding. In the C++ 2003 standard, using static to modify the external availability of functions and variables was marked as deprecated. Therefore, unnamed namespaces are the recommended method. Main Reasons: @@ -1210,7 +1220,7 @@ namespace Foo { ## Global Functions and Static Member Functions -### Recommendation 6.2.1 Use namespaces to manage global functions. If global functions are closely tied to a class, you can use static member functions. +### Rec 6.2.1 Use namespaces to manage global functions. If global functions are closely tied to a class, you can use static member functions. Note: Placing non-member functions in a namespace avoids polluting the global scope. Do not use "class + static member function" to simply manage global functions. If a global function is closely tied to a class, it can be used as a static member function of the class. If you need to define some global functions for a .cpp file, use unnamed namespaces for management. @@ -1227,7 +1237,7 @@ public: ## Global Constants and Static Member Constants -### Recommendation 6.3.1 Use namespaces to manage global constants. If global constants are closely tied to a class, you can use static member constants. +### Rec 6.3.1 Use namespaces to manage global constants. If global constants are closely tied to a class, you can use static member constants. Note: Placing global constants in a namespace avoids polluting the global scope. Do not use "class + static member constant" to simply manage global constants. If a global constant is closely tied to a class, it can be used as a static member constant of the class. If you need to define some global constants only for a .cpp file, use unnamed namespaces for management. @@ -1244,7 +1254,7 @@ public: ## Global Variables -### Recommendation 6.4.1 Do not use global variables. Use the singleton pattern instead. +### Rec 6.4.1 Do not use global variables. Use the singleton pattern instead. Note: Global variables can be modified and read, which results in data coupling between production code and the global variables. ```cpp int g_counter = 0; @@ -1314,7 +1324,7 @@ Constructors, copy/move constructors, copy/move assignment operators, and destru ### Rule 7.1.1 The member variables of a class must be initialized explicitly. Note: If a class has members but no constructor and a default constructor is defined, the compiler will automatically generate a constructor, but it will not initialize member variables. The content of each object is uncertain. -Exception: +Exceptions: - If the member variables in a class have a default constructor, explicit initialization is not required. Example: The following code has no constructor, and private data members cannot be initialized: @@ -1323,7 +1333,7 @@ class Message { public: void ProcessOutMsg() { - //… + //... } private: @@ -1345,7 +1355,7 @@ public: void ProcessOutMsg() { - // … + // ... } private: @@ -1356,7 +1366,7 @@ private: }; ``` -### Recommendation 7.1.1 Initialization during declaration (C++ 11) and initialization using the constructor initialization list are preferred for member variables. +### Rec 7.1.1 Initialization during declaration (C++ 11) and initialization using the constructor initialization list are preferred for member variables. Note: Initialization during declaration (C++11) is preferred because initialized values of member variables can be easily understood. If initialized values of certain member variables are relevant to constructors, or C++ 11 is not supported, the constructor initialization list is used preferentially to initialize these member variables. Compared with the assignment statements in constructors, code of the constructor initialization list is simpler and has higher performance, and can be used to initialize constant and reference members. ```cpp @@ -1417,6 +1427,29 @@ private: ``` 2. Use delete provided by C++ 11. For details, see Rule 10.1.3 in chapter 10 Modern C++ Features. + +3. You are advised to inherit **NoCopyable** and **NoMovable**. Do not use macros such as **DISALLOW_COPY_AND_MOVE**, **DISALLOW_COPY**, and **DISALLOW_MOVE**. +```cpp +class Foo : public NoCopyable, public NoMovable { +}; +``` +Implementation of NoCopyable and NoMovable: +```cpp +class NoCopyable { +public: + NoCopyable() = default; + NoCopyable(const NoCopyable&) = delete; + NoCopyable& operator = (NoCopyable&) = delete; +}; + +class NoMovable { +public: + NoMovable() = default; + NoMovable(NoMovable&&) noexcept = delete; + NoMovable& operator = (NoMovable&&) noexcept = delete; +}; +``` + ### Rule 7.1.4 Copy constructors and copy assignment operators should be implemented or forbidden together. Both copy constructors and copy assignment operators provide copy semantics. They should be implemented or hidden together. @@ -1502,10 +1535,40 @@ When running the following statement: The constructor of the derived class is executed first. However, the constructor of the base class is called first. Because the constructor of the base class calls the virtual function log, the log is in the base class version. The derived class is constructed only after the base class is constructed. As a result, behaviors of non-polymorphism are caused. This also applies to destructors. +### Rule 7.1.7 The copy constructors, copy assignment operators, move constructors, and move assignment operators in polymorphic base classes must be non-public or delete functions. +Slicing occurs if the value of a derived class object is directly assigned to a base class object. In this case, only the base class part is copied or moved, which undermines polymorphism. +[Counterexample] +In the following code example, the copy constructor and copy assignment operator are not defined in the base class. The compiler automatically generates two special member functions. +If the value of a derived class object is assigned to the base class object, slicing occurs. The copy constructor and copy assignment operator can be declared as **deleted** so that the compiler can check such assignment behavior. +```cpp +class Base { +public: + Base() = default; + virtual ~Base() = default; + ... + virtual void Fun() { std::cout << "Base" << std::endl;} +}; + +class Derived : public Base { + ... + void Fun() override { std::cout << "Derived" << std::endl; } +}; + +void Foo(const Base &base) +{ + Base other = base; // Bad: Slicing occurs + other.Fun(); // The Fun() function of the base class is called. +} +``` +```cpp +Derived d; +Foo(d); // A derived class object is passed. +``` +1. Set copy constructors or copy assignment operators to **private** and do not implement them. ## Inheritance -### Rule 7.2.1 Destructors of a base class should be declared as virtual. +### Rule 7.2.1 Declare destructors of a base class as virtual, and declare the class that is not to be inherited as final. Note: Destructors of the derived class can be called during polymorphism invocation only when destructors of the base class are virtual. Example: There will be memory leak if destructors of the base class are not declared as virtual. @@ -1564,7 +1627,8 @@ int main(int argc, char* args[]) } ``` Because destructors of the base class are not declared as virtual, only destructors of the base class are called when an object is destroyed. Destructors of the derived class Sub are not called. As a result, a memory leak occurs. - +Exceptions: +For classes such as **NoCopyable** and **NoMovable** that have no behavior and are used only as identifiers, you do not need to define them as final. ### Rule 7.2.2 Do not use default parameter values for virtual functions. Note: In C++, virtual functions are dynamically bound, but the default parameters of functions are statically bound during compilation. This means that the function you finally execute is a virtual function that is defined in the derived class but uses the default parameter value in the base class. To avoid confusion and other problems caused by inconsistent default parameter declarations during overriding of virtual functions, it is prohibited to declare default parameter values for all virtual functions. @@ -1642,7 +1706,7 @@ Multiple inheritance provides a simpler method for assembling and reusing multip Therefore, multiple inheritance can be used only in the following cases: -### Recommendation 7.3.1 Use multiple inheritance to implement interface separation and multi-role combination. +### Rec 7.3.1 Use multi-inheritance to implement interface separation and multi-role combination. If a class requires multiple interfaces, combine multiple separated interfaces by using multiple inheritance. This is similar to the Traits mixin of the Scala language. ```cpp @@ -1695,7 +1759,7 @@ It is recommended that you split a long function into several functions that are ## Inline Functions -### Recommendation 8.2.1 An inline function cannot exceed 10 lines. +### Rec 8.2.1 An inline function cannot exceed 10 lines. **Note**: An inline function has the same characteristics of a normal function. The difference between an inline function and a normal function lies in the processing of function calls. When a general function is called, the program execution right is transferred to the called function, and then returned to the function that calls it. When an inline function is called, the invocation expression is replaced with an inline function body. Inline functions are only suitable for small functions with only 1-10 lines. For a large function that contains many statements, the function call and return overheads are relatively trivial and do not need the help of an inline function. Most compilers may abandon the inline mode and use the common method to call the function. @@ -1705,7 +1769,7 @@ If an inline function contains complex control structures, such as loop, branch ## Function Parameters -### Recommendation 8.3.1 Use a reference instead of a pointer for function parameters. +### Rec 8.3.1 Use a reference instead of a pointer for function parameters. **Note**: A reference is more secure than a pointer because it is not empty and does not point to other targets. Using a reference stops the need to check for illegal null pointers. @@ -1714,7 +1778,7 @@ Use const to avoid parameter modification, so that readers can clearly know that Exception: When the input parameter is an array with an unknown compile-time length, you can use a pointer instead of a reference. -### Recommendation 8.3.2 Use strongly typed parameters. Do not use void*. +### Rec 8.3.2 Use strongly typed parameters. Do not use void*. While different languages have their own views on strong typing and weak typing, it is generally believed that C and C++ are strongly typed languages. Since we use such a strongly typed language, we should keep to this style. An advantage of this is the compiler can find type mismatch problems at the compilation stage. @@ -1749,7 +1813,7 @@ void MakeTheList() 1. You can use a template function to change the parameter type. 2. A base class pointer can be used to implement this according to polymorphism. -### Recommendation 8.3.3 A function can have a maximum of five parameters. +### Rec 8.3.3 A function can have a maximum of five parameters. If a function has too many parameters, it is apt to be affected by external changes, and therefore maintenance is affected. Too many function parameters will also increase the testing workload. If a function has more than five parameters, you can: @@ -1776,7 +1840,7 @@ const int MAX_MSISDN_LEN = 20; // Good constexpr int MAX_MSISDN_LEN = 20; ``` -### Recommendation 9.1.1 A group of related integer constants must be defined as an enumeration. +### Rec 9.1.1 A group of related integer constants must be defined as an enumeration. **Note**: Enumerations are more secure than `#define` or `const int`. The compiler checks whether a parameter value is within the enumerated value range to avoid errors. @@ -1900,7 +1964,7 @@ Even if a class of the aggregate type is directly copied and compared, and any f For details about the POD type, see the appendix. -### Recommendation 9.1.2 Declare and initialize variables only when they are used. +### Rec 9.1.2 Declare and initialize variables only when they are used. **Note**: It is a common low-level programming error that a variable is not assigned an initial value before being used. Declaring and initializing a variable just before using it will prevent this. @@ -1951,7 +2015,7 @@ x = Func(i, i); ### Rule 9.2.2 A switch statement must have a default branch. In most cases, a switch statement requires a default branch to ensure that there is a default action when the case tag is missing for a processed value. -Exception: +Exceptions: If the switch condition variables are enumerated and the case branch covers all values, the default branch is redundant. Because modern compilers can check which case branches are missing in the switch statement and provide an advanced warning. @@ -1973,7 +2037,7 @@ switch (color) { } ``` -### Recommendation 9.2.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged. +### Rec 9.2.1 When comparing expressions, follow the principle that the left side tends to change and the right side tends to remain unchanged. When a variable is compared with a constant, placing the constant on the left, for example, if (MAX == v), does not comply with standard reading habits and is more difficult to understand. The constant should be placed on the right. The expression is written as follows: ```cpp @@ -1989,7 +2053,7 @@ There are special cases: for example, if the expression `if (MIN < value && valu You do not need to worry about writing '==' as '=' because a compilation alarm will be generated for `if (value = MAX)` and an error will be reported by other static check tools. Use these tools to solve such writing errors and ensure that that code is readable. -### Recommendation 9.2.2 Use parentheses to specify the operator precedence. +### Rec 9.2.2 Use parentheses to specify the operator precedence. Use parentheses to specify the operator precedence. This will prevent program errors due to the inconsistency between default priority and the intended design. At the same time, it makes the code clearer and more readable. However, too many parentheses muddy the code, reducing readability. The following is a recommendation on their correct usage. - For binary and ternary operators, if multiple operators are involved, parentheses should be used. @@ -2033,15 +2097,15 @@ The type casting provided by C++ is more targeted, easy to read, and more secure int64_t i{ someInt32 }; ``` -### Recommendation 9.3.1 Avoid using `dynamic_cast`. +### Rec 9.3.1 Avoid using `dynamic_cast`. 1. `dynamic_cast` depends on the RTTI of C++ so that the programmer can identify the type of the object in C++ at run time. 2. `dynamic_cast` indicates that a problem has occurred in the design of the base class and derived class.The derived class destroys the contract of the base class and it is necessary to use `dynamic_cast` to convert the class to a subclass for special processing. In this case, it is more desirable to improve the design of the class, instead of using `dynamic_cast` to solve the problem. -### Recommendation 9.3.2 Avoid using `reinterpret_cast`. +### Rec 9.3.2 Avoid using `reinterpret_cast`. **Note**: `reinterpret_cast` is used to convert irrelevant types. Trying to use `reinterpret_cast` to force a type to another type destroys the security and reliability of the type and is an insecure casting method. Avoid casting between completely different types. -### Recommendation 9.3.3 Avoid using `const_cast`. +### Rec 9.3.3 Avoid using `const_cast`. **Note**: The `const_cast` command is used to remove the `const` and `volatile` properties of an object. @@ -2109,7 +2173,7 @@ delete[] numberArray; numberArray = NULL; ``` -### Recommendation 9.4.1 Use the RAII feature to trace dynamic allocation. +### Rec 9.4.1 Use the RAII feature to trace dynamic allocation. Note: RAII is an acronym for Resource Acquisition Is Initialization. It is a simple technology that controls program resources (such as memory, file handle, network connections, and mutexes) by using the object lifecycle. @@ -2125,12 +2189,12 @@ class LockGuard { public: LockGuard(const LockType& lockType): lock_(lockType) { - lock_.Acquire(); + lock_.Aquire(); } ~LockGuard() { - lock_.Release(); + lock_.Relase(); } private: @@ -2187,10 +2251,10 @@ void Fun2() Exception: In rare cases where high performance coding is required , you can temporarily save the pointer returned by string::c_str() to match the existing functions which support only the input parameters of the const char* type. However, you should ensure that the lifecycle of the string object is longer than that of the saved pointer, and that the string object is not modified within the lifecycle of the saved pointer. -### Recommendation 9.5.1 Use std::string instead of char*. +### Rec 9.5.1 Use std::string instead of char*. Note: Using string instead of `char*` has the following advantages: -1. There is no need to consider the null character ’\0’at the end. +1. There is no need to consider the null character '\0' at the end. 2. You can directly use operators such as `+`, `=`, and `==`, and other character and string operation functions. 3. There is no need to consider memory allocation operations.This helps avoid explicit usage of `new` and `delete` and the resulting errors. @@ -2216,7 +2280,7 @@ Exception: Before the C++ 11 standard is widely used, std::auto_ptr can be used in scenarios where ownership needs to be transferred. However, it is recommended that std::auto_ptr be encapsulated. The copy constructor and assignment operator of the encapsulation class should not be used in a standard container. -### Recommendation 9.5.2 Use the new standard header files. +### Rec 9.5.2 Use the new standard header files. Note: When using the standard header file of C++, use `` instead of ``. @@ -2257,7 +2321,7 @@ private: }; ``` -### Recommendation 9.6.1 Member variables that will not be modified after initialization should be defined as constants. +### Rec 9.6.1 Member variables that will not be modified after initialization should be defined as constants. ```cpp class Foo { @@ -2270,7 +2334,7 @@ private: ## Exceptions -### Recommendation 9.7.1 If the function does not throw an exception, the declaration is `noexcept`. +### Rec 9.7.1 If the function does not throw an exception, the declaration is `noexcept`. **Reasons:** 1. If the function does not throw an exception, the declaration is `noexcept`, which enables the compiler to optimize the function to the maximum extent, for example, reducing the execution paths and improving the efficiency of exiting when an error occurs. 2. For STL containers such as `vector`, to ensure the interface robustness, if the `move ` constructor of saved items is not declared as `noexcept`, the `copy machanism` instead of the `move machanism` is used when the items are removed from the container. This would cause performance loss risks. If the function does not throw an exception, or a program does not intercept and process an exception thrown by the function, new `noexcept` keywords can be used to modify the function, indicating that the function does not throw an exception or the thrown exception is not intercepted or processed. For example: @@ -2317,21 +2381,26 @@ a2.push_back(Foo2()); //Triggers container expansion and invokes the move constr **Note** The default constructor, destructor, `swap` function, and `move` operator should not throw an exception. -## Templates +## Templates and Generic Programming -Template programming allows for extremely flexible interfaces that are type safe and high performance, enabling reuse of code of different types but with the same behavior. +### Rule 9.8.1 Do not use generic programming. +OpenHarmony adopts object-oriented programming, which has ideas, concepts, and techniques totally different from those of generic programming. -The disadvantages of template proramming are as follows: +Generic programming in C++ allows for extremely flexible interfaces that are type safe and high performance, enabling reuse of code of different types but with the same behavior. -1. The techniques used in template programming are often obscure to anyone but language experts. Code that uses templates in complicated ways is often unreadable, and is hard to debug or maintain. -2. Template programming often leads to extremely poor compiler time error messages: even if an interface is simple, complicated implementation details become visible when the user does something wrong. -3. If the template is not properly used, the code will be over expanded during runtime. -4. It is difficult to modify or refactor template code. The template code is expanded in multiple contexts, and it is hard to verify that the transformation makes sense in all of them. +However, generic programming has the following disadvantages: -Therefore, it is recommended that __ template programming be used only in a small number of basic components and basic data structure__. When using the template programming, minimize the __ complexity as much as possible, and __ avoid exposing the template__. It is better to hide programming as an implementation detail whenever possible, so that user-facing headers are readable. And you should write sufficiently detailed comments for code that uses templates. +1. People who are not familiar with generic programming often write into templates object-oriented logic or members that do not depend on template parameters, making the code unreadable or bloated. +2. The techniques used in generic programming are often obscure to anyone but language experts. Template code can be unreadable in certain cases. +3. Generic programming often leads to extremely poor compile time error messages. The uncalled-for implementation details of APIs are displayed to users in the error messages, making even a simple API difficult to debug. +4. Inappropriate use of templates cause code bloat during runtime. +5. It is difficult to modify or refactor the template code. The template code is expanded in multiple contexts, and it is hard to verify that the code refactoring makes sense in all of them. +Only __a few components of OpenHarmony__ support generic programming, and the templates developed using generic programming must have detailed comments. +Exceptions: +1. The STL adaptation layer can use generic programming. -## Macros +## Macros In the C++ language, it is strongly recommended that complex macros be used as little as possible. - For constant definitions, use `const` or `enum` as stated in the preceding sections. - For macro functions, try to be as simple as possible, comply with the following principles, and use inline functions and template functions for replacement. @@ -2353,7 +2422,7 @@ As the ISO released the C++ 11 language standard in 2011 and released the C++ 17 This chapter describes some guidelines for modern C++ use, to avoid language pitfalls. ## Code Simplicity and Security Improvement -### Recommendation 10.1.1 Use `auto` properly. +### Rec 10.1.1 Use `auto` properly. **Reasons** * `auto` can help you avoid writing verbose, repeated type names, and can also ensure initialization when variables are defined. @@ -2593,26 +2662,53 @@ void func() ``` ## Smart Pointers -### Rule 10.2.1 Use smart pointers instead of a raw pointer to manage resources. +### Rule 10.2.1 Preferentially use the original pointer source instead of the smart pointer for singletons and class members that are not held by multiple parties. **Reason:** -Avoid resource leakage. +Smart pointers automatically release object resources to prevent resource leakage, but they require extra resource overheads. For example, the classes, constructors, and destructors automatically generated by smart pointers consume more resources such as memory. + +When singletons, class members, and the like are not held by multiple parties, resources can be released only in class destructors. In this case, smart pointers should not be used. **Example:** ```cpp -void Use(int i) -{ - auto p = new int {7}; // Bad: Initializing local pointers with new. - auto q = std::make_unique(9); // Good: Guarantee that memory is released. - if (i > 0) { - return; // Return and possible leak. +class Foo; +class Base { +public: + Base() {} + virtual ~Base() + { + delete foo_; } - delete p; // Too late to salvage. -} +private: + Foo* foo_ = nullptr; +}; ``` -**Exception:** -Raw pointers can be used in scenarios requiring high performance and compatibility. +**Exceptions** +1. When a created object is returned, a smart pointer can be used if the pointer destructor is required. +```cpp +class User; +class Foo { +public: + std::unique_ptr CreateUniqueUser() // Use unique_ptr to ensure that the object is created and released in the same runtime. + { + sptr ipcUser = iface_cast(remoter); + return std::unique_ptr(::new User(ipcUser), [](User *user) { + user->Close(); + ::delete user; + }); + } + + std::shared_ptr CreateSharedUser() // Use shared_ptr to ensure that the object is created and released in the same runtime. + { + sptr ipcUser = iface_cast(remoter); + return std::shared_ptr(ipcUser.GetRefPtr(), [ipcUser](User *user) mutable { + ipcUser = nullptr; + }); + } +}; +``` +2. When the created object is returned and needs to be referenced by multiple parties, `shared_ptr` can be used. ### Rule 10.2.2 Use `unique_ptr` instead of `shared_ptr`. **Reasons:** @@ -2620,7 +2716,7 @@ Raw pointers can be used in scenarios requiring high performance and compatibili 2. Shared ownership in some cases (such as circular dependency) may create objects that can never be released. 3. Shared ownership can be an attractive alternative to careful ownership design but it may obfuscate the design of a system. -### Rule 10.2.3 Use `std::make_unique` instead of `new` to create a `unique_ptr`. +### Rule 10.2.2 Use `std::make_unique` instead of `new` to create a `unique_ptr`. **Reasons:** 1. `make_unique` provides a simpler creation method. 2. `make_unique` ensures the exception safety of complex expressions. @@ -2654,7 +2750,7 @@ F(make_unique(), Bar()); **Exception:** `std::make_unique` does not support user-defined `deleter`. -In the scenario where the `deleter` needs to be customized, it is recommended that `make_unique` be implemented in the customized version’s own namespace. +In the scenario where the `deleter` needs to be customized, it is recommended that `make_unique` be implemented in the customized version's own namespace. Using `new` to create `unique_ptr` with the user-defined `deleter` is the last choice. ### Rule 10.2.4 Create `shared_ptr` by using `std::make_shared` instead of `new`. @@ -2670,7 +2766,7 @@ When `std::make_shared` creates `std::shared_ptr`, it allocates sufficient memor Similar to `std::make_unique`, `std::make_shared` does not support `deleter` customization. ## Lambda -### Recommendation 10.3.1 Use `lambda` to capture local variables or write local functions when normal functions do not work. +### Rec 10.3.1 Use `lambda` to capture local variables or write local functions when normal functions do not work. **Reason:** Functions cannot capture local variables or be declared at local scope. If you need those things, choose `lambda` instead of handwritten `functor`. On the other hand, `lambda` and `functor` objects do not support overloading. If overloading is required, use a function. @@ -2720,7 +2816,7 @@ void Foo() } ``` -### Recommendation 10.3.2 All variables are explicitly captured if `this` is captured. +### Rec 10.3.2 All variables are explicitly captured if `this` is captured. **Reason:** The `[=]` in the member function seems to indicate capturing by value but actually it is capturing data members by reference because it captures the invisible `this` pointer by value. Generally, it is recommended that capturing by reference be avoided. If it is necessary to do so, write `this` explicitly. @@ -2748,11 +2844,11 @@ private: }; ``` -### Recommendation 10.3.3 Avoid default capture modes. +### Rec 10.3.3 Avoid default capture modes. **Reason:** The lambda expression provides two default capture modes: by-reference (&) and by-value (=). By default, the "by-reference" capture mode will implicitly capture the reference of all local variables, which will easily lead to dangling references. By contrast, explicitly writing variables that need to be captured can make it easier to check the lifecycle of an object and reduce the possibility of making a mistake. -By default, the "by-value” capture mode will implicitly capture this pointer, and it is difficult to find out which variables the lambda function depends on. If a static variable exists, the reader mistakenly considers that the lambda has copied a static variable. +By default, the "by-value" capture mode will implicitly capture this pointer, and it is difficult to find out which variables the lambda function depends on.If a static variable exists, the reader mistakenly considers that the lambda has copied a static variable. Therefore, it is required to clearly state the variables that lambda needs to capture, instead of using the default capture mode. **Bad example:** @@ -2786,7 +2882,7 @@ auto func() Reference: Effective Modern C++: Item 31: Avoid default capture modes. ## Interfaces -### Recommendation 10.4.1 Use `T*` or `T&` arguments instead of a smart pointer in scenarios where ownership is not involved. +### Rec 10.4.1 Use `T*` or `T&` arguments instead of a smart pointer in scenarios where ownership is not involved. **Reasons:** 1. Passing a smart pointer to transfer or share ownership should only be used when the ownership mechanism is explicitly required. 2. Passing a smart pointer (for example, passing the `this` smart pointer) restricts the use of a function to callers using smart pointers. @@ -2818,4 +2914,3 @@ void F(shared_ptr& w) // ... }; ``` - diff --git a/en/contribute/OpenHarmony-security-design-guide.md b/en/contribute/OpenHarmony-security-design-guide.md index e7ef720f079334307ae67ab11cb314c2519ca895..aa6e19a89ccd166d16f0617c69ade02f61b3a84d 100644 --- a/en/contribute/OpenHarmony-security-design-guide.md +++ b/en/contribute/OpenHarmony-security-design-guide.md @@ -46,9 +46,9 @@ The following are some examples of insecure cipher algorithms: MD5, DES, 3DES (D (3) **java.security.SecureRandom** of the JDK (4) **/dev/random** file of Unix-like platforms -3-4 By default, use secure cipher algorithms and disable/prohibit insecure cipher algorithms. Use cipher algorithm libraries that are certified by authoritative organizations, recognized by open-source communities in the industry, or assessed and approved by Huawei +3-4 By default, use secure cipher algorithms and disable/prohibit insecure cipher algorithms. Use cipher algorithm libraries that are certified by authoritative organizations, recognized by open-source communities in the industry, or assessed and approved by OpenHarmony. -**Description:** In the context of advances in cryptographic technologies and enhancement in computing capabilities, some cipher algorithms may become insecure. Using such algorithms may bring risks to user data. In addition, unknown flaws may exist in cipher algorithms that are developed by amateurs and not analyzed/verified by the industry. In this regard, use cipher algorithm libraries that are certified by authoritative organizations, recognized by open-source communities in the industry, or assessed and approved by Huawei. +**Description:** In the context of advances in cryptographic technologies and enhancement in computing capabilities, some cipher algorithms may become insecure. Using such algorithms may bring risks to user data. In addition, unknown flaws may exist in cipher algorithms that are developed by amateurs and not analyzed/verified by the industry. In this regard, use cipher algorithm libraries that are certified by authoritative organizations, recognized by open-source communities in the industry, or assessed and approved by OpenHarmony. **Example:** For examples of cipher algorithms, see 3-1. diff --git a/en/contribute/Readme-EN.md b/en/contribute/Readme-EN.md index e1cc5652e4436769cb38126b318a0d587177a3fc..8ac3b563d2274fdea813fd8eb8a4ac80917ab04f 100755 --- a/en/contribute/Readme-EN.md +++ b/en/contribute/Readme-EN.md @@ -4,6 +4,7 @@ - [Code of Conduct](code-of-conduct.md) - [Code Contribution](code-contribution.md) - [Contribution Process](contribution-process.md) +- [Auto-Test](../readme/test_subsystem.md) - [Documentation Contribution](documentation-contribution.md) - [Writing Instructions](writing-instructions.md) - [Communication in Community](communication-in-community.md) diff --git a/en/contribute/code-contribution.md b/en/contribute/code-contribution.md index 740bee3e7dde41847347ebb2ff1925ff8b6f20b6..923c335c3754c54d8e82246eb1686ea2a69b9520 100644 --- a/en/contribute/code-contribution.md +++ b/en/contribute/code-contribution.md @@ -2,7 +2,13 @@ ## Start Contributions -**Code Style** +### Design Specifications + +- [OpenHarmony API Governance Charter](../design/OpenHarmony-API-governance.md) + +- [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md) + +### Code Style Develop, review, and test code following the OpenHarmony coding standards. Make sure code is written in the same style. @@ -12,6 +18,7 @@ Develop, review, and test code following the OpenHarmony coding standards. Make - [Python Coding Style Guide](https://pep8.org/) - [C&C++ Secure Coding Guide](OpenHarmony-c-cpp-secure-coding-guide.md) - [Java Secure Coding Guide](OpenHarmony-Java-secure-coding-guide.md) +- [Logging Guide](OpenHarmony-Log-guide.md) ## Contribution Workflow diff --git a/en/contribute/contribution-process.md b/en/contribute/contribution-process.md index 9fa4be4fa4e8beb8051004e43408982a084fffa9..de1dc328fe27122ddc3b5a9f977b75709c74782e 100755 --- a/en/contribute/contribution-process.md +++ b/en/contribute/contribution-process.md @@ -242,7 +242,7 @@ Visit [CI portal](http://ci.openharmony.cn/#/pipeLine). ## Reviewing Code -For details, visit [https://gitee.com/help/articles/4304](https://gitee.com/help/articles/4304). +For details, visit [https://gitee.com/help/articles/4304](https://gitee.com/help/articles/4304). -Related topic: [FAQs](faqs.md) +Related topic: [FAQs](faqs.md) diff --git a/en/contribute/contribution.md b/en/contribute/contribution.md index 0b954ea421d608e49e289329bea05441bdb8d5e2..2819f40f16c3eaa4ff1454f9d475fe372d39c874 100755 --- a/en/contribute/contribution.md +++ b/en/contribute/contribution.md @@ -22,6 +22,10 @@ For details about how to participate in Special Interest Group (SIG), see **SIG For details about how to contribute to code, see [Code Contributing ](code-contribution.md). +## Auto-Test + +For details about how to develop test cases based on test requirements, see [Test Subsystem](../readme/test_subsystem.md). + ## Contributing Documents For details, see [Documentation Contribution](documentation-contribution.md). diff --git a/en/contribute/template/figures/figure01.png b/en/contribute/template/figures/figure01.png new file mode 100644 index 0000000000000000000000000000000000000000..df3c115b78a0c8bb792c704735dd6e213a2d1e6c Binary files /dev/null and b/en/contribute/template/figures/figure01.png differ diff --git a/en/contribute/template/figures/figure02.png b/en/contribute/template/figures/figure02.png new file mode 100644 index 0000000000000000000000000000000000000000..159b193f425237a47ca351a8d093060a08f27d20 Binary files /dev/null and b/en/contribute/template/figures/figure02.png differ diff --git a/en/contribute/template/js-template.md b/en/contribute/template/js-template.md new file mode 100644 index 0000000000000000000000000000000000000000..e9075f5d26e5a2b454bf78e77a280c907355b307 --- /dev/null +++ b/en/contribute/template/js-template.md @@ -0,0 +1,228 @@ +# JS API Reference Template + +> *Writing Instructions* +> +> 0.1 - Delete all writing instructions after you finish the writing. +> +> 0.2 - Upload JS API reference documents to **docs/en/application-dev/reference/apis**. If these documents contain figures, upload the figures to the **figures** folder. +> +> 0.3 - Use a .d.ts file for a JS API reference document. **The file name must be in the following format: js-apis-.md**. Examples: +> +> ​ For @ohos.multimedia.audio in the Media subsystem, the file name is **js-apis-audio.md**. +> +> ​ For @ohos.telephony.sms in the Telephony subsystem, the file name is **js-apis-sms.md**. +> +> 0.4 - After uploading a JS API reference document, update the **Readme-EN.md** file in **docs/en/application-dev/reference/apis**. +> +> 0.5 - **Document Title**: Use phrases that summarize the module functionalities. +> +> 0.6 - Use the document title as the level-1 heading. Use the attributes, functions, classes, interfaces, enums, and types under the namespace as level-2 headings. Use the attributes and functions under classes as level-3 headings. +> +> 0.7 - **When introducing an API to an existing module, use the \ tag to mark its earliest version.** +> +> ​ Example: For an existing module of API 6, if an attribute is added in API 7, suffix the \ tag to the name of the new attribute, for example, **newAttribute7+**. +> +> ​ If a method is added, suffix the \ tag to the method name, for example, **sim.getSimIccId7+**. The processing of new interfaces, classes, and enums is similar. +> +> 0.8 - **Deprecated content**: Do not delete the deprecated content directly from the document. Instead, suffix **deprecated** as a superscript to the content, and use the greater-than symbol (>) to introduce the substitute method plus the corresponding link. +> +> ​ Example: abandonmentMethod(deprecated) +> +> > Discarded. This change is effective since API version 7. You are advised to use [newMethod](#newMethod) instead. +> +> The following describes the instructions for writing a specific API. + +*** +> *Writing Instructions* +> +> 1.1 - Use the greater-than symbol (>) to describe the initial version of an API. +> +> 1.2 - A module has only one initial version. +> +> 1.3 - Use the following sentence: "The initial APIs of this module are supported since API version ***x***. Newly added APIs will be marked with a superscript to indicate their earliest API version." Change ***x*** to the actual version. + + +> **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. + +Describe the module from its functionalities, use cases, and use suggestions in this section. + +## Modules to Import +> *Writing Instructions* +> +> 2.1 - Write the modules to import based on the actual conditions. Provide the **import** statement in the form of a code segment. +> +> 2.2 - If no module needs to be imported, change "Modules to Import" to "How to Use" and provide a usage description. +> +> ​ Example of **How to Use**: +> +> ​ Before using the **AbilityContext**, obtain the **Context** object through **[getContext()]**(***API-reference***.md). +> ```js +> import ability_featureAbility from '@ohos.ability.featureAbility'; +> var context = ability_featureAbility.getContext(); +> ``` + +```js +import call from '@ohos.telephony.call'; +``` + +## Attributes + +> *Writing Instructions* +> +> 4.1 - Optional. Delete this heading if there is no attribute. +> +> 4.2 - If an attribute is of a custom type, create a link to the corresponding interface or enum. +> +> 4.3 - For a readable attribute, if it has a limited number of values with special meanings, enumerate the values. +> +> 4.4 - For a writable attribute, if only fixed fields are supported, describe them. + +| Name| Type| Readable| Writable| Description| +| ---------------- | ----------------------------------------- | ---- | ---- | ------------------------------------------ | +| pluggedType | [BatteryPluggedType](#BatteryPluggedType) | Yes| No| Charger type of the current device.| +| isBatteryPresent | boolean | Yes| No| Whether the battery is supported or present.| + +## Enums + +> *Writing Instructions* +> +> 5.1 - Optional. Delete this heading if there is no enum. If there are multiple enums, describe them in separate level-2 headings. To create a level-2 heading, use two number signs (#). +> +> 5.2 - Use the actual enum name as the level-2 heading, for example, **BatteryHealthState**. + +Provide a brief description of the enum type. Example: Enumerates charger types. + +| Name| Value| Description| +| ---- | ---- | -------------------------- | +| NONE | 1 | Unknown type.| + +## Methods + +> *Writing Instructions* +> +> 6.1 - Optional. Delete this heading if there is no method. If there are multiple methods, describe them in separate level-2 headings. To create a level-2 heading, use two number signs (#). +> +> 6.2 - Use the actual method name, in the format of ClassName.methodName, as the level-2 heading. For a subscription method, add the subscription event to the method name. +> +> ​ Example of a common method: sim.getSimIccId +> +> ​ Example of a subscription method: sim.on('exampleEvent') +> +> 6.3 - **Method calling mode**: The description must be the same as that in the .d.ts file. The description must include the parameter type, parameter name, and return value type. +> +> ​ Example: getNetworkState(slotId: number, callback: AsyncCallback\): void +> +> ​ Note: The angle bracket (<>) may be identified as a label and not displayed. To ensure normal display, you can either add a backslash (\\) (in the format of "\\<>") or use escape characters \< and \>. +> +> 6.4.1 - **Method description**: Describe the features implemented by the method and include the prerequisites for using the method, the impact of the method, and the permissions required to use the command. (*Example of prerequisites: The method can be called only after the xx method is called; you must ensure that the connection to the Internet is normal. Example of impact: xx does not take effect after this method is called.*) +> +> 6.4.2 - **Asynchronous method**: If there are asynchronous methods, describe their return type in the method description. The return type can be a callback function or a **Promise** instance. +> +> 6.4.3 - **Line feed in a table**: Use \
for line feed. + +Provide the method name in the following format: (**static** if it is a static method) methodName (parameterName1: parameterType1, parameterName2: parameterType2, ...): returnValueType + +Describe the method. For details, see 6.4.1 and 6.4.2. + +Required permission: ohos.permission.XXX (Delete this part if no permission is involved. If a system permission is required, describe it.) + +**Parameters: ** (Optional. Delete this heading if there is no parameter.) + +| Name| Type| Mandatory| Description| +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| parameterOne | number \| string \| [CustomType](#CustomType) | Yes| Describe the parameter. Provide the value range and recommended value. If there is a fixed format, provide a format example, especially for the URI.
Provide a link for any custom parameter type.| +| callback | Callback\> | No| Describe the parameter. For an optional parameter, describe the consequences if it is not specified.
Example: If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Return values**: (Optional. Delete this heading if there is no return value.) + +| Type| Description| +| ------------------------------------------ | -------------------------------------------- | +| string | Describe the return value, for example, what can be done after the return value is obtained.| +| Promise\> | Describe the return value, for example, what is obtained through the **Promise** instance.| + +**Example:** + +```js +// This part is mandatory. +// Check all sample code provided in the example. +// Minor errors such as missing symbols and variable inconsistency are unacceptable. +// Declare all variables that are used. +// Write an actual case that can be easily used, rather than the parameter names themselves. +// Use comments to describe the content that are not user-defined. +// Example: var result = xxx.createExample(parameterOne); // parameterOne is automatically obtained by scanning. +``` + +## Classes/Interfaces + +> *Writing Instructions* +> +> 7.1 - Optional. Delete this heading if there is no class or interface. If there are multiple classes or interfaces, describe them in multiple level-2 headings. To create a level-2 heading, use two number signs (#). +> +> 7.2 - Use the actual class or interface name as the level-2 heading. +> +> 7.3 - If the class or interface contains both attributes and methods, write the attributes above the methods. Write their actual names in separate level-3 headings. +> +> ​ If the class of interface contains only attributes, you do not need to create a level-3 heading. Instead, use a table to display the attributes. For details, see [CustomType](#CustomType). + +Describe the class or interface. If there are usage restrictions, describe them as well, for example, whether there is a prerequisite and whether an instance needs to be created by using any method. + +### Attributes + +> *Writing Instructions* +> +> Except that a level-3 heading is used, other instructions are the same as those listed under [Attributes](#Attributes). + +### Methods in Classes/Interfaces + +> *Writing Instructions* +> +> 7.4 - Use the actual method name as the level-3 heading. **Do not add a prefix**. For a subscription method, add the corresponding subscription event to the method name. +> +> ​ Example of a common method: getSimIccId +> +> ​ Example of a subscription method: on('exampleEvent') +> +> The other instructions are the same as those stipulated in [Methods](#Methods). + +Describe the method calling mode. For details, see 6.3. + +Describe the method. For details, see 6.4.1 and 6.4.2. + +Required permission: ohos.permission.XXX (Delete this part if no permission is involved. If a system permission is required, describe it.) + +**Parameters: ** (Optional. Delete this heading if there is no parameter.) + +| Name| Type| Mandatory| Description| +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| parameterOne | number \| string \| [CustomType](#CustomType) | Yes| Describe the parameter. Provide the value range and recommended value. If there is a fixed format, provide a format example, especially for the URI.
Provide a link for any custom parameter type.| +| callback | Callback\> | No| Describe the parameter. For an optional parameter, describe the consequences if it is not specified.
Example: If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| + +**Return values**: (Optional. Delete this heading if there is no return value.) + +| Type| Description| +| ------------------------------------------ | -------------------------------------------- | +| string | Describe the return value, for example, what can be done after the return value is obtained.| +| Promise\> | Describe the return value, for example, what is obtained through the **Promise** instance.| + +**Example:** + +```js +// This part is mandatory. +// Check all sample code provided in the example. +// Minor errors such as missing symbols and variable inconsistency are unacceptable. +// Declare all variables that are used. +// Write an actual case that can be easily used, rather than the parameter names themselves. +// Use comments to describe the content that are not user-defined. +// Example: var result = xxx.createExample(parameterOne); // parameterOne is automatically obtained by scanning. +``` + +## CustomType + +The following is an example of the custom type of a key-value pair. + +| Name| Type| Readable|Writable| Description| +| ------------ | ---- | ---- | ---- | ---- | +| parameterUrl | string | Yes| Yes|Media output URI. The following types of URIs are supported:
1. Relative path whose protocol type is **internal**. Example:
Temporary directory: internal://cache/test.mp4

2. Absolute path. Example:
file:///data/data/ohos.xxx.xxx/files/test.mp4| +| parameterOne | [CustomEnum](#Enumeration)| Yes| Yes|Describe the attributes. The requirements are similar to those for the parameter description.| diff --git a/en/contribute/template/readme-template.md b/en/contribute/template/readme-template.md new file mode 100644 index 0000000000000000000000000000000000000000..127a3fc8b4483e13c80c0d6cdbf95e52a7e3e58b --- /dev/null +++ b/en/contribute/template/readme-template.md @@ -0,0 +1,155 @@ +# ***ExampleName*** Subsystem/Part + +- [Introduction](#Introduction) +- [Directory Structure](#Directory-Structure) +- [Constraints](#Constraints) +- [Compilation and Building](#Compilation-and-Building) +- [Usage](#Usage) + - [Available APIs](#Available-APIs) + - [How to Use](#How-to-Use) +- [Repositories Involved](#Repositories-Involved) + +[Title Description] Use **Subsystem** or **Part** based on the Readme file type. + + +![Subsystem-readme](figures/figure01.png) + + +## Introduction + + +[Writing Instructions] **Mandatory**. The following contents must be included: + +**Overall introduction.** Describe the subsystem from the following aspects: background (role in the entire OpenHarmony architecture), functions, use cases, and supported devices. + +**Architecture diagram.** Provide an architecture diagram and explain the main components in the architecture. + +**If this document is about a part, which is part of a subsystem, and related concepts of the subsystem can help understand the part, you are advised to include the following information:** + +**For more concepts related to the ***exampleName*** subsystem, see ***exampleName***. (Provide the link to the subsystem readme.)** + + +The precautions for writing are as follows: + + +| Item| Requirement| +| -------- | -------- | +| **A.1** | **Content**| +| A.1.1 | Style: Use formal language and avoid colloquial language.| +| A.1.2 | Compliance: Do not use terms that have compliance and legal risks, such as concepts specific to third-party intellectual property rights.| +| A.1.3 | Concise: Provide only necessary and minimum information to instruct developers to complete operations as soon as possible.| +| A.1.4 | Correct: The code and parameters in the Readme file must be consistent with the actual product information.| +| A.1.5 | Accurate: Use accurate rather than ambiguous description.| +| A.1.6 | Consistent: Words and concepts in the Readme file must be used consistently across the file and compliant with the glossary. The full name of an acronym or abbreviation must be provided when it appears for the first time in the file.| +| A.1.7 | Specific: Use specific words. For example, when indicating the quantity or degree, do not use "more" or "less". Use specific numbers instead.| +| **A.2** | **Format**| +| A.2.1 | Use punctuation correctly. End a sentence with punctuation.| +| A.2.2 | Present the content clearly, for example, by using bullets or categories. Do not include a single bullet or extra empty lines.| +| A.2.3 | Do not add a space between an English word and Chinese word.| +| A.2.4 | Use valid and specific links that provide direct redirection or download. It is recommended that relative links in Gitee instead of absolute links be used.| +| A.2.5 | For auxiliary description, use the "Note" format. For declaration in advance, use the "Notice" format.| +| **A.3** | **Tables**| +| A.3.1 | Include a caption for each table. Use nouns or noun phrases in the caption.| +| A.3.2 | Include a header for each table. Ensure that a table contains at least two rows and two columns.| +| A.3.3 | If there is no content in a table cell, use an underscore (_) in the cell, rather than leaving it blank.| +| **A.4** | **Figures**| +| A.4.1 | Do not include figures of religious beliefs.| +| A.4.2 | Include a caption for each figure. Use nouns or noun phrases in the caption.| +| A.4.3 | Figures must be clear, legible, complete, and easy to read. For example, a flowchart must contain "Start" and "End".| +| A.4.4 | Each figure must have clear logic and be provided with relevant text descriptions.| +| A.4.5 | It is recommended that each figure, in .png format, have the size less than or equal to 150 KB, the height about 640 px, and the width less than or equal to 820 px.| +| A.4.6 | Try not to include text in figures. If text is required, make sure the text language is consistent with your file's language.| + + +The following shows an architecture diagram. Pay attention to the **color and format requirements**. + +**Figure 1** Subsystem architecture +![Architecture](figures/figure02.png) + + + +## Directory Structure + +[Writing Instructions] **Mandatory**. Describe the code directory structure of the project repository and function description of the corresponding directory. + +```undefined +/foundation/ace +├── frameworks # Framework code +│ └── lite +│ ├── examples # Sample code +│ ├── include # Exposed header files +│ ├── packages # JS implementation +│ ├── src # Source code +│ ├── targets # Configuration file of each target device +│ └── tools # Tool code +├── interfaces # APIs exposed externally +│ └── innerkits # Header files for internal subsystems +│ └── builtin # Third-party module APIs provided by the JS application framework +``` + + + +## Constraints + +[Writing Instructions] **Optional**. Include the conditions for project running, for example, a specific programming language or a specific operating system with a given version. + +| Item| Requirement| +| -------- | -------- | +| D.1.1 | Clearly specify the function limitations or operation restrictions.| +| D.1.2 | Describe only constraints that affect task development or user experience.| +| D.1.3 | Describe operations that are prone to errors in the procedure, but not in this section.| + + +## Compilation and Building + +[Writing Instructions] **Optional**. This section is not required for a subsystem Readme file. Include this section in a part Readme file based on the actual conditions. + + +## Usage + + +### Available APIs + +[Writing Instructions] **Optional**. Describe the APIs related to the development guide so that developers can have a general understanding of the APIs before development. **This section is not required for a subsystem Readme file.** Determine whether this section is required for a part Readme file based on the actual conditions. If the corresponding API reference is available, you do not need to include this section. The precautions for writing are as follows: + +| Item| Requirement| +| -------- | -------- | +| J.1.1 | Include only APIs relevant to the development task.| +| J.1.2 | Provide only main APIs if there are too many APIs.| + + +### How to Use + +[Writing Instructions] **Optional**. Provide a concept introduction for a subsystem Readme file and function introduction for a part Readme file. If the corresponding development guide is available, you can provide a link, rather than details here. + +The table below describes the writing requirements. After finishing the writing, check your content against these requirements one by one. + +| Item| Requirement| +| -------- | -------- | +| **F.1** | **Writing a Development Procedure**| +| F.1.1 | Complete: Provide all mandatory steps.| +| F.1.2 | Clear: The logic of the writing must be clear and reasonable. The overview, preparations, and operations in the document must be described by following certain logic, and the chapters should not be broken or contradictory.| +| F.1.3 | Sentence pattern for tasks: Use verbs + nouns to describe actions in titles or sentences.| +| F.1.4 | Prevention in advance: If the operation involves restrictions, errors, or potential risks, describe them in advance.| +| F.1.5 | Clear steps-1: Describe the purpose of each step, no matter whether it is simple or not.| +| F.1.6 | Clear steps-2: Specify the environment, tools, operations, and how-to.| +| F.1.7 | If an operation is optional, specify the conditions in which the operation is required.| +| F.1.8 | After the development procedure is complete, specify the expected results.| +| **F.2** | **Writing a Code Segment**| +| F.2.1 | If a code segment involves commands to be copied by developers, display the commands in editable mode, instead of using screenshots. Use code snippets to wrap the commands.| +| F.2.2 | Provide comments for key sections and key steps in the code.| +| F.2.3 | The code display meets the code indentation requirements.| +| F.2.4 | If an API call is involved in a step, provide the API and its usage description or sample code. The code should come from specific instances.| + + +## Repositories Involved + +[Writing Instructions] **Mandatory**. List the links of all related repositories of the subsystem where the current repository is located and mark the current repository in bold. + +Example: + +[Kernel](https://gitee.com/openharmony/docs/blob/master/en/readme/kernel-subsystem.md) + +[drivers\_liteos](https://gitee.com/openharmony/drivers_liteos/blob/master/README.md) + +**kernel\_liteos\_a** \ No newline at end of file diff --git a/en/contribute/template/xxboard-template.md b/en/contribute/template/xxboard-template.md new file mode 100644 index 0000000000000000000000000000000000000000..1d2f96eee083e9f81f45cdbec5c302476af94727 --- /dev/null +++ b/en/contribute/template/xxboard-template.md @@ -0,0 +1,81 @@ +# ***ExampleName*** Development Board +*Template positioning: When a third-party development board is introduced to OpenHarmony, the board vendor needs to provide an introduction to the board for developers to quickly understand the board.* + +## Introduction + +*[Writing Instructions]* + +*Describe the functions, scenarios, and key features supported by the development board.* + +*Provide a picture to show the appearance of the development board.* + +*Provide a bottom board picture.* + +*Provide a functional block diagram and an introduction.* + +*Name the figures after the development board.* + +*Reference document: https://gitee.com/openharmony/docs/blob/master/en/device-dev/quick-start/quickstart-lite-introduction-hi3861.md* + +******** +## Development Board Specifications + +*[Writing Instructions] Provide the module and hardware specifications of the development board.* + +## (Optional) Constraints + +*[Writing Instructions] Describe the restrictions and suggestions on functions, features, and specifications of the development board, if any.* + +******** + + +## Key Features +*[Writing Instructions] List supported key features of OpenHarmony.* + +## Pin Definition +*[Writing Instruction] Describe the definitions of I/O pins, and how to configure pins and connect pins to external components.* + +## Setting Up the Development Environment + +### System Requirements + +*[Writing Instruction] Describe the dependency of the development board on the OpenHarmony system, software environment, and hardware environment.* + +### Required Tools + +*[Writing Instruction] Provide the paths for downloading the tools used to build and debug the development board.* + +### Setup Process + +*[Writing Instruction] Describe the procedure for setting up the environment step by step.* + +## Building and Debugging + +### Building + +*[Writing Instruction] Describe how to use OpenHarmony and update OpenHarmony binary files and devices on the development board.* + +### Burning + +*[Writing Instruction] Describe how to burn images step by step.* + +### Running + +*[Writing Instruction] Describe how to check whether the lighting, running, and output of the development board are proper.* + + +### Debugging + +*[Writing Instruction] Describe how to debug common errors on the development board.* + +## First Demo + +*[Writing Instruction] Provide a quick start example and running effect based on the development board, or provide the link of the demo source code.* + +## References + +*[Writing Instruction] Provide links to the reference documents, samples, and FAQs.* + +## (Optional) Acknowledgments + +*[Writing Instruction] Provide acknowledgements to third-party contributors.* diff --git a/en/contribute/title-(briefly-describe-the-key-information-of-the-issue-).md b/en/contribute/title-(briefly-describe-the-key-information-of-the-issue-).md deleted file mode 100755 index 15c30a8b6b21617f55892701526d2f1c6ef83701..0000000000000000000000000000000000000000 --- a/en/contribute/title-(briefly-describe-the-key-information-of-the-issue-).md +++ /dev/null @@ -1,36 +0,0 @@ -# Title \(Briefly Describe the Key Information of the Issue.\) - -This topic describes the issues encountered during development and their solutions, helping developers quickly address the issues. - -## Template for Writing Minor Issues - -Briefly describe the operations, issues, and solutions. - -## Template for Writing Complex Issues - -**Description** - -- System software and version in use -- Problem description and trigger conditions - -- Error messages - -- Screenshots if available - - -**Possible Causes** - -Analyze the causes of the problem. If there are multiple possible causes, list them one by one. - -1. XXX -2. XXX - -**Solutions** - -- If there are multiple solutions, arrange them in order from least complex to most complex, and provide their respective scenarios. -- If possible, provide screenshots to help understand the steps. -- If the code has print output, provide the output content separately to help understand the solution procedure. - -1. XXX -2. XXX - diff --git a/en/contribute/tutorial-title-(task-name).md b/en/contribute/tutorial-title-(task-name).md deleted file mode 100755 index 9dd5b359f46a9d9c312bbeb361ba05517adc1f49..0000000000000000000000000000000000000000 --- a/en/contribute/tutorial-title-(task-name).md +++ /dev/null @@ -1,48 +0,0 @@ -# Tutorial: Title \(Task Name\) - -A tutorial describes how to develop a complex task, feature, and application. Usually, the development process is divided into several sections, each with a series of steps. In addition, code examples are provided to help developers understand the specific feature implementation. - -You should explain basic concepts mentioned in the tutorial, and suggest developers refer to specific corresponding topics in developer-oriented documents for in-depth concepts. - -When you write the tutorial page, create a **MarkDown** file in the **others** directory. - -## Overview - -Content: Describe the tasks that developers will do and the features and effects that developers will achieve after learning this tutorial. If multiple goals can be achieved, it is recommended that you use a bulleted list. - -If possible, provide pictures or short videos to demonstrate the effect. - -## Preparations - -- Provide the information about the required software, hardware, tools, and their version information. -- Describe required permissions. - -## _XXX_ \(Key Task 1\) - -Break down the tutorial into several sequential critical tasks or parallel scenario-specific tasks. - -1. XXXX - - ``` - // Sample code - ``` - -2. XXXX - -Comply with the following writing instructions on how to describe operations: - -1. Specify the operation scenario and purpose for each step, and clarify the actor of each action. -2. Provide API descriptions and related sample codes if needed. -3. Provide screenshots of GUI-based steps for better understanding. -4. Ensure that code logic and syntax are correct. -5. Provides comments for key steps in the code. -6. Provide the output content if any. - -## XXX \(Key Task 2\) - -1. XXXX - -## Next - -Describe the subsequent development tasks that may be associated with this tutorial. If there are no associated tasks, skip this topic. - diff --git a/en/design/API-Review-Template.md b/en/design/API-Review-Template.md new file mode 100644 index 0000000000000000000000000000000000000000..3d83cfb7f8cfda6904eab4370635bccf6e5fb22e --- /dev/null +++ b/en/design/API-Review-Template.md @@ -0,0 +1,137 @@ +# Review Application for the API in the OpenHarmony Subsystem + +## Background + +* API type: [Public API | Test API | HDI] +* API requirement source: +* API usage scenario: +* Belonging subsystem: +* Expected API release version: +* Contributor: +* Number of APIs involved in this review: + +| Change Type| Quantity| Programming Language| +|---|---|---| +| Added| | | +| Behavior changed| | +| Deprecated| | | +| Deleted| | | + +## API Description + +### Necessity of the Changes + +> Based on the as-is and gap analysis, describe what the application scenarios and benefits of the APIs are. + +### Feature Overview + +> Describe features implemented by the APIs. + +## Review Conclusion + +### Review Conclusion from Committers + +### Review Conclusion from Domain SIGs + +## Self-Check Table + +| Self-Check Item| Self-Check Result| +|---|---| +| Is the spelling check completed?| | +| Are coding specifications complied with?| | +| Are parts of speech (noun, adjective, adverb) used correctly?| | +| Does the API name fully describe the API logic?| | +|Is the number of API parameters appropriate? (Generally, there should be fewer than 7 parameters.)| | +|Are abbreviations properly used? (Abbreviations used should be well known.)| | +|Is it really that the caller of a void API does not need a return value?| | +|Is the inheritance system appropriate? Does every method of a parent class apply to its child classes?| | +|Are all possible error states included and defined?| | +| Is the group of antonyms used correctly, for example:
add/remove, create/destroy, insert/delete, start/stop, begin/end,
send/receive, up/down, show/hide, open/close, source/target,
source/destination, increase/decrease, first/last, next/previous| | +|Are the description and semantic hierarchy of new APIs consistent with those of existing APIs in the same module?| | +| Are asynchronous counterparts needed for synchronous APIs?| | +| Are all the public APIs truly required by developers?| | + +## API Description + +> Enter the code commit address. + +* Code address: + +## API Permission Design + +> Specify whether developers need to apply for certain permissions to use the APIs. + +## API Privacy Protection Design + +> If user privacy data is involved, privacy protection must be considered. + +## Developer Guide + +> Optional. + +## API Code Example + +> Select either of the following: + +* Code address: +* Code snippet: + +## API Updates + +> Only required for existing APIs. + +### Behavior Change + +> The API behavior change indicates that the API only has its behavior changed. +> The new API behavior must be released in a new version. You should not change the API behavior without releasing a new version (except for defect rectification). + +#### Related APIs + +#### Reason for the Change + +### Deprecated APIs + +> Add the `@deprecated` annotation to the description of deprecated APIs (including JS, TS, C, and C++ APIs). + +#### Related APIs + +> State the version from which the API is annotated by `@deprecated`. + +#### Reason for Deprecation + +#### Substitute APIs + +> List the APIs provided to substitute the deprecated ones. If there are no substitute APIs provided, describe the reason. + +### Deleted APIs + +> An API can be deleted only after five API versions have been released since it is marked as deprecated. + +#### Related APIs + +#### Reason for Deletion + +#### Substitute APIs + +> List the APIs provided to substitute the deleted ones. If there are no substitute APIs provided, describe the reason. + +## DFX + +### Compatibility + +### Performance + +### Power Consumption + +### Reliability + +### Testability + +> Automatic API test cases must be delivered for all APIs. + +## Review Conclusion + +* Reviewed on: +* Reviewers: +* Review conclusion: [Pass | Fail] +* Review meeting minutes: diff --git a/en/design/OpenHarmony-API-governance.md b/en/design/OpenHarmony-API-governance.md index d117bf795c8979d66234470535554885e009ab72..ccd43d6076d4935d60a583eb3ee43ee679bae8ee 100644 --- a/en/design/OpenHarmony-API-governance.md +++ b/en/design/OpenHarmony-API-governance.md @@ -1,179 +1,205 @@ # OpenHarmony API Governance Charter +## Introduction + +To help the OpenHarmony ecosystem develop and evolve in a healthy and orderly way, this Charter defines the governance process and lifecycle (create, change, deprecate, and delete) of OpenHarmony APIs. It also specifies basic design requirements of OpenHarmony APIs. + +This Charter is formulated by the API SIG and approved by the PMC for release. Any revision to this Charter will be released only after being reviewed by the API SIG and approved by the PMC. + ## Overview -To help the OpenHarmony application ecosystem develop in a healthy and orderly way, this Charter defines the governance process and API lifecycle (create, change, deprecate, and delete) and specifies basic design requirements of OpenHarmony APIs. +### Scope and Definition +The OpenHarmony software stack contains multiple roles. Naturally, OpenHarmony APIs have multiple types. -## API Scope and Definition + -APIs locate between the application layer and framework layer. They are predefined class and methods provided by the framework layer and system to developers for the development of system and third-party applications. The APIs do not include OEM-extended interfaces. +Different types of APIs have different compatibility requirements, as described in the table below. -![](figures/API-Scope-And-Definition.png) +| Type| Prepared By| Used By| Compatibility Requirement| Guarding Method| +|---|---|---|---|---| +| Public API | System and framework| All application developers| 5 API versions| X test suite (XTS)| +| Test API | Test framework| All application developers| 3 API versions| To be built| +| System API | System and framework|System application developers|Not guaranteed| To be built| +| HDI | HDF| System services| 4 API versions| XTS | +| Driver API | HDF | Driver developers| Not guaranteed| None| +| Inner API | System parts| System parts| Not guaranteed| None| -OpenHarmony APIs are classified into the following types by authorized usage: +The APIs are described as follows: -- Public API: released publicly for third-party application development. -- System API: released privately for applications with authorization signature and privileged applications only. -- Test API: released with restrictions and used only for X test suite (XTS) or application debugging. +* Public API: APIs provided for all application developers. +* Test API: APIs provided for developers to test their applications. +* System API: APIs provided for privileged system applications. Common applications cannot use these APIs. +* HDI: APIs that describe hardware capabilities. +* Driver API: APIs provided for driver developers. +* Inner API: APIs to implement mutual calling between the system service and framework. They are used only inside the system and do not guarantee compatibility. -Unless otherwise specified, the terms defined in this Charter apply to Public APIs, System APIs, and Test APIs of OpenHarmony. Additional requirements or exceptions for the System and Test APIs are provided as a supplement. +### APIs and Programming Languages -OpenHarmony APIs are classified into the following types by programming language: +OpenHarmony aims to build a next-generation Operating System (OS) for the Internet of Everything (IoE) era. The following programming languages and more can be used: -- JS APIs: JavaScript programming APIs open to applications. -- Native APIs: C/C++ programming APIs open to applications. +* C/C++ +* JavaScript +* TypeScript -Unless otherwise specified, the terms defined in this Charter apply to JS APIs and Native APIs. +The content described in this Charter is irrelevant to the programming language in use. Regardless of the programming language, APIs must comply with this Charter while meeting the programming language requirements. ## API Governance ### Roles and Responsibilities -| **Role**| **Responsibilities in API Governance** -|----------|---------- -| Contributor| Submit API code and design documents. -| Committer| Review the code and submit a pre-review comment on an API commit. -| Domain SIG|

Comment on the commits of new API code, and the passed commits can be merged. Submit a pre-review comment on updated API code.

-| API SIG| Comment on updated API code. -| PMC| Release API version plans. Review amendments of this Charter, revise the terms, and publish the API Governance Charter. +|**Role**|**Responsibilities in API Governance**| +| - | - | +|Contributor|Commit API code and design documents.| +|Committer|Review the code and submit a pre-review comment on an API commit.| +|Domain SIG|Comment on the commits of new API code, so the passed commits can be merged.
Submit a pre-review comment on updated API code.| +|API SIG|Comment on updated API code.| +|PMC|Release API version plans. Review amendments of this Charter, revise the terms, and publish this Charter.| ### API Review Process +The API review process is as follows: -The review process is as follows. + -![](figures/API-Review-Process.png) +The main process is as follows: -Process description - -1. Initiate review and submit code (Contributor): If any APIs are added or modified, the Contributor needs to additionally submit the the API design document to specify the demand source, application scenarios and usage, permission design, and privacy protection clarification. For details, see the API review application composites. To avoid rework, the Contributor can send an email to submit the API design document to the Committer, Domain SIG, and API SIG for pre-review before the formal API review application and code submission. -2. Review code and pre-review APIs (Committer): After the code review is approved, the Committer should submit the APIs to the Domain SIG. If the API code involve multiple domains, they should be submitted to the Committers of the corresponding domains. The next review step can be performed only after all Committers review and approve the code. -3. Review APIs (Domain SIG): The code of added APIs can be merged only after being reviewed and approved by the Domain SIG. If there are changes of existing APIs to review, the Domain SIG should submit them to the API SIG. If the newly added APIs involve multiple domains, they should be submitted to the SIGs of the corresponding domains. The code can be merged after being reviewed and approved by one of the Domain SIGs. If the changed APIs involve multiple domains, they should be submitted to the SIGs of the corresponding domains. The next review step can be performed only after all Domain SIGs approve the APIs. -4. Review API changes (API SIG): The code of changed APIs can be merged only after being reviewed and approved by the API SIG. -5. The review is complete. +1. Initiate API review and commit code (contributor). If any APIs are added or modified, the contributor must additionally submit an API review application to specify the API requirement source, usage scenario, permission design, and privacy protection design. For details, see "API Review Application Composites" below. To avoid rework, the contributor can send an email to submit the API design document to the committer, domain SIG, and API SIG for pre-review before the formal API review application and code commit. +1. Review code (committer). After the code review is approved, the committer should submit the APIs to the domain SIG. If the API code involves multiple domains, they should be submitted to the committers of the corresponding domains. The next review step can be performed only after all committers review and approve the code. +1. Review APIs (domain SIG). The code of new APIs can be merged only after being reviewed and approved by the domain SIG. If there are changes to existing APIs, the domain SIG should submit them to the API SIG. If the new APIs involve multiple domains, they should be submitted to the SIGs of the corresponding domains. The code can be merged after being reviewed and approved by one of the domain SIGs. If the changed APIs involve multiple domains, they should be submitted to the SIGs of the corresponding domains. The next review step can be performed only after all domain SIGs approve the APIs. +1. Review API changes (owner: API SIG): The code of changed APIs can be merged only after being reviewed and approved by the API SIG. +1. The review is complete. ### API Review Application Composites -If an API is added or changed, the corresponding API design document needs to be submitted. - -For new APIs, the following elements must be included: - -1. (Mandatory) Describe the demand source and application scenario. -2. (Mandatory) Analyze the API as-is and gaps, and describe the necessity of adding or changing APIs. -3. (Mandatory) Describe the API prototype design and usage. (Optional) When necessary, add use examples. -4. (Mandatory) Provide the API permission design. -5. (Mandatory) Clarify the API privacy protection solution and requirements fulfillment. -6. (Mandatory) Submit the corresponding API reference when submitting the code. (Optional) When necessary, submit the corresponding developer guide. -7. (Optional) Describe the compatibility, performance, power consumption, reliability, and tests. (If "API Design Requirements" of this Charter are not met, the description must be included.) +If an API is added or changed, the corresponding API review application must be submitted. For details on the application template, see [API Review Template](API-Review-Template.md). -For changed APIs, except the preceding composites, the following must be included: +For new APIs, you must: +1. (Mandatory) Describe the requirement source and usage scenario. +1. (Mandatory) Analyze the API as-is and gaps, and describe the necessity of adding or changing APIs. +1. (Mandatory) Describe the API prototype design and usage. (Optional) When necessary, add use examples. +1. (Mandatory) Provide the API permission design. +1. (Mandatory) Clarify the API privacy protection solution and requirements fulfillment. +1. (Mandatory) Submit the corresponding API reference when committing the code. (Optional) When necessary, submit the corresponding developer guide. +1. (Optional) Describe the compatibility, performance, power consumption, reliability, and tests. (If "API Design Requirements" of this Charter are not met, the description must be included.) -1. (Mandatory) How old APIs are handled (deprecated, hidden, or permanently deleted) and compatibility measures for developing applications using old SDKs. -2. (Mandatory) Change impact, substitute APIs, and corresponding application adaptation solution. -3. (Mandatory) Update the ChangeLog file. Update the API-diff file (Mandatory if JS/Native API changes are involved.) +For changed APIs, except the preceding operations, you must: +1. (Mandatory) Describe how earlier APIs are handled (deprecated, hidden, or permanently deleted) and compatibility measures for developing applications using old SDKs. +2. (Mandatory) Describe the change impact, substitute APIs, and corresponding application adaptation solution. +3. (Mandatory) Update the ChangeLog file. Update the API-diff file (Mandatory if JS or native API changes are involved.) ## API Design Requirements -### Consistency - -1. Concept: Scenario-based service models are abstracted to form coherent, consistent, and self-consistent OpenHarmony user program model and service concepts. -2. Term: Service terms must be nouns. Multiple nouns with similar semantic meanings are not allowed to represent the same service object. Similarly, to avoid confusion, it is not allowed to use the same noun or linguistically close nouns for different service objects. -3. Operation: Each operation action is expressed using a unique verb. -4. Parameter sequence: The location and sequence of the same parameter or parameter sequence in multiple APIs are the same. -5. Mechanism and algorithm: The communication mechanism, calling mode, authentication mechanism, and encryption algorithm are consistent. -6. API reference, demo, and template style: The layout and usage are consistent. - -### Ease of Use +### Consistency +1. Concept: Scenario-based service models must be abstracted to form coherent, consistent, and self-consistent OpenHarmony user program models and service concepts. +1. Term: Service terms must be nouns. Multiple nouns with similar semantic meanings are not allowed to represent the same service object. Similarly, to avoid confusion, it is not allowed to use the same noun or linguistically close nouns for different service objects. +1. Operation: Every operation action must be expressed using a unique verb. +1. Parameter sequence: The location and sequence of the same parameter or parameter sequence in multiple APIs must be the same. +1. Mechanism and algorithm: The communication mechanism, calling mode, authentication mechanism, and encryption algorithm must be consistent. +1. API reference, demo, and template style: The layout and usage must be consistent. + +### Ease to Use Design APIs from the perspective of their users rather than providers. - -1. Readability: API naming, functions, and features must be easy to understand. -2. Ease of use: Provide easy-to-use APIs by reducing unnecessary coupling between APIs, avoiding dependencies on the calling sequence of multiple unrelated APIs, and avoiding calling multiple methods from different packages, modules, or classes at the same time when using a single function. -3. Avoiding misleading: Provide capabilities complying with user expectations to avoid misuse. -4. Provide required API reference documents. +1. Readability: API naming and features must be easy to understand. +1. Ease of use: Provide easy-to-use APIs by reducing unnecessary coupling between APIs, avoiding dependencies on the calling sequence of multiple unrelated APIs, and avoiding calling multiple methods from different packages, modules, or classes at the same time when using a single feature. +1. Avoiding misleading: Provide capabilities complying with user expectations to avoid misuse. +1. Provide required API reference documents. ### Naming - -1. Be able to express the function clearly. Use full descriptive words. -2. Avoid misleading. Misleading names are more harmful than ill-stated ones. -3. The meaning of the word is clear. Avoid using common words such as info, data, and object. -4. The larger the scope is, the more precise the naming should be. -5. Do not use or minimize the use of abbreviations. Common terms in the industry must comply with industry conventions and can be abbreviated. -6. Package name/module name/namespace prefix convention: +1. Be able to express the capabilities clearly. Use full descriptive words. +1. Avoid misleading. Misleading names are more harmful than ill-stated ones. +1. Use words with clear meaning. Do not use words with common meanings, such as info, data, and object. +1. The larger the scope is, the more precise the naming should be. +1. Eliminate or minimize the use of abbreviations. Common terms in the industry must comply with industry conventions and can be abbreviated. +1. Bundle name/Module name/Namespace prefix convention: 1. JS API module name: @ohos.\*. 2. Native API namespace: namespace OHOS.\*. - 3. If external open-source code is referenced, retain the original package name, module name, or namespace, or replace the package name according to the preceding rules. -7. The package name, module name, and namespace must contain at least two and at most four segments. One word is recommended for each segment, and a maximum of two words are allowed. -8. The class name, method name, function name, member variable, and variable name cannot exceed four words. + 3. If external open-source code is referenced, retain the original bundle name, module name, or namespace, or replace the bundle name according to the preceding rules. +1. The bundle name, module name, and namespace must contain 2 to 4 segments. One word is recommended for each segment, and a maximum of two words are allowed. +1. The class name, method name, function name, member variable, and variable name cannot exceed four words. ### Permission Control - -1. Completeness principle: All behaviors across application sandboxes must be limited by permission control. -2. Optimal granularity principle: One permission protects only one type of objects. You only need to apply for one permission to access an interface. -3. Clearness principle: The protected object, permission scope, and sensitivity level must be clearly specified in the permission definition. -4. Minimum scope principle: A permission is assigned only to applications that have service requirements to minimize permission scope. +1. Completeness: All behaviors across application sandboxes must be limited by permission control. +1. Optimal granularity: One permission protects only one type of object. Developers only need to apply for one permission to access an interface. +1. Clearness: The protected object, permission scope, and sensitivity level must be clearly specified in the permission definition. +1. Minimum scope: A permission is assigned only to applications that have service requirements to minimize permission scope. ### Privacy Protection - -1. The response returned from API calling contains only necessary information. -2. Mobile phone users’ personal data cannot be obtained through API calling unless required permissions are assigned by users. -3. In case that an API is called by multiple applications, if personal data needs to be disclosed to the API to be called, the caller must specify the disclosed data type, data receiver, and data use purpose in the privacy statement. -4. When an API needs to access sensitive user data (such as phone calls, contacts, and media content), the system picker mechanism must be used to prevent the API from accessing the data by applying for sensitive permissions. -5. API openness does not allow unrelated functions. +1. The response returned from API calling should contain only necessary information. +1. Mobile phone users' personal data cannot be obtained through API calling unless required permissions are assigned by users. +1. In case that an API is called by multiple applications, if personal data needs to be disclosed to the API to be called, the caller must specify the disclosed data type, data receiver, and data use purpose in the privacy statement. +1. When an API needs to access sensitive user data (such as phone calls, contacts, and media content), the system picker mechanism must be used to prevent the API from accessing the data through sensitive permission application. +1. API openness does not allow unrelated features. ### Documentation - -1. The API reference document is in English. -2. The API reference document must include the brief and detailed descriptions of modules and packages. -3. The API reference document must include brief descriptions of classes, methods, interfaces, enumerations, and member variables. -4. The API reference document can optionally include detailed descriptions of classes, methods, interfaces, enumerations, and member variables. -5. The API reference document must contain descriptions of all input parameters of a method or interface. -6. If a method or interface has a return value, the API reference document must contain a return value description. -7. If an exception may be thrown during the execution, the API reference document must contain the exception description. -8. The starting version number of the API (annotated with @since) must be included. -9. The version number of a module or class (annotated with @version) is optionally included. -10. If incompatible API changes are involved, both API-Diff and ChangeLog files must be delivered. +1. The API reference document must be written in English. +1. The API reference document must include the brief and detailed descriptions of modules and packages. +1. The API reference document must include brief descriptions of classes, methods, interfaces, enumerations, and member variables. +1. The API reference document can optionally include detailed descriptions of classes, methods, interfaces, enumerations, and member variables. +1. The API reference document must contain descriptions of all input parameters of every method or interface. +1. If a method or interface has a return value, the API reference document must contain a return value description. +1. If an exception may be thrown during the execution, the API reference document must contain the exception description. +1. The starting version of the API (annotated with @since) must be included. +1. The version of a module or class (annotated with @version) is optionally included. +1. If incompatible API changes are involved, both API-Diff and ChangeLog files must be delivered. ### Compatibility - 1. The API compatibility requirements in descending order are as follows: contract compatibility > binary-code compatibility > source-code compatibility. - 1. Source-code compatibility: After version evolution, the developer’s existing source code can be compiled properly. - 2. Binary-code compatibility: After version evolution, the developer’s existing programs can be linked to and run properly without recompilation. - 3. Contract compatibility: It is also called semantic compatibility. After version evolution, the developer’s original program behaviors remain unchanged. -2. OpenHarmony API backward compatibility must meet binary-code compatibility requirements. Exceptions must be reviewed by the API SIG and approved by the PMC. Common API changes that break binary-code compatibility include: + 1. Source-code compatibility: After version evolution, the existing source code can be compiled properly. + 1. Binary-code compatibility: After version evolution, the existing programs can be linked to and run properly without recompilation. + 1. Contract compatibility: also called semantic compatibility. After version evolution, the original program behaviors remain unchanged. +1. API backward compatibility must meet binary-code compatibility requirements. Exceptions must be reviewed by the API SIG and approved by the PMC. Common API changes that break binary-code compatibility include: 1. Delete any API elements. - 2. Reduce the visibility of a method. For example, change from protected to private or from public to protected. - 3. Change the class type. For example, change from an abstract class to a non-abstract class, or from an interface class to a non-interface class. - 4. Change the method prototype. For example, change the return value type, input parameter sequence, or input parameter type. - 5. Change the member attributes. For example, change the member attribute from non-final to final or from non-static to static. -3. Do not modify APIs with the same prototype but incompatible functions. You can modify APIs by deprecating old APIs and adding new ones with restrictions. -4. Depending on the release type, the API lifecycle and compatibility requirements are as follows: + 1. Reduce the visibility of a method. For example, change from protected to private or from public to protected. + 1. Change the class type. For example, change from an abstract class to a non-abstract class, or from an interface class to a non-interface class. + 1. Change the method prototype. For example, change the return value type, input parameter sequence, or input parameter type. + 1. Change the member attributes. For example, change the member attribute from non-final to final or from non-static to static. +1. Do not modify APIs with the same prototype but incompatible features. You can modify APIs by deprecating old APIs and adding new ones with restrictions. +1. Depending on the release type, the API lifecycle and compatibility requirements are as follows: ![](figures/API-Lifecycle.png) -1. Canary version: API preview version released at an earlier date, which cannot ensure API stability. - 1. Canary versions are compatible with the previous release version. - 2. Different Canary versions of the same API version are not required to keep compatible. -2. Beta version: publicly released beta version, which cannot ensure API stability. - 1. Beta versions are compatible with the previous release version. - 2. Beta versions are not compatible with the early canary versions of the same API version. - 3. Different Beta versions of the same API version are not required to keep compatible. - 4. The APIs are frozen after the API Stable version is released. API additions or changes are not allowed for later Beta versions. -3. Release version: official API release version. Released APIs must comply with the contractual commitments made to external developers. In principle, incompatible changes cannot be made on released APIs, and deprecation of released APIs is restricted. The basic requirements for deprecating released APIs are as follows: - 1. Add the deprecate annotation. - 2. Provide alternative interfaces. - 3. Retain the deprecated APIs in at least five API versions released since the deprecation. - -### Performance, Power Consumption, and Reliability - + 1. Canary version: API Preview version released at an earlier date, which cannot ensure API stability. + 1. Canary versions are compatible with the previous Release version. + 1. Different Canary versions of the same API version are not required to keep compatible. + 1. Beta version: publicly released beta version, which cannot ensure API stability. + 1. Beta versions are compatible with the previous Release version. + 1. Beta versions are not compatible with the early Canary versions of the same API version. + 1. Different Beta versions of the same API version are not required to keep compatible. + 1. The APIs are frozen after the API Stable version is released. API additions or changes are not allowed for later Beta versions. + 1. Release version: official API release version. + Released APIs must comply with the contractual commitments made to developers. In principle, incompatible changes cannot be made on released APIs, and deprecation of released APIs is restricted. The basic requirements for deprecating released APIs are as follows: + 1. Add the @deprecated annotation. + 1. Provide substitute APIs. + 1. Retain the deprecated APIs in at least five API versions released since the deprecation. + +### Performance 1. Respond in a timely manner to avoid callers waiting. If an API call takes a long time, use an asynchronous API. 2. Pay attention to the impact of the API call timing and frequency on the RAM usage. 3. Pay attention to the impact of the API call timing and frequency on power consumption. -4. The lifecycle of an object created in an API must be complete to prevent object resource leakage. -5. The idempotence requirement must be met. The caller can obtain the same effect after calling request APIs with the same service meaning for one or multiple times (except for the APIs whose calling depends on the change of external resources). To call a reentrant API, avoid introducing time-varying factors, such as system ticks, static variables, and global variables without mutual exclusion protection. To call an API from a client repeatedly, use contextID, clientToken, and sequenceNo as input parameters. +4. Resources must be released in a timely manner when APIs that use resources are called. A fault tolerance mechanism must be provided for abnormal scenarios to ensure timely resource release. -### Testing +### Power Consumption +1. Evaluate the impact of the API call timing and frequency on power consumption, and perform related design if there is any impact. +2. The power consumption should not deteriorate during version evolution. + +### Reliability + +1. APIs cannot crash due to external input (such as input parameters, system status, and external data), internal status, or data exceptions. It must return a specific error code or throw a predefined exception. +2. It must be specified whether an API is called synchronously or asynchronously. If an API is called synchronously, specify the timeout duration or allow the caller to set the timeout duration to prevent service response failure caused by call suspension. +3. APIs must support multi-thread reentrant. +4. APIs must meet the idempotence requirement, which means that the same effect should be obtained for one or multiple API call requests with the same service meaning (except that API call depends on external resource changes). For reentrant API call, avoid introducing time-varying factors, such as system ticks, static variables, and global variables without mutual exclusion protection. For repeated call of the same client, **contextID**, **clientToken**, and **squenceNo** can be used as input parameters. +5. The lifecycle of objects created in APIs must have an end to prevent object resource leakage. +6. The APIs must specify the maximum number of retries allowed after a call failure. + +### Testing 1. Automatic API test cases must be delivered for all new APIs. -2. Use one test case for each single scenario. One test case covers a single function scenario of an API, simplifying the code logic of each single test case. -3. The test case execution is efficient. The execution time of each test case is limited to milliseconds. \ No newline at end of file +2. Use a test case for each single scenario. One test case covers a single function of an API, simplifying the code logic of each single test case. +3. The test case execution must be efficient. The execution time of each test case must be limited to milliseconds. +4. Automatic API test cases must be available for all APIs. +5. Assertions with functional logic are required in addition to the capability of throwing exceptions. + +### Programming Languages + +Regardless of the programming language in use, APIs must comply with the OpenHarmony programming language specifications. diff --git a/en/design/figures/API-Category.png b/en/design/figures/API-Category.png new file mode 100644 index 0000000000000000000000000000000000000000..0d4fc2f8b42c36eb7bfa8b907a299a0fd3fb2bb6 Binary files /dev/null and b/en/design/figures/API-Category.png differ diff --git a/en/design/figures/API-Definition.png b/en/design/figures/API-Definition.png new file mode 100644 index 0000000000000000000000000000000000000000..fc11d7e85845fdc3f80513f0bfbf042f2cd6592c Binary files /dev/null and b/en/design/figures/API-Definition.png differ diff --git a/en/design/figures/API-Lifecycle.png b/en/design/figures/API-Lifecycle.png index 79c15efb497d93778c2399afe25e6b2034624a42..63da45189ca31b5f9d0a826a07f6f090b97cec32 100644 Binary files a/en/design/figures/API-Lifecycle.png and b/en/design/figures/API-Lifecycle.png differ diff --git a/en/design/figures/API-Workflow.png b/en/design/figures/API-Workflow.png new file mode 100644 index 0000000000000000000000000000000000000000..41a41b6f19dc9a3001e7914d066810910a211622 Binary files /dev/null and b/en/design/figures/API-Workflow.png differ diff --git a/en/device-dev/Readme-EN.md b/en/device-dev/Readme-EN.md index bbe11a57349df5d98efb884316d9e1dea5171221..e0c8070e8fe4feb3b8f3e65b3ff78d3c952bc668 100644 --- a/en/device-dev/Readme-EN.md +++ b/en/device-dev/Readme-EN.md @@ -153,7 +153,7 @@ In addition, OpenHarmony provides a series of optional system components that ca

Porting and adapting the OpenHarmony to a third-party library

+

Contributing components

diff --git a/en/device-dev/apinotes/.keep b/en/device-dev/apinotes/.keep deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/zh-cn/device-dev/apis/usb/usbd_client.h b/en/device-dev/apis/usb/usbd_client.h similarity index 35% rename from zh-cn/device-dev/apis/usb/usbd_client.h rename to en/device-dev/apis/usb/usbd_client.h index c8b8e1f9b53cf6f5572899f1d4b38b6f86506cbf..ffb834ee3987f3eb407f1070c9a40a067a716f4f 100644 --- a/zh-cn/device-dev/apis/usb/usbd_client.h +++ b/en/device-dev/apis/usb/usbd_client.h @@ -27,7 +27,7 @@ /** * @file usbd_client.h * - * @brief Defines the usbd Interface. + * @brief Defines the usbd interface. * * @since 3.0 * @version 1.0 @@ -44,232 +44,232 @@ namespace USB { class UsbdClient { public: /* * - * @brief 打开设备,建立连接 + * @brief Opens a USB device to set up a connection. * - * @param dev usb设备地址信息 + * @param dev Indicates the USB device address. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t OpenDevice(const UsbDev &dev); /* * - * @brief 关闭设备,释放与设备相关的所有系统资源 + * @brief Closes a USB device to release all system resources related to the device. * - * @param dev usb设备地址信息 + * @param dev Indicates the USB device address. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t CloseDevice(const UsbDev &dev); /* * - * @brief 获取设备描述符device + * @brief Obtains the USB device descriptor. * - * @param dev usb设备地址信息 - * @param decriptor usb设备描述符信息 + * @param dev Indicates the USB device address. + * @param descriptor Indicates the USB device descriptor. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetDeviceDescriptor(const UsbDev &dev, std::vector &decriptor); /* * - * @brief 根据String ID获取设备的字符串描述符string + * @brief Obtains the string descriptor of a USB device based on the specified string ID. * - * @param dev usb设备地址信息 - * @param descId usb的string ID - * @param decriptor 获取usb设备config信息 + * @param dev Indicates the USB device address. + * @param descId Indicates string descriptor ID. + * @param descriptor Indicates the string descriptor of the USB device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetStringDescriptor(const UsbDev &dev, uint8_t descId, std::vector &decriptor); /* * - * @brief 根据config ID获取设备的配置描述符config + * @brief Obtains the configuration descriptor of a USB device based on the specified config ID. * - * @param dev usb设备地址信息 - * @param descId usb的config ID - * @param decriptor 获取usb设备config信息 + * @param dev Indicates the USB device address. + * @param descId Indicates configuration descriptor ID. + * @param descriptor Indicates the configuration descriptor of the USB device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetConfigDescriptor(const UsbDev &dev, uint8_t descId, std::vector &decriptor); /* * - * @brief 获取原始描述符 + * @brief Obtains the raw descriptor. * - * @param dev usb设备地址信息 - * @param decriptor usb设备原始描述符 + * @param dev Indicates the USB device address. + * @param descriptor Indicates the raw descriptor of the USB device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetRawDescriptor(const UsbDev &dev, std::vector &decriptor); /* * - * @brief 设置当前的config信息 + * @brief Sets the configuration information of a USB device. * - * @param dev usb设备地址信息 - * @param configIndex usb设备config信息 + * @param dev Indicates the USB device address. + * @param configIndex Indicates the configuration information of the USB device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t SetConfig(const UsbDev &dev, uint8_t configIndex); /* * - * @brief 获取当前的config信息 + * @brief Obtains the configuration information of a USB device. * - * @param dev usb设备地址信息 - * @param configIndex usb设备config信息 + * @param dev Indicates the USB device address. + * @param configIndex Indicates the configuration information of the USB device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetConfig(const UsbDev &dev, uint8_t &configIndex); /* * - * @brief 打开接口,并申明独占接口,必须在数据传输前执行 + * @brief Claims a USB interface exclusively. This must be done before data transfer. * - * @param dev usb设备地址信息 - * @param interfaceid usb设备interface ID + * @param dev Indicates the USB device address. + * @param interfaceid Indicates the interface ID of the USB device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t ClaimInterface(const UsbDev &dev, uint8_t interfaceid); /* * - * @brief 关闭接口,释放接口的占用,在停止数据传输后执行 + * @brief Releases a USB interface. This is usually done after data transfer. * - * @param dev usb设备地址信息 - * @param interfaceid usb设备interface ID + * @param dev Indicates the USB device address. + * @param interfaceid Indicates the interface ID of the USB device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t ReleaseInterface(const UsbDev &dev, uint8_t interfaceid); /* * - * @brief 设置指定接口的备选设置,用于在具有相同ID但不同备用设置的两个接口之间进行选择 + * @brief Sets the alternate settings for the specified USB interface. This allows you to switch between two interfaces with the same ID but different alternate settings. * - * @param dev usb设备地址信息 - * @param interfaceid usb设备interface ID - * @param altIndex interface 的 AlternateSetting 信息 + * @param dev Indicates the USB device address. + * @param interfaceid Indicates the interface ID of the USB device. + * @param altIndex Indicates the alternate settings of the USB interface. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t SetInterface(const UsbDev &dev, uint8_t interfaceid, uint8_t altIndex); /* * - * @brief 在给定端点上执行批量数据读取,返回读取的数据和长度,端点方向必须为数据读取可以设置超时时间 + * @brief Reads data on a specified endpoint during bulk transfer. The endpoint must be in the data reading direction. You can specify a timeout duration if needed. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param timeout 超时时间 - * @param data 获取写入的数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param timeout Indicates the timeout duration. + * @param data Indicates the read data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkTransferRead(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector &data); /* * - * @brief 在给定端点上执行批量数据写入,返回读取的数据和长度,端点方向必须为数据写入 + * @brief Writes data on a specified endpoint during bulk transfer. The endpoint must be in the data writing direction. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param timeout 超时时间 - * @param data 写入的数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param timeout Indicates the timeout duration. + * @param data Indicates the written data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkTransferWrite(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, const std::vector &data); /* * - * @brief 对此设备执行端点零的控制事务,传输方向由请求类型决定。如果requestType& - * USB_ENDPOINT_DIR_MASK是USB_DIR_OUT,则传输是写入,如果是USB_DIR_IN,则传输是读取。 + * @brief Performs control transfer for endpoint 0 of the device. The data transfer direction is determined by the request type. If the result of requestType& + * USB_ENDPOINT_DIR_MASK is USB_DIR_OUT, the endpoint is in the data writing direction; if the result is USB_DIR_IN, the endpoint is in the data reading direction. * - * @param dev usb设备地址信息 - * @param ctrl usb设备控制数据包结构 - * @param data 读取/写入 的数据 + * @param dev Indicates the USB device address. + * @param ctrl Indicates the control data packet structure. + * @param data Indicates the read data or written. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t ControlTransfer(const UsbDev &dev, const UsbCtrlTransfer &ctrl, std::vector &data); /* * - * @brief 在给定端点上执行中断数据读取,返回读取的数据和长度,端点方向必须为数据读取 + * @brief Reads data on a specified endpoint during interrupt transfer. The endpoint must be in the data reading direction. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param timeout 超时时间 - * @param data 读取的数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param timeout Indicates the timeout duration. + * @param data Indicates the read data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t InterruptTransferRead(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector &data); /* * - * @brief 在给定端点上执行中断数据写入,返回读取的数据和长度,端点方向必须为数据写入 + * @brief Writes data on a specified endpoint during interrupt transfer. The endpoint must be in the data writing direction. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param timeout 超时时间 - * @param data 读取的数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param timeout Indicates the timeout duration. + * @param data Indicates the read data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t InterruptTransferWrite(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector &data); /* * - * @brief 在给定端点上执行等时数据读取,返回读取的数据和长度,端点方向必须为数据读取 + * @brief Reads data on a specified endpoint during isochronous transfer. The endpoint must be in the data reading direction. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param timeout 超时时间 - * @param data 读取的数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param timeout Indicates the timeout duration. + * @param data Indicates the read data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t IsoTransferRead(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector &data); /* * - * @brief 在给定端点上执行等时数据写入,返回读取的数据和长度,端点方向必须为数据写入 + * @brief Writes data on a specified endpoint during isochronous transfer. The endpoint must be in the data writing direction. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param timeout 超时时间 - * @param data 读取的数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param timeout Indicates the timeout duration. + * @param data Indicates the written data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t IsoTransferWrite(const UsbDev &dev, const UsbPipe &pipe, int32_t timeout, std::vector &data); /* * - * @brief 将指定的端点进行异步数据发送或者接收请求,数据传输方向由端点方向决定 + * @brief Sends or receives requests for isochronous transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param clientData 用户数据 - * @param buffer 传输数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param clientData Indicates the client data. + * @param buffer Indicates the transferred data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t RequestQueue(const UsbDev &dev, @@ -278,137 +278,137 @@ public: const std::vector &buffer); /* * - * @brief 等待RequestQueue异步请求的操作结果 + * @brief Waits for the operation result of the requests for isochronous transfer in RequestQueue. * - * @param dev usb设备地址信息 - * @param clientData 用户数据 - * @param buffer 传输数据 - * @param timeout 超时时间 + * @param dev Indicates the USB device address. + * @param clientData Indicates the client data. + * @param buffer Indicates the transferred data. + * @param timeout Indicates the timeout duration. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t RequestWait(const UsbDev &dev, std::vector &clientData, std::vector &buffer, int32_t timeout); /* * - * @brief 取消待处理的数据请求 + * @brief Cancels the data transfer requests to be processed. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t RequestCancel(const UsbDev &dev, const UsbPipe &pipe); /* * - * @brief 获取从设备支持的功能列表(按位域表示)(从设备) + * @brief Obtains the list of functions (represented by bit field) supported by the current device. * - * @param funcs 获取当前设备的function的值 + * @param funcs Indicates the list of functions supported by the current device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t GetCurrentFunctions(int32_t &funcs); /* * - * @brief 设置从设备支持的功能列表(按位域表示)(从设备) + * @brief Sets the list of functions (represented by bit field) supported by the current device. * - * @param funcs 传入设备支持的function的值 + * @param funcs Indicates the list of functions supported by the current device. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t SetCurrentFunctions(int32_t funcs); /* * - * @brief 关闭设备,释放与设备相关的所有系统资源 + * @brief Closes a USB device to release all system resources related to the device. * - * @param portId port接口 ID - * @param powerRole 电源角色的值 - * @param dataRole 数据角色的值 + * @param portId Indicates the port ID of the USB interface. + * @param powerRole Indicates the power role. + * @param dataRole Indicates the data role. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); /* * - * @brief 查询port端口的当前设置 + * @brief Queries the current settings of a port. * - * @param portId port接口 ID - * @param powerRole 电源角色的值 - * @param dataRole 数据角色的值 - * @param mode 模式的值 + * @param portId Indicates the port ID of the USB interface. + * @param powerRole Indicates the power role. + * @param dataRole Indicates the data role. + * @param mode Indicates the mode. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t QueryPort(int32_t &portId, int32_t &powerRole, int32_t &dataRole, int32_t &mode); /* * - * @brief 绑定订阅者 + * @brief Binds a subscriber. * - * @param subscriber 订阅者信息 + * @param subscriber Indicates the subscriber. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static ErrCode BindUsbdSubscriber(const sptr &subscriber); /* * - * @brief 解绑订阅者 + * @brief Unbinds a subscriber. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static ErrCode UnbindUsbdSubscriber(); /* * - * @brief 异步批量读取数据,传输大量数据时使用 + * @brief Reads bulk data during isochronous transfer. This method is applicable to transfer of a huge amount of data. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param length 打算以什么长度读取数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param length Indicates the length of the data to read. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkRequstDataSize(const UsbDev &dev, const UsbPipe &pipe, uint32_t &length); /* * - * @brief 与BulkRequstDataSize配合使用,获取读取结果 + * @brief Obtains the data reading result. Use this method together with BulkRequstDataSize. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param data 读取到的数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param data Indicates the read data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkReadData(const UsbDev &dev, const UsbPipe &pipe, std::vector &data); /* * - * @brief 异步批量写数据,传输大量数据时使用 + * @brief Writes bulk data during isochronous transfer. This method is applicable to transfer of a huge amount of data. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param data 要写入的数据 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param data Indicates the written data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkWriteData(const UsbDev &dev, const UsbPipe &pipe, const std::vector &data); /* * - * @brief 与BulkWriteData配合使用,获取写入状态,由length描述 + * @brief Obtains the data writing status based on length. Use this method together with BulkWriteData. * - * @param dev usb设备地址信息 - * @param pipe usb设备pipe信息 - * @param length 已经写入的数据长度 + * @param dev Indicates the USB device address. + * @param pipe Indicates the pipe of the USB device. + * @param length Indicates the length of the written data. * - * @return 0 表示成功,其他返回值表示失败 + * @return Returns 0 if the operation is successful; returns a non-0 value if the operation fails. * @since 3.0 */ static int32_t BulkGetWriteCompleteLength(const UsbDev &dev, const UsbPipe &pipe, uint32_t &length); diff --git a/en/device-dev/driver/Readme-EN.md b/en/device-dev/driver/Readme-EN.md index c2c3dea84dfb01310ae917c9d6c60dd2c5a1e672..2c0d763aeefc102df40371b779547d8cad78ead0 100644 --- a/en/device-dev/driver/Readme-EN.md +++ b/en/device-dev/driver/Readme-EN.md @@ -11,7 +11,7 @@ - [ADC](driver-platform-adc-develop.md) - [GPIO](driver-platform-gpio-develop.md) - [I2C](driver-platform-i2c-develop.md) - - [MIPI-DSI](driver-platform-mipidsi-develop.md) + - [MIPI DSI](driver-platform-mipidsi-develop.md) - [MMC](driver-platform-mmc-develop.md) - [PWM](driver-platform-pwm-develop.md) - [RTC](driver-platform-rtc-develop.md) @@ -19,6 +19,7 @@ - [SPI](driver-platform-spi-develop.md) - [UART](driver-platform-uart-develop.md) - [Watchdog](driver-platform-watchdog-develop.md) + - [MIPI CSI](driver-platform-mipicsi-develop.md) - [Platform Driver Usage](driver-platform.md) - [GPIO](driver-platform-gpio-des.md) - [I2C](driver-platform-i2c-des.md) @@ -29,9 +30,11 @@ - [Watchdog](driver-platform-watchdog-des.md) - [MIPI DSI](driver-platform-mipidsi-des.md) - [PWM](driver-platform-pwm-des.md) + - [MIPI CSI](driver-platform-mipicsi-des.md) - [Peripheral Driver Usage](driver-peripherals.md) - [LCD](driver-peripherals-lcd-des.md) - - [TOUCHSCREEN](driver-peripherals-touch-des.md) + - [Touchscreen](driver-peripherals-touch-des.md) - [Sensor](driver-peripherals-sensor-des.md) - [WLAN](driver-peripherals-external-des.md) + - [Audio](driver-peripherals-audio-des.md) - [USB](driver-peripherals-usb-des.md) \ No newline at end of file diff --git a/en/device-dev/driver/driver-hdf-development.md b/en/device-dev/driver/driver-hdf-development.md index bac84cd8058471e746d640a3c04cc14c7d4a7bea..b33052bf687c836944c115b573028446ec195224 100644 --- a/en/device-dev/driver/driver-hdf-development.md +++ b/en/device-dev/driver/driver-hdf-development.md @@ -1,20 +1,20 @@ # Driver Development -- [Introduction](#section157425168112) +- [Driver Model](#section157425168112) - [How to Develop](#section1969312275533) -## Introduction +## Driver Model -The HDF is designed based on the component-based driver model. It provides more refined driver management to make driver development and deployment more standard. Device drivers of the same type are placed in the same host. You can develop and deploy the drivers separately. One driver can have multiple nodes. [Figure 1](#fig3580184214210) shows the HDF driver model. +The HDF is designed based on the component-based driver model. This model allows refined driver management and normalizes driver development and deployment. Device drivers of the same type are placed in the same host. You can develop and deploy the drivers separately. One driver can have multiple nodes. [Figure 1](#fig3580184214210) shows the HDF driver model. **Figure 1** HDF driver model ![](figures/hdf-driver-model.png "hdf-driver-model") ## How to Develop -Driver development based on the HDF consists of two parts: driver implementation and driver configuration. The details are as follows: +Driver development based on the HDF involves driver implementation and driver configuration. The development procedure is as follows: -1. Implement driver. +1. Implement a driver. To implement a driver, compile driver service code and register a driver entry. @@ -64,34 +64,94 @@ Driver development based on the HDF consists of two parts: driver implementation HDF_INIT(g_sampleDriverEntry); ``` -2. Compile the driver code. - - Use the **Makefile** template provided by the HDF to compile the driver code. +2. Build the driver. - ``` - include $(LITEOSTOPDIR)/../../drivers/adapter/lite/khdf/lite.mk # (Mandatory) Import the predefined content of the HDF. - MODULE_NAME := # Generated result file - LOCAL_INCLUDE: = # Header file directory of the driver - LOCAL_SRCS : = # Source code file of the driver - LOCAL_CFLAGS : = # Custom compilation options - include $(HDF_DRIVER) # Import the template Makefile to complete compilation. - ``` + - LiteOS - - Link the compilation result file to the kernel image by adding the result file to **hdf\_vendor.mk** in the **vendor** directory. The following is an example: + Modify **makefile** and **BUILD.gn**: - ``` - LITEOS_BASELIB += -lxxx # Static library generated through linking - LIB_SUBDIRS += # Directory of Makefile - ``` + * makefile: + + Use the **makefile** template provided by the HDF to compile the driver code. + + ``` + include $(LITEOSTOPDIR)/../../drivers/adapter/khdf/liteos/lite.mk # Import the content predefined by the HDF. This operation is mandatory. + MODULE_NAME := # File to be generated. + LOCAL_INCLUDE: = # Header file directory of the driver. + LOCAL_SRCS : = # Source code file of the driver. + LOCAL_CFLAGS : = # Custom compilation options. + include $(HDF_DRIVER) # Import the makefile template to complete the compilation. + ``` + + Add the path of the generated file to **hdf_lite.mk** in the **drivers/adapter/khdf/liteos** directory to link the file to the kernel image. The following is an example: + + ``` + LITEOS_BASELIB += -lxxx # Static library generated by the link. + LIB_SUBDIRS += # Directory in which the driver code makefile is located. + ``` + + * BUILD.gn: + + Add **BUILD.gn**. The content of **BUILD.gn** is as follows: + + ``` + import("//build/lite/config/component/lite_component.gni") + import("//drivers/adapter/khdf/liteos/hdf.gni") + module_switch = defined(LOSCFG_DRIVERS_HDF_xxx) + module_name = "xxx" + hdf_driver(module_name) { + sources = [ + "xxx/xxx/xxx.c", # Source code file of the driver + ] + public_configs = [ ":public" ] # Configuration applied to dependencies + } + config("public") {# Configuration of the dependencies + include_dirs = [ + "xxx/xxx/xxx", # Directory of the dependency header file. + ] + } + ``` + + Add the directory where the **BUILD.gn** file of the driver is located to **/drivers/adapter/khdf/liteos/BUILD.gn**. + + ``` + group("liteos") { + public_deps = [ ":$module_name" ] + deps = [ + "xxx/xxx", # Directory where the BUILD.gn of the driver is located. It is a relative path to /drivers/adapter/khdf/liteos. + ] + } + ``` + + - Linux + + To define the driver control macro, add the **Kconfig** file to the driver directory **xxx** and add the path of the **Kconfig** file to **drivers/adapter/khdf/linux/Kconfig**. + + ``` + source "drivers/hdf/khdf/xxx/Kconfig" # Kernel directory to which the HDF module is soft linked. + ``` + + Add the driver directory to **drivers/adapter/khdf/linux/Makefile**. + + ``` + obj-$(CONFIG_DRIVERS_HDF) += xxx/ + ``` + + Add a **Makefile** to the driver directory **xxx** and add code compiling rules of the driver to the **Makefile** file. + + ``` + obj-y += xxx.o + ``` 3. Configure the driver. - HDF Configuration Source \(HCS\) is the source code that describes the configuration of the HDF. For details about the HCS, see [Driver Configuration Management](driver-hdf-manage.md). + HDF Configuration Source (HCS) is the source code that describes the configuration of the HDF. For details about the HCS, see [Driver Configuration Management](driver-hdf-manage.md). The driver configuration consists of the driver device description defined by the HDF and private driver configuration information. - - \(Mandatory\) Driver device description + - (Mandatory) Driver device description - The information required for the HDF to load drivers comes from the driver device description defined by the HDF. Therefore, the device description must be added to the configuration file **device\_info.hcs** defined by the HDF for drivers developed based on the HDF. The following is an example: + The information required for the HDF to load drivers comes from the driver device description defined by the HDF. Therefore, the device description must be added to the configuration file **device_info.hcs** defined by the HDF for drivers developed based on the HDF.The following is an example: ``` root { @@ -165,7 +225,6 @@ Driver development based on the HDF consists of two parts: driver implementation > DEVICE_PRELOAD_INVALID > } DevicePreload; > ``` -> When the **preload** field in the configuration file is set to **0** \(**DEVICE\_PRELOAD\_ENABLE**\), the driver is loaded by default during system startup. When this field is set to **1** \(**DEVICE\_PRELOAD\_ENABLE\_STEP2**\), the driver is loaded after system startup if quick start is enabled; it is loaded during system startup otherwise. When this field is set to **2** \(**DEVICE\_PRELOAD\_DISABLE**\), the driver is not loaded by default during system startup and can be dynamically loaded later. If the driver service does not exist when a user-level application obtains the driver service \(for details about how to obtain the driver service, see [Driver Message Mechanism Management](driver-hdf-message-management.md)\), the HDF attempts to dynamically load the driver. +> If the **preload** field in the configuration file is set to **0** (DEVICE\_PRELOAD\_ENABLE), the driver is loaded by default during the system boot process. If **preload** is set to **1** (DEVICE\_PRELOAD\_ENABLE\_STEP2), the driver is loaded after a quick start is complete if the system supports quick start. If the system does not support quick start, the value **1** has the same meaning as DEVICE\_PRELOAD\_ENABLE. If **preload** is set to **2** (DEVICE\_PRELOAD\_DISABLE), the driver is dynamically loaded instead of being loaded during the system boot process. When a user-mode process requests the driver service (for details, see [Driver Message Mechanism Management](driver-hdf-news.md)), the HDF attempts to dynamically load the driver if the driver service does not exist. >- Sequential loading \(drivers must be loaded by default\) > In the configuration file, the **priority** field \(the value is an integer ranging from 0 to 200\) indicates the priority of the host and driver. For drivers in different hosts, a smaller host priority value indicates a higher driver loading priority; for drivers in the same host, a smaller driver priority value indicates a higher driver loading priority. - diff --git a/en/device-dev/driver/driver-hdf-sample.md b/en/device-dev/driver/driver-hdf-sample.md index b800b9fffa426949deaa863cdf8bd65e0a279b65..56e8e4526df79e1a530210a3e31f63838ca732e5 100644 --- a/en/device-dev/driver/driver-hdf-sample.md +++ b/en/device-dev/driver/driver-hdf-sample.md @@ -50,7 +50,7 @@ root { ## Compiling the Driver Code -The following is the sample driver code compiled based on HDF: +The following is the sample driver code compiled based on HDF (for details, see [Driver Development](driver-hdf-development.md)): ``` #include @@ -122,7 +122,7 @@ HDF_INIT(g_sampleDriverEntry); ## Compiling the Code for Interaction -The following is the sample code compiled based on HDF for interaction between the driver and user-state applications: +The following is the sample code compiled based on HDF for interaction between the driver and user-state applications. You can place the code in **drivers/adapter/uhdf** for compilation. For details about the **build.gn** file, see **drivers/framework/sample/platform/uart/dev/build.gn**. ``` #include diff --git a/en/device-dev/driver/driver-peripherals-audio-des.md b/en/device-dev/driver/driver-peripherals-audio-des.md new file mode 100644 index 0000000000000000000000000000000000000000..7529e34c2392c6661ec30ce34b2f62aead119457 --- /dev/null +++ b/en/device-dev/driver/driver-peripherals-audio-des.md @@ -0,0 +1,1408 @@ +# Audio + +- **[Audio Driver Overview](#section1000)** + +- **[Audio Driver Architecture](#section2000)** + +- **[Audio Driver Development](#section3000)** + + - **[Audio ADM Architecture](#section3100)** + - [Startup Process](#section3111) + - [Playback Process](#section3112) + - [Control Process](#section3113) + + - **[Audio Driver Development Procedure](#section3200)** + - [Development on an Adapted Platform](#section3221) + - [Development on a New Platform](#section3222) + +- **[Audio Driver Development Examples](#section4000)** + - [Codec Driver Development Example](#section4100) + - [Filling in Codec Data Structures](#section4111) + - [Initializing the Codec Device and Codec DAI Device](#section4112) + - [Implementing the Codec Operation Function Set](#section4113) + - [Registering and Binding Codec to HDF](#section4114) + - [Configuring HCS](#section4115) + - [Accessory Driver Development Example](#section4200) + - [Filling in Accessory Data Structures](#section4221) + - [Initializing the Accessory Device and Accessory DAI Device](#section4222) + - [Implementing the Accessory Operation Function Set](#section4223) + - [Registering and Binding Accessory to HDF](#section4224) + - [Configuring HCS](#section4225) + - [Platform Driver Development Example](#section4300) + - [Filling in Platform Data Structures](#section4331) + - [Initializing the DMA Device](#section4332) + - [Implementing the DMA Operation Function Set](#section4333) + - [Registering and Binding Platform to HDF](#section4334) + - [Configuring HCS](#section4335) + - [DAI Driver Development Example](#section4400) + - [Filling in DAI Data Structures](#section4441) + - [Initializing the DAI Device](#section4442) + - [Implementing the DAI Operation Function Set](#section4443) + - [Registering and Binding DAI to HDF](#section4444) + - [Configuring HCS](#section4445) + - [Adding Compilation Configuration to Makefile](#section4500) + - [Source Code Structure and Directory](#section4600) + +- **[HAL-based Development Procedure and Example](#section5000)** + - [Development Procedure](#section5100) + - [Development Example](#section5200) + +- **[Summary](#section9999)** + +# Audio Driver Overview + +A multimedia system is an indispensable part in Internet of Things (IoT) devices. Audio is an important module of the multimedia system, and building an audio driver model is particularly important in device development. + +This document describes the audio driver architecture and functional modules and how to develop audio drivers based on the Hardware Driver Foundation (HDF). Chip vendors can develop their own drivers and invocation of Hardware Abstraction Layer (HAL) APIs based on the driver architecture. + + + +# Audio Driver Architecture + +The audio driver architecture is implemented based on the [HDF](https://device.harmonyos.com/en/docs/documentation/guide/driver-hdf-overview-0000001051715456). The audio driver architecture is as follows: +![](figures/Audio_architecture.png) + +The driver architecture consists of the following: +- Hardware Device Interface (HDI) adapter: implements the audio HAL driver (HDI adaptation) and provides hardware driver capability interfaces for the audio service (frameworks). The HDI adapter provides interface objects such as Audio Manager, Audio Adapter, Audio Control, Audio Capture, and Audio Render. +- Audio Interface Lib: works with the Audio Driver Model (ADM) in the kernel to control audio hardware, read recording data, and write playback data. The **Stream_ctrl_common** in the Audio Interface Lib interacts with the audio HDI adapter layer. +- ADM: helps system developers to develop scenario-specific applications for the multimedia audio subsystem. With the ADM, codec and DSP device vendors can adapt their driver code based on the unified interfaces provided by the ADM and implement quick development and easy adaptation to the OpenHarmony system. +- Audio Control Dispatch: dispatches the control instructions from the Audio Interface Lib to the driver layer. +- Audio Stream Dispatch: dispatches the data from the Audio Interface Lib to the driver layer. + +- Card Manager: manages multiple audio adapters. Each audio adapter consists of the digital audio interface (DAI), platform, codec, accessory, DSP, and Smart Audio Power Manager (SAPM) modules. +- Platform Drivers: implement driver adaptation. +- SAPM: optimizes the power consumption policy of the ADM. + +# Audio Driver Development + +The following uses the Hi3516D V300 as an example to describe how to develop drivers based on the audio driver architecture. + +## Audio ADM Architecture +The audio driver provides the **hdf_audio_render**, **hdf_audio_capture**, and **hdf_audio_control** services for the HDI layer. The driver service nodes in the **dev** directory of the development board are as follows: + +```c +# ls -l hdf_audio* +crw-rw---- 1 system system 248, 6 1970-01-01 00:00 hdf_audio_capture // Voice recording service. +crw-rw---- 1 system system 248, 4 1970-01-01 00:00 hdf_audio_codec_dev0 // Name of audio adapter 0. +crw-rw---- 1 system system 248, 4 1970-01-01 00:00 hdf_audio_codec_dev1 // Name of audio adapter 1. +crw-rw---- 1 system system 248, 5 1970-01-01 00:00 hdf_audio_control // Audio control service. +crw-rw---- 1 system system 248, 7 1970-01-01 00:00 hdf_audio_render // Audio playback service. +``` + +The audio adapters have the following driver services: + +hdf\_audio\_codec\_dev0 +- **dma\_service\_0**: direct memory access (DMA) service +- **dai_service**: CPU DAI service +- **codec\_service\_0**: codec service (built-in codec) +- **dsp\_service\_0**: DSP service (optional) + +hdf\_audio\_codec\_dev1 +- **dma\_service\_0**: DMA service +- **dai_service**: CPU DAI service +- **codec\_service\_1**: accessory service (SmartPA) +- **dsp\_service\_0**: DSP service (optional) + +### Startup Process + +![](figures/ADM_startup_flowchart.png) + +1. When the system starts, the platform, codec, accessory, DSP, and DAI drivers of the audio module are loaded first. Each driver obtains the configuration information from its configuration file and saves the obtained information to the data structures. + +2. Each driver module calls the ADM registration interface to add itself to the linked list of the driver module. + +3. The ADM obtains the hdf_audio_driver_0 and hdf_audio_driver_1 configuration and loads the devices of each module. + +4. The ADM module initializes each module device by calling the initialization API of the respective module. + +5. The initialized audio devices are added to the cardManager linked list. + +### Playback Process +![=](figures/ADM_playback_flowchart.png) +1. The Audio Interface Lib sends the **Render Open** instruction to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the API of each module to deliver the instruction. + +2. The Audio Interface Lib sends a path select instruction to the Control Dispatch service. The Control Dispatch service calls the DAI API to set the path. + +3. The Audio Interface Lib sends hardware parameters to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the API of each module to set the hardware parameters. + +4. The Audio Interface Lib sends the start playing instruction to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the API of each module to perform related settings for each module. + +5. The Audio Interface Lib sends audio data to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the **Platform AudioPcmWrite** API to send the audio data to DMA. + +6. The Audio Interface Lib sends the stop playing instruction to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the stop API of each module to perform related stop settings for each module. + +7. The Audio Interface Lib sends the **Render Close** instruction to the Audio Stream Dispatch service. The Audio Stream Dispatch service calls the **Platform AudioRenderClose** API to release resources. + +### Control Process + +![](figures/ADM_control_flowchart.png) + +1. When the volume needs to be adjusted, the Audio Interface Lib sends an instruction for obtaining the volume range to the Control Dispatch service. The Control Dispatch service parses the instruction and calls **get()** of the codec module to obtain the volume range. +2. The Audio Interface Lib sends an instruction for setting the volume to the Control Dispatch service. The Control Dispatch service parses the instruction and calls **Set()** of the codec module to set the volume. + +## Audio Driver Development Procedure + +### Development on an Adapted Platform + +The following figure shows the process for developing the codec or accessory (SmartPA) driver on a chip platform (Hi3516D V300) to which the ADM has adapted. + +![](figures/development_flowchart_1.png) + +1. Add register information to the private HDF configuration source (HCS) of the codec or SmartPA based on the chip description. + + If the workflow of the newly added codec or SmartPA is the same as that of the existing codec or SmartPA, you do not need to implement the operation function set or configure the compilation file for the newly added codec or SmartPA. + +2. Perform build, debugging, and testing. + +### Development on a New Platform + +The following figure shows the driver development process if the ADM has not adapted to the platform. + +![](figures/development_flowchart_2.png) + +The codec (optional), DAI, DMA, DSP (optional), and SmartPA (optional) modules of the audio adapter need to be adapted to the new platform. + +1. Add register information of each module driver to the private configuration file of the respective module according to the chip description. + +2. Implement the operation function set of each module. + +3. Modify the compilation file of the audio module. + +4. Perform build, debugging, and testing. + + + +# Audio Driver Development Examples + +Code path: **drivers/peripheral/audio** + +The following uses Hi3516D V300 as an example to describe how to develop the audio codec driver, accessory driver, DAI driver, and platform driver. + +## Codec Driver Development Example +Code path: **drivers/peripheral/audio/chipsets/hi3516dv300/codec** + +The major steps for developing the codec driver are as follows: +1. Define and fill in a codec instance. +2. Implement callbacks for the codec instance. +3. Register and bind the codec instance to the HDF. +4. Configure the HCS and makefile. + +### Filling in Codec Data Structures + +Fill in the following data structures for the codec module: + +- **g_codecData**: operation function set and private data set of the codec device. + +- **g_codecDaiDeviceOps**: codec DAI device operation function set, including APIs for starting transmission and setting parameters. + +- **g_codecDaiData**: operation function set and private data set of the digital audio interface of the codec. + +```c +struct CodecData g_codecData = { + .Init = CodecDeviceInit, // Initialize the codec device (need to be implemented for a new platform). + .Read = AudioDeviceReadReg, // Read the register (already implemented in the existing framework and no adaptation needed). + .Write = AudioDeviceWriteReg, // Write the register (already implemented in the existing framework and no adaptation needed). +}; + +struct AudioDaiOps g_codecDaiDeviceOps = { + .Startup = CodecDaiStartup, // Start transmission (need to be implemented for a new platform). + .HwParams = CodecDaiHwParams, // Set parameters (need to be implemented for a new platform). +}; + +struct DaiData g_codecDaiData = { + .DaiInit = CodecDaiDeviceInit, // Initialize the codec DAI device (need to be implemented for a new platform). + .ops = &g_codecDaiDeviceOps, // codec DAI device operation function set. +}; +``` + +### Initializing the Codec Device and Codec DAI Device + +**CODECDeviceInit** sets audio input/audio output (AIAO), initializes registers, inserts **g_audioControls** into the controller linked list, initializes the power management, and selects a path. + +```c +int32_t CodecDeviceInit(struct AudioCard *audioCard, struct CodecDevice *codec) +{ + ... + /* Register set() and get() of the AIAO module on the Hi3516 platform. */ + CodecSetCtlFunc(codec->devData, AudioCodecAiaoGetCtrlOps, AudioCodecAiaoSetCtrlOps) + ... + /* Hi3516 codec register IoRemap */ + CodecHalSysInit(); + ... + /* Initialize the codec registers of the Hi3516 platform. */ + CodecRegDefaultInit(codec->devData->regCfgGroup); + ... + /* Insert g_audioControls of the Hi3516 platform to the controller linked list. */ + AudioAddControls(audioCard, codec->devData->controls, codec->devData->numControls); + ... + /* Load the codec of the Hi3516 platform to the SAPM. */ + AudioSapmNewComponents(audioCard, codec->devData->sapmComponents, codec->devData->numSapmComponent); + ... + /* Insert the codec of the Hi3516 platform to the audioRoutes linked list. */ + AudioSapmAddRoutes(audioCard, g_audioRoutes, HDF_ARRAY_SIZE(g_audioRoutes); + ... + AudioSapmNewControls(audioCard); + ... + /* Hi3516 codec power management */ + AudioSapmSleep(audioCard); + ... + return HDF_SUCCESS; +} +``` + +**CodecDaiDeviceInit** initializes the codec DAI device. This API is not used on the Hi3516 and is reserved. + +```c +int32_t CodecDaiDeviceInit(struct AudioCard *card, const struct DaiDevice *device) + +{ + ... + AUDIO_DRIVER_LOG_DEBUG("codec dai device name: %s\n", device->devDaiName); + (void)card; + return HDF_SUCCESS; +} +``` + +### Implementing the Codec Operation Function Set + +The codec module is encapsulated with the **read()** and **write()** functions of the read and write registers at the operating system abstraction layer (OSAL). + +If the new platform cannot use the OSAL **read()** and **write()** functions to operate registers, you should implement them. + +```c +int32_t AudioDeviceReadReg(unsigned long virtualAddress, uint32_t reg, uint32_t *val) +{ + ... + *val = OSAL_READL((void *)((uintptr_t)(virtualAddress + reg))); + return HDF_SUCCESS; +} + +int32_t AudioDeviceWriteReg(unsigned long virtualAddress, uint32_t reg, uint32_t value) +{ + OSAL_WRITEL(value, (void *)((uintptr_t)(virtualAddress + reg))); + return HDF_SUCCESS; +} +``` + +**CodecDaiStartup** completes startup settings. + +```c +int32_t CodecDaiStartup(const struct AudioCard *card, const struct DaiDevice *device) +{ + int32_t ret; + ... + (void)card; + ret = CodecSetAdcTuneEnable(device->devData->regCfgGroup); + ... + return HDF_SUCCESS; +} +``` + +**CodecDaiHwParams** sets parameters, including the sampling rate and bit width. + +```c +int32_t CodecDaiHwParams(const struct AudioCard *card, const struct AudioPcmHwParams *param) +{ + unsigned int bitWidth; + struct CodecDaiParamsVal codecDaiParamsVal; + ... + int ret = AudioFramatToBitWidth(param->format, &bitWidth); + ... + codecDaiParamsVal.frequencyVal = param->rate; + codecDaiParamsVal.formatVal = bitWidth; + ret = CodecDaiParamsUpdate(card->rtd->codecDai->devData->regCfgGroup, codecDaiParamsVal); + ... + return HDF_SUCCESS; +} +``` + +### Registering and Binding Codec to HDF + +This process depends on the driver implementation mode of the HDF. For details, see [HDF](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf.md). + +Fill in the **g_codecDriverEntry** structure. Ensure that the value of **moduleName** is the same as that in **device_info.hcs**. Implement the pointers to the **Bind**, **Init**, and **Release** functions. + +drivers/peripheral/audio/chipsets/hi3516dv300/codec/src/hi3516_codec_adapter.c + +```c +struct HdfDriverEntry g_codecDriverEntry = { + .moduleVersion = 1, + .moduleName = "CODEC_HI3516", + .Bind = CodecDriverBind, + .Init = CodecDriverInit, + .Release = CodecDriverRelease, +}; +HDF_INIT(g_codecDriverEntry); +``` + +**CodecDriverBind** binds the device in the HDF to the codec and registers the codec service with the HDF. + +```c +static int32_t CodecDriverBind(struct HdfDeviceObject *device) +{ + struct CodecHost *codecHost = (struct CodecHost *)OsalMemCalloc(sizeof(*codecHost)); + ... + codecHost->device = device; + device->service = &codecHost->service; + return HDF_SUCCESS; +} +``` + +**CodecDriverInit** obtains the codec service name and private register configuration, and inserts them into the linked list by using **AudioRegisterCodec**. + +```c +static int32_t CodecDriverInit(struct HdfDeviceObject *device) +{ + ... + CodecGetConfigInfo(device, &g_codecData); + CodecSetConfigInfo(&g_codecData, &g_codecDaiData); + CodecGetServiceName(device, &g_codecData.drvCodecName); + CodecGetDaiName(device, &g_codecDaiData.drvDaiName); + AudioRegisterCodec(device, &g_codecData, &g_codecDaiData); + ... + return HDF_SUCCESS; +} +``` + +**CodecDriverRelease** releases driver resources. + +```c +static void CodecDriverRelease(struct HdfDeviceObject *device) +{ + codecHost = (struct CodecHost *)device->service; + OsalMemFree(codecHost); +} +``` + +### Configuring HCS + +Configure the driver node, loading sequence, and service name in the .hcs file. For details about the HCS syntax, see [Driver Configuration Management](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf-manage.md) in the HDF. + +Path of the standard-system configuration file: + +**vendor/hisilicon/Hi3516DV300/hdf_config/khdf/** + +Path of the small-system configuration file: + +**vendor/hisilicon/hispark_taurus/hdf_config/** + +**Configuring Codec Device Information in device_info.hcs** + +Add codec node configuration. Modify **moduleName** in the configuration file. The value must be the same as **moduleName** in the **HdfDriverEntry** structure. Generally, the value should present the hardware platform, for example, **moduleName = "CODEC_HI3516"**. + +The code snippet is as follows: + +```c + audio :: host { + device_codec :: device { + device0 :: deviceNode { + policy = 1; // The codec module provides services only for the kernel. + priority = 50; // The codec module must be loaded before the load of the HDF_AUDIO module. + preload = 0; + permission = 0666; + moduleName = "CODEC_HI3516"; // The value must be the same as moduleName in HdfDriverEntry. + serviceName = "codec_service_0"; // Name of the service provided externally. + deviceMatchAttr = "hdf_codec_driver"; // Name of the private attribute, which is used to match the corresponding private data (including the register configuration). + } + } +``` + +**Configuring Dependencies in audio_config.hcs** + +Configure dependencies between the codec, platform, DAI, DSP, and accessory for the audio adapters. + +The code snippet is as follows: + +```c +root { + platfrom { + ... + controller_0x120c1001 :: card_controller { + // Set the private data attribute name, which must be the same as deviceMatchAttr in device_info.hcs. + match_attr = "hdf_audio_driver_1"; + serviceName = "hdf_audio_smartpa_dev0"; // Name of the service provided externally. + accessoryName = "codec_service_1"; // External codec service name. + platformName = "dma_service_0"; // DMA service. + cpuDaiName = "dai_service"; // CPU DAI service. + accessoryDaiName = "accessory_dai"; // External DAI. + dspName = "dsp_service_0"; // DSP service name. + dspDaiName = "dsp_dai"; // DSP DAI. + } + } +} +``` + +**Configuring Private Registers in codec_config.hcs** + +The configuration matches **deviceMatchAttr** of the codec configured in **device_info.hcs**. It includes the register configuration. + +Binding the control functionality configuration is to configure the control functionalities and their register parameters in the .hcs file according to unified structure specifications. The configuration can be obtained and parsed, and added to the controller linked list. + +- **regConfig**: register and control functionality configuration + +- **ctrlParamsSeqConfig**: control functionality register configuration + +- **daiStartupSeqConfig**: DAI startup configuration + +- **daiParamsSeqConfig**: playback parameter configuration + +- **resetSeqConfig**: reset process register configuration + +- **initSeqConfig**: initialization process register configuration + +- **controlsConfig**: control functionality configuration. The **array index** (specific service scenario) and **iface** (same as the HAL) are of fixed values. + +``` +array index +0: Main Playback Volume +1: Main Capture Volume +2: Playback Mute +3: Capture Mute +4: Mic Left Gain +5: Mic Right Gain +6: External Codec Enable +7: Internally Codec Enable +8: Render Channel Mode +9: Capture Channel Mode +iface +0: virtual dac device +1: virtual adc device +2: virtual adc device +3: virtual mixer device +4: Codec device +5: PGA device +6: AIAO device +``` + +**ctrlParamsSeqConfig**: control functionality register configuration. The sequence of the configuration items is the same as that in **controlsConfig**, indicating the register configuration corresponding to a functionality. + +```c + root { + platfrom { + template codec_controller { + match_attr = ""; + serviceName = ""; + codecDaiName = ""; + } + controller_0x120c1030 :: codec_controller { + match_attr = "hdf_codec_driver"; + serviceName = "codec_service_0"; + codecDaiName = "codec_dai"; + + /* Base address of the Hi3516 register*/ + idInfo { + chipName = "hi3516"; // Codec name + chipIdRegister = 0x113c0000; // Codec base address + chipIdSize = 0x1000; // Codec address offset + } + + /* Register configuration, including configuration of registers */ + regConfig { + /* reg: register address + rreg: register address + shift: shift bits + rshift: rshift bits + min: min value + max: max value + mask: mask of value + invert: enum InvertVal 0-uninvert 1-invert + value: value + */ + + /* reg, value */ + initSeqConfig = [ + 0x14, 0x04000002, + 0x18, 0xFD200004, + 0x1C, 0x00180018, + 0x20, 0x83830028, + 0x24, 0x00005C5C, + 0x28, 0x00130000, + 0x30, 0xFF035A00, + 0x34, 0x08000001, + 0x38, 0x06062424, + 0x3C, 0x1E1EC001, + 0x14, 0x04000002 + ]; + + /* Control functionality configuration + array index, iface, enable*/ + controlsConfig = [ + 0, 0, 0, + 1, 1, 1, + 2, 0, 1, + 3, 1, 1, + 4, 2, 1, + 5, 2, 1, + 8, 6, 0, + 9, 6, 0, + ]; + /* Control functionality register configuration + reg, rreg, shift, rshift, min, max, mask, invert, value */ + ctrlParamsSeqConfig = [ + 0x3c, 0x3c, 24, 24, 0x0, 0x57, 0x7F, 1, 0, //"Main Capture Volume" + 0x38, 0x38, 31, 31, 0x0, 0x1, 0x1, 0, 0, //"Playback Mute" + 0x3c, 0x3c, 31, 31, 0x0, 0x1, 0x1, 0, 0, //"Capture Mute" + 0x20, 0x20, 16, 16, 0x0, 0xF, 0x1F, 0, 0, //"Mic Left Gain" + 0x20, 0x20, 24, 24, 0x0, 0xF, 0x1F, 0, 0, // "Mic Right Gain" + 0x2000, 0x2000, 16, 16, 0x0, 0x7, 0x7, 0, 0, // "Render Channel Mode" + 0x1000, 0x1000, 16, 16, 0x0, 0x7, 0x7, 0, 0 // "Capture Channel Mode" + ]; + + /* After the upper layer delivers parameters, write audio-related data to registers. + reg, rreg, shift, rshift, min, max, mask, invert, value */ + daiParamsSeqConfig = [ + 0x30, 0x30, 13, 13, 0x0, 0x1F, 0x1F, 0, 0x0, // i2s_frequency + 0x1C, 0x1C, 6, 6, 0x0, 0x3, 0x3, 0, 0x0, // adc_mode_sel + 0x30, 0x30, 22, 22, 0x0, 0x3, 0x3, 0, 0x0, // i2s_datawith + ]; + + /* Configuration of the power management function register. + reg, rreg, shift, rshift, min, max, mask, invert, value */ + ctrlSapmParamsSeqConfig = [ + 0x20, 0x20, 23, 23, 0x0, 0x1, 0x1, 0, 0, //LPGA MIC 0 -- connect MIC + 0x20, 0x20, 31, 31, 0x0, 0x1, 0x1, 0, 0, //RPGA MIC 0 -- connect MIC + 0x30, 0x30, 27, 27, 0x0, 0x1, 0x1, 0, 0, //dacl to dacr mixer + 0x30, 0x30, 26, 26, 0x0, 0x1, 0x1, 0, 0 //dacr to dacl mixer + ]; + + /* + Power management component configuration + componentName: function name, {"ADCL", "ADCR", "DACL", "DACR", "LPGA", "RPGA", "SPKL", "SPKR", "MIC"} array index. + sapmType,compNameIndex,reg, mask,shift,invert, kcontrolNews,kcontrolsNum + */ + sapmComponent = [ + 10, 0, 0x20, 0x1, 15, 1, 0, 0, //ADCL + 10, 1, 0x20, 0x1, 14, 1, 0, 0, //ADCR + 11, 2, 0x14, 0x1, 11, 1, 0, 0, //DACL + 11, 3, 0x14, 0x1, 12, 1, 0, 0, //DACR + 8, 4, 0x20, 0x1, 13, 1, 1, 1, //LPGA + 8, 5, 0x20, 0x1, 12, 1, 2, 1, //RPGA + 15, 6, 0, 0x1, 0, 0, 3, 1, //SPKL + 15, 7, 0, 0x1, 0, 0, 4, 1, //SPKR + 0, 8, 0, 0x1, 0, 0, 0, 0 //MIC + ]; + + /* Power management function configuration + array index, iface, enable + */ + sapmConfig = [ + 0, 5, 1, + 1, 5, 1, + 2, 0, 1, + 3, 0, 1 + ]; + } + } + } +} +``` + +Read the .hcs files in the C code to obtain register configuration. + +```c +static int32_t CodecDriverInit(struct HdfDeviceObject *device) +{ + ... + CodecGetConfigInfo(device, &g_codecData) ; + CodecSetConfigInfo(&g_codecData, &g_codecDaiData); + ... + return HDF_SUCCESS; +} +``` + +When the codec is registered, the input parameter **device** contains controller_0x120c1030 node information. You only need to parse the node to obtain the configuration information. + +```c +int32_t CodecGetConfigInfo(const struct HdfDeviceObject *device, struct CodecData *codecData) +{ + codecData->regConfig = (struct AudioRegCfgData *)OsalMemCalloc(sizeof(*(codecData->regConfig))); + CodecGetRegConfig(device, codecData->regConfig); + return HDF_SUCCESS; +} +``` + +Obtain the node configuration to configure the node. + +```c +int32_t CodecGetRegConfig(const struct HdfDeviceObject *device, struct AudioRegCfgData *configData) +{ + ... + drsOps = DeviceResourceGetIfaceInstance(HDF_CONFIG_SOURCE); + ... + idNode = drsOps->GetChildNode(root, "idInfo"); + ParseAudioAttr(drsOps, idNode, &configData->audioIdInfo); + regCfgNode = drsOps->GetChildNode(root, "regConfig"); + ... + DEV_RES_NODE_FOR_EACH_ATTR(regCfgNode, regAttr) { + ... + return HDF_SUCCESS; +} +``` + +Obtain and use the configuration of the **regConfig** node. After the configuration files are parsed, the register information in the code can be directly updated. + +```c +int32_t CodecDeviceInit(struct AudioCard *audioCard, struct CodecDevice *codec) +{ +... + if (CodecRegDefaultInit(codec->devData->regCfgGroup) != HDF_SUCCESS) { + AUDIO_DRIVER_LOG_ERR("CodecRegDefaultInit failed."); + return HDF_FAILURE; + } +... + return HDF_SUCCESS; +} +``` + + + +## Accessory Driver Development Example +Code path: **drivers/peripheral/audio/chipsets/tfa9879/accessory** + +SmartPA is a type of accessory driver. The SmartPA development procedure is similar to the codec development procedure. +1. Define and fill in an accessory instance. +2. Implement callbacks for the accessory instance. +3. Register and bind the accessory instance to the HDF. +4. Configure the HCS and makefile. + +### Filling in Accessory Data Structures + +Fill in the following data structures for the accessory module: + +- **g_tfa9879Data**: operation function set of the accessory device. It contains the configuration in the .hcs file, and defines and maps the functions for initializing the accessory device and reading and writing registers. + +- **g_tfa9879DaiDeviceOps**: data set of the accessory device DAI. It defines and maps the operation set of the accessory device DAI. + +- **g_tfa9879DaiData**: data set of the DAI of the accessory device. It defines and maps the driver name, initialization, and operation set of the data access interface of the accessory device. + +```c +struct AccessoryData g_tfa9879Data = { + .Init = Tfa9879DeviceInit, + .Read = AccessoryDeviceRegRead, + .Write = AccessoryDeviceRegWrite, +}; + +struct AudioDaiOps g_tfa9879DaiDeviceOps = { + .Startup = Tfa9879DaiStartup, + .HwParams = Tfa9879DaiHwParams, +}; + +struct DaiData g_tfa9879DaiData = { + .drvDaiName = "accessory_dai", + .DaiInit = Tfa9879DaiDeviceInit, + .ops = &g_tfa9879DaiDeviceOps, +}; +``` + +### Initializing the Accessory Device and Accessory DAI Device + +As the entry function for device initialization, **Tfa9879DeviceInit** sets the address of the SmartPA I2C device, obtains configuration data, initializes (including resets) the device registers, and adds the control functionality to the controller linked list. The current demo also includes the initialization of the registers related to the Hi3516D V300 device, such as initialization of GPIO pins. + +```c +int32_t Tfa9879DeviceInit(struct AudioCard *audioCard, const struct AccessoryDevice *device) +{ + int32_t ret; + ... + g_accessoryTransferData.i2cDevAddr = TFA9879_I2C_DEV_ADDR; // 0x6D + // Obtain configuration data. + ret = AccessoryDeviceCfgGet(device->devData, &g_accessoryTransferData); + ... + // Initialize GPIO pins. + ret = Hi35xxGpioPinInit(); + ... + // Initialize device registers. + ret = AccessoryDeviceCtrlRegInit(); + ... + // Bind the control functionality configuration. + ret = AudioAddControls(audioCard, g_accessoryTransferData.accessoryControls, + g_accessoryTransferData.accessoryCfgCtrlCount); + ... +} +``` + +**AccessoryI2cReadWrite** reads and writes I2C registers. + +```c +int32_t AccessoryI2cReadWrite(struct AudioAddrConfig *regAttr, uint16_t rwFlag) +{ + int32_t ret; + DevHandle i2cHandle; + int16_t transferMsgCount = 1; + uint8_t regs[I2C_REG_LEN]; + struct I2cMsg msgs[I2C_MSG_NUM]; + ... + i2cHandle = I2cOpen(I2C_BUS_NUM); + ... + if (rwFlag == I2C_FLAG_READ) { + transferMsgCount = I2C_MSG_NUM; + } + ret = AccessoryI2cMsgFill(regAttr, rwFlag, regs, msgs); + ... + ret = I2cTransfer(i2cHandle, msgs, transferMsgCount); + ... + AccessoryI2cRelease(msgs, transferMsgCount, i2cHandle); + return HDF_SUCCESS; +} +``` + +### Implementing the Accessory Operation Function Set + +The callbacks **AccessoryDeviceRegRead** and **AccessoryDeviceRegWrite** invoke **AccessoryI2cReadWrite** to read and write the control register values. + +```c +int32_t AccessoryDeviceRegRead(const struct AccessoryDevice *codec, uint32_t reg, uint32_t *val) +{ + int32_t ret; + struct AudioAddrConfig regAttr; + ... + (void)codec; + regAttr.addr = (uint8_t)reg; + regAttr.value = 0; + ret = AccessoryI2cReadWrite(®Attr, I2C_FLAG_READ); + if (ret != HDF_SUCCESS) { + AUDIO_DRIVER_LOG_ERR("failed."); + return HDF_FAILURE; + } + *val = regAttr.value; + ... + return HDF_SUCCESS; +} + +int32_t AccessoryDeviceRegWrite(const struct AccessoryDevice *codec, uint32_t reg, uint32_t value) +{ + int32_t ret; + struct AudioAddrConfig regAttr; + (void)codec; + regAttr.addr = (uint8_t)reg; + regAttr.value = (uint16_t)value; + ret = AccessoryI2cReadWrite(®Attr, 0); + ... + return HDF_SUCCESS; +} +``` + +**Tfa9879DaiStartup** performs startup settings. The code snippet is as follows: + +```c +int32_t Tfa9879DaiStartup(const struct AudioCard *card, const struct DaiDevice *device) +{ + int ret; + (void)card; + (void)device; + // Set the working status of SmartPA. + ret = Tfa9879WorkStatusEnable(); + ... + return HDF_SUCCESS; +} + +``` + +**Tfa9879DaiHwParams** delivers playback parameters. The code snippet is as follows: + +```c +int32_t Tfa9879DaiHwParams(const struct AudioCard *card, const struct AudioPcmHwParams *param) +{ + int32_t ret; + uint16_t frequency, bitWidth; + struct DaiParamsVal daiParamsVal; + (void)card; + ... + // Set the sampling rate. + ret = AcessoryDeviceFrequencyParse(param->rate, &frequency); + ... + // Set the bit width. + ret = Tfa9879FormatParse(param->format, &bitWidth); + ... + daiParamsVal.frequencyVal = frequency; + daiParamsVal.formatVal = bitWidth; + daiParamsVal.channelVal = param->channels; // Set the audio channel. + ret = AccessoryDaiParamsUpdate(daiParamsVal); + ... + return HDF_SUCCESS; +} +``` + +### Registering and Binding Accessory to HDF + +This process depends on the driver implementation mode of the HDF. For details, see [HDF](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf.md). + +Fill in the **g_tfa9879DriverEntry** structure. Ensure that the value of **moduleName** is the same as that in **device_info.hcs**. Implement the pointers to the **Bind**, **Init**, and **Release** functions. + +drivers/peripheral/audio/chipsets/tfa9879/accessory/src/tfa9879_accessory_adapter.c + +```c +static int32_t Tfa9879DriverBind(struct HdfDeviceObject *device) +{ + (void)device; + AUDIO_DRIVER_LOG_INFO("success!"); + return HDF_SUCCESS; +} + +static int32_t Tfa9879DriverInit(struct HdfDeviceObject *device) +{ + int32_t ret; + ... + // Obtain configuration data from .hcs files. + ret = AccessoryGetConfigInfo(device, &g_tfa9879Data); + ... + ret = ret = GetServiceName(device); + ... + ret = AudioRegisterAccessory(device, &g_tfa9879Data, &g_tfa9879DaiData); + .... + return HDF_SUCCESS; +} + +/* HdfDriverEntry definitions */ +struct HdfDriverEntry g_tfa9879DriverEntry = { + .moduleVersion = 1, + .moduleName = "CODEC_TFA9879", + .Bind = Tfa9879DriverBind, + .Init = Tfa9879DriverInit, + .Release = NULL, +}; +HDF_INIT(g_tfa9879DriverEntry); +``` + +### Configuring HCS + +For details about the configuration process, see [Configuring HCS](#section4115) in **Codec Driver Development Example**. + + + +## Platform Driver Development Example +Code path: **drivers/peripheral/audio/chipsets/hi3516dv300/soc** + +In audio driver development, the Platform module is configured to adapt to the DMA driver. The major steps for developing the platform driver are as follows: +1. Define and fill in a platform instance. +2. Implement callbacks for the platform instance. +3. Register and bind the platform instance to the HDF. +4. Configure the HCS and makefile. + +### Filling in Platform Data Structures + +Fill in the following structures for the platform module: + +- **g_platformData**: private configuration of the platform device, including the initialization and operation functions of the platform device. + +- **g_dmaDeviceOps**: DMA device operation function set, including the encapsulation of some common DMA APIs. + +```c +struct AudioDmaOps g_dmaDeviceOps = { + .DmaBufAlloc = Hi3516DmaBufAlloc, // Apply for memory for the DMA device. + .DmaBufFree = Hi3516DmaBufFree, // Release the memory of the DMA device. + .DmaRequestChannel = Hi3516DmaRequestChannel, // Request a DMA channel. + .DmaConfigChannel = Hi3516DmaConfigChannel, // Configure the DMA channel. + .DmaPrep = Hi3516DmaPrep, // Prepare for DMA. + .DmaSubmit = Hi3516DmaSubmit, // Submit a DMA request. + .DmaPending = Hi3516DmaPending, // Pend DMA. + .DmaPause = Hi3516DmaPause, // Pause or stop DMA. + .DmaResume = Hi3516DmaResume, // Resume DMA. + .DmaPointer = Hi3516DmaPointer, // Obtain the current playing or recording position. +}; + +struct PlatformData g_platformData = { + .PlatformInit = AudioDmaDeviceInit, // Initialize the DMA device. + .ops = &g_dmaDeviceOps, +}; +``` + +### Initializing the DMA Device + +**AudioDmaDeviceInit** initializes the DMA device, including setting the Hi3516 AIAO module. + +```c +int32_t AudioDmaDeviceInit(const struct AudioCard *card, const struct PlatformDevice *platformDevice) +{ +... + AiaoHalSysInit(); + /* PIN MUX */ + AiaoSysPinMux(); + /* CLK reset */ + AiaoClockReset(); + /* AIAO initialization */ + AiaoDeviceInit(chnId); +... + return HDF_SUCCESS; +} +``` + +### Implementing the DMA Operation Function Set + +The DMA device operation function set includes the encapsulation of DMA common APIs. If the common APIs cannot meet development requirements, you can implement new DMA callbacks. + +```c +int32_t Hi3516DmaBufAlloc(struct PlatformData *data, const enum AudioStreamType streamType); +int32_t Hi3516DmaBufFree(struct PlatformData *data, const enum AudioStreamType streamType); +int32_t Hi3516DmaRequestChannel(const struct PlatformData *data); +int32_t Hi3516DmaConfigChannel(const struct PlatformData *data); +int32_t Hi3516DmaPrep(const struct PlatformData *data); +int32_t Hi3516DmaSubmit(const struct PlatformData *data); +int32_t Hi3516DmaPending(struct PlatformData *data); +int32_t Hi3516DmaPause(struct PlatformData *data); +int32_t Hi3516DmaResume(const struct PlatformData *data); +int32_t Hi3516DmaPointer(struct PlatformData *data, uint32_t *pointer); +``` + +### Registering and Binding Platform to HDF + +This process depends on the driver implementation mode of the HDF. For details, see [HDF](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf.md). + +- Fill in the **g_platformDriverEntry** structure. +- Ensure that the value of **moduleName** is the same as that in **device_info.hcs**. +- Implement the pointers to the **Bind**, **Init**, and **Release** functions. + +drivers/peripheral/audio/chipsets/hi3516dv300/soc/src/hi3516_dma_adapter.c + +```c +static int32_t Hi3516DmaDriverInit(struct HdfDeviceObject *device) +{ +... + OsalMutexInit(&g_platformData.renderBufInfo.buffMutex); + OsalMutexInit(&g_platformData.captureBufInfo.buffMutex); + g_platformData.platformInitFlag = false; + ret = AudioSocRegisterPlatform(device, &g_platformData); +... + return HDF_SUCCESS; +} + +static void Hi3516DmaDriverRelease(struct HdfDeviceObject *device) +{ + struct PlatformHost *platformHost = NULL; +... + platformHost = (struct PlatformHost *)device->service; +... + OsalMutexDestroy(&g_platformData.renderBufInfo.buffMutex); + OsalMutexDestroy(&g_platformData.captureBufInfo.buffMutex); + OsalMemFree(platformHost); +} + +/* HdfDriverEntry definitions */ +struct HdfDriverEntry g_platformDriverEntry = { + .moduleVersion = 1, + .moduleName = "DMA_HI3516", + .Bind = Hi3516DmaDriverBind, + .Init = Hi3516DmaDriverInit, + .Release = Hi3516DmaDriverRelease, +}; +HDF_INIT(g_platformDriverEntry); +``` + +### Configuring HCS + +For details about the configuration process, see [Configuring HCS](#section4115) in **Codec Driver Development Example**. + + + +## DAI Driver Development Example +Code path: **drivers/peripheral/audio/chipsets/hi3516dv300/soc** + +The major steps for developing the DAI driver are as follows: +1. Define and fill in a DAI instance. +2. Implement callbacks for the DAI instance. +3. Register and bind the DAI instance to the HDF. +4. Configure the HCS and makefile. + +### Filling in DAI Data Structures + +Fill in the following structures for the DAI module: + +- **g_daiData**: private configuration of the DAI device, including the initialization of the DAI device, read/write of registers, and operation functions. + +- **g_daiDeviceOps**: DAI device operation function set, including setting DAI parameters and triggering and starting the DAI device. + +```c +struct AudioDaiOps g_daiDeviceOps = { + .HwParams = DaiHwParams, + .Trigger = DaiTrigger, + .Startup = DaiStartup, +}; + +struct DaiData g_daiData = { + .DaiInit = DaiDeviceInit, + .Read = AudioDeviceReadReg, + .Write = AudioDeviceWriteReg, + .ops = &g_daiDeviceOps, +}; +``` + +### Initializing the DAI Device + +**DaiDeviceInit** initializes DAI configuration and adds the information to the controller linked list. + +```c +int32_t DaiDeviceInit(struct AudioCard *audioCard, const struct DaiDevice *dai) +{ +... + struct DaiData *data = dai->devData; + struct AudioRegCfgData *regConfig = dai->devData->regConfig; +... + g_regCodecBase = OsalIoRemap(CODEC_REG_BASE, CODEC_MAX_REG_SIZE); +... + data->regVirtualAddr = (uintptr_t)g_regCodecBase; + DaiSetConfigInfo(data); + AudioAddControls(audioCard, data->controls, data->numControls); + I2c6PinInit(); +... + data->daiInitFlag = true; + return HDF_SUCCESS; +} +``` + +### Implementing the DAI Operation Function Set + +**AudioDeviceReadReg** and **AudioDeviceWriteReg** are not used on the Hi3516 and are reserved. + +**DaiHwParams** sets PCM stream information. + +```c +int32_t DaiHwParams(const struct AudioCard *card, const struct AudioPcmHwParams *param) +{ + uint32_t bitWidth; + struct DaiDevice *device = card->rtd->cpuDai; +... + DaiCheckSampleRate(param->rate); + struct DaiData *data = DaiDataFromCard(card); + data->pcmInfo.channels = param->channels; +... + AudioFramatToBitWidth(param->format, &bitWidth); +... + data->pcmInfo.bitWidth = bitWidth; + data->pcmInfo.rate = param->rate; + data->pcmInfo.streamType = param->streamType; + data->regVirtualAddr = (uintptr_t)g_regDaiBase; +... + DaiParamsUpdate(device); + data->regVirtualAddr = (uintptr_t)g_regCodecBase; + return HDF_SUCCESS; +} +``` + +**DaiTrigger** is not used on the Hi3516 and is reserved. + +**DaiStartup** updates the register configuration and configures the I2S. + +```c +int32_t DaiStartup(const struct AudioCard *card, const struct DaiDevice *device) +{ + struct AudioMixerControl *regCfgItem = NULL; +... + regCfgItem = device->devData->regConfig->audioRegParams[AUDIO_DAI_STARTUP_PATAM_GROUP]->regCfgItem; + itemNum = device->devData->regConfig->audioRegParams[AUDIO_DAI_STARTUP_PATAM_GROUP]->itemNum; + + device->devData->regVirtualAddr = (uintptr_t)g_regDaiBase; + for (int i = 0; i < itemNum; i++) { + int ret = AudioUpdateDaiRegBits(device, ®CfgItem[i], regCfgItem[i].value); + if (ret != HDF_SUCCESS) { + AUDIO_DRIVER_LOG_ERR("set frequency fail."); + return HDF_FAILURE; + } + } + device->devData->regVirtualAddr = (uintptr_t)g_regCodecBase; + + if (I2sPinInit() != HDF_SUCCESS) { + AUDIO_DRIVER_LOG_ERR("I2sPinInit fail."); + } + + return HDF_SUCCESS; +} +``` + +### Registering and Binding DAI to HDF + +This process depends on the driver implementation mode of the HDF. For details, see [HDF](https://gitee.com/openharmony/docs/blob/master/en/device-dev/driver/driver-hdf.md). + +- Fill in the **g_daiDriverEntry** structure. +- Ensure that the value of **moduleName** is the same as that in **device_info.hcs**. +- Implement the pointers to the **Bind**, **Init**, and **Release** functions. + +drivers/peripheral/audio/chipsets/hi3516dv300/soc/src/hi3516_dai_adapter.c + +```c +static int32_t DaiDriverBind(struct HdfDeviceObject *device) +{ +... + struct DaiHost *daiHost = (struct DaiHost *)OsalMemCalloc(sizeof(*daiHost)); +... + daiHost->device = device; + device->service = &daiHost->service; + g_daiData.daiInitFlag = false; +... + return HDF_SUCCESS; +} + +static int32_t DaiDriverInit(struct HdfDeviceObject *device) +{ +... + DaiGetConfigInfo(device, &g_daiData); + DaiGetServiceName(device); +... + OsalMutexInit(&g_daiData.mutex); + AudioSocRegisterDai(device, &g_daiData); +... + return HDF_SUCCESS; +} + +static void DaiDriverRelease(struct HdfDeviceObject *device) +{ +... + OsalMutexDestroy(&g_daiData.mutex); +... + struct DaiHost *daiHost = (struct DaiHost *)device->service; +... + OsalMemFree(daiHost); +} + +/* HdfDriverEntry definitions */ +struct HdfDriverEntry g_daiDriverEntry = { + .moduleVersion = 1, + .moduleName = "DAI_HI3516", + .Bind = DaiDriverBind, + .Init = DaiDriverInit, + .Release = DaiDriverRelease, +}; +HDF_INIT(g_daiDriverEntry); +``` + +### Configuring HCS + +For details about the configuration process, see [Configuring HCS](#section4115) in **Codec Driver Development Example**. + + + +## Adding Compilation Configuration to Makefile + +Add the newly added files to the **Makefile** file to link them to the kernel image. + +Standard system (Linux): **drivers/adapter/khdf/linux/model/audio/Makefile** + +```makefile +obj-$(CONFIG_DRIVERS_HDF_AUDIO_CODEC) += \ +$(KHDF_AUDIO_HI3516DV300_DIR)/../tfa9879/accessory/src/tfa9879_accessory_adapter.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/../tfa9879/accessory/src/tfa9879_accessory_impl.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_adapter.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_impl.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_ops.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/dsp/src/dsp_adapter.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dai_adapter.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dai_ops.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_aiao_impl.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dma_ops.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dma_adapter.o \ +$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_adapter.o +``` + +Small system (LiteOS): **drivers/adapter/khdf/liteos/model/audio/Makefile** + +```makefile +LOCAL_SRCS += \ +$(KHDF_AUDIO_HI3516DV300_DIR)/../tfa9879/accessory/src/tfa9879_accessory_adapter.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/../tfa9879/accessory/src/tfa9879_accessory_impl.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_adapter.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_impl.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/codec/src/hi3516_codec_ops.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/dsp/src/dsp_adapter.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dai_adapter.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dai_ops.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_aiao_impl.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dma_ops.c \ +$(KHDF_AUDIO_HI3516DV300_DIR)/soc/src/hi3516_dma_adapter.c +``` + + + +## Source Code Structure and Directory + +The development example implements the functions in the header file of the driver interface. The following uses Hi3516 as an example to describe the directory structure. + +Path of the driver implementation sample code: **drivers/peripheral/audio/chipsets** + +``` +├── hi3516dv300 +│   ├── codec +│   │   ├── include +│   │   │   ├── hi3516_codec_impl.h +│   │   │   └── hi3516_codec_ops.h +│   │   ├── src +│ │ │ ├── hi3516_codec_adapter.c // Codec driver entry +│ │ │ ├── hi3516_codec_impl.c // Implement codec hardware operations. +│ │ │ └── hi3516_codec_ops.c // Implement codec driver APIs. +│   │   └── test +│   │   └── unittest +│   ├── dsp +│   │   └── include +│   │   └── dsp_ops.h +│   │   └── src +│ │ └── dsp_adapter.c // DSP driver entry +│   │   └── dsp_ops.c +│   └── soc +│   ├── include +│   │   ├── hi3516_aiao_impl.h +│   │   ├── hi3516_dai_ops.h +│   │   └── hi3516_dma_ops.h +│   ├── src +│   │   ├── hi3516_aiao_impl.c +│ │ ├── hi3516_dai_adapter.c // DAI driver entry +│   │   ├── hi3516_dai_ops.c +│ │ ├── hi3516_dma_adapter.c // DMA driver entry +│   │   └── hi3516_dma_ops.c +│   └── test +│   └── unittest +└── tfa9879 +    └── accessory +    ├── include +    │   └── tfa9879_accessory_impl.h +    └── src + ├── tfa9879_accessory_adapter.c // Accessory driver entry +    └── tfa9879_accessory_impl.c +``` + +HCS Files and Directory + +``` +Standard system: +vendor/hisilicon/Hi3516DV300/ +└── hdf_config + └── khdf + ├── audio + │   ├── audio_config.hcs + │   ├── codec_config.hcs + │   ├── dai_config.hcs + │   ├── dma_config.hcs + │   └── dsp_config.hcs + ├── device_info + │   └── device_info.hcs + └── hdf.hcs + +Small system: +vendor/hisilicon/hispark_taurus/ +├── config.json +└── hdf_config + ├── audio + │   ├── audio_config.hcs + │   ├── codec_config.hcs + │   ├── dai_config.hcs + │   ├── dma_config.hcs + │   └── dsp_config.hcs + ├── device_info + │   └── device_info.hcs + └── hdf.hcs +``` + + + +# HAL-based Development Procedure and Example +Code path: **drivers/peripheral/audio/hal** + +## Development Procedure + +![](figures/HAL_flowchart.png) + +1. Call **GetAudioManagerFuncs()** to obtain functions. + +2. Call **GetAllAdapters()** to obtain information about the supported audio adapters and call **LoadAdapter()** to load the corresponding audio adapter. + +3. Create an audio player class by calling **CreateRender()** or create a recorder class and deliver audio attributes. + +4. Call the methods mounted to the created audio player class to call **render->control.Start()** and **render->RenderFrame()** to dispatch the start instruction and deliver audio data cyclically. + +5. During the playback, call **render->control.Pause()**, **render->control.Resume()**, or **render->volume.SetVolume()** to control the audio player service, for example, pausing the playback, resuming the playback, and adjusting the volume. + +6. After the audio player service is complete, stop the playback, destroy the audio player class, and unload the audio adapter. + + 1. render->control.Stop(); + + 2. adapter->DestroyRender(); + + 3. manager->UnloadAdapter(); + +## Development Example + +```c +#include +#include +#include "audio_types.h" +#include +#include "audio_manager.h" + + /* Open the dynamic link to the so library. */ +char *soPathHdi = "/system/lib/libhdi_audio.z.so"; +void *g_handle = dlopen(soPathHdi , 1); + +int32_t FrameStart(void *param) +{ +... + /* Send audio data cyclically. */ + do { + readSize = (remainingDataSize > bufferSize) ? bufferSize : remainingDataSize; + numRead = fread(frame, 1, readSize, g_file); + if (numRead > 0) { + ret = render->RenderFrame(render, frame, numRead, &replyBytes); + if (ret == HDF_ERR_INVALID_OBJECT) { + LOG_FUN_ERR("Render already stop!"); + break; + } + remainingDataSize -= numRead; + } + /* Pause the playback and wait. */ + while (g_waitSleep) { + printf("music pause now.\n"); + pthread_cond_wait(&g_functionCond, &g_mutex); + printf("music resume now.\n"); + } + } while (!g_closeEnd && numRead > 0 && remainingDataSize > 0); +... +} + +static void *hal_main() +{ + /* Map and call the entry function. */ + struct AudioManager *(*getAudioManager)() = + (struct AudioManager *(*)())(dlsym(g_handle, "GetAudioManagerFuncs")); + struct AudioManager *manager = getAudioManager(); + + /* Obtain the audio adapter list. */ + struct AudioAdapterDescriptor *descs = NULL; + int32_t size = 0; + int32_t ret = manager->GetAllAdapters(manager, &descs, &size); + + /* Locate the audio adapter and port based on the specified audio adapter name and port description. */ + enum AudioPortDirection port = PORT_OUT; // The port type OUT means to play the audio. + struct AudioPort renderPort; + char * adapterNameCase = "usb"; + int32_t index = SwitchAdapter(descs, adapterNameCase, port, &renderPort, size); + + /* Load the audio adapter based on the matched audio adapter information. */ + struct AudioAdapter *adapter = NULL; + struct AudioAdapterDescriptor *desc = &descs[index]; // Obtain the device based on the matched audio adapter information. + manager->LoadAdapter(manager, desc, &adapter); // Load the audio adapter and obtain the audio adapter instance. + + /* Create an audio player class. */ + struct AudioRender *render; + struct AudioDeviceDescriptor devDesc; + struct AudioSampleAttributes attrs; + InitDevDesc(&devDesc, renderPort.portId); // Initialize device parameters. + WavHeadAnalysis(g_file, &attrs); // Parse the audio file to set attributes. + adapter->CreateRender(adapter, &devDesc, &attrs, &render); + + /* Deliver the audio data to play. */ + render->control.Start((AudioHandle)render); // Dispatch the start instruction and prepare for the action. + pthread_create(&g_tids, NULL, (void *)(&FrameStart), &g_str); // Start the thread to play the audio clip. + + /* Control instructions */ + render->control.Pause((AudioHandle)render); // Pause the playback. + render->control.Resume((AudioHandle)render); // Resume the playback. + render->volume.SetVolume((AudioHandle)render, 0.5); // Set the volume. + + /* Stop playback and destroy the audio player class. */ + render->control.Stop((AudioHandle)render); + adapter->DestroyRender(adapter, render); + /* Unload the audio adapter. */ + manager->UnloadAdapter(manager, adapter); +} +``` + + + +# Summary + +This document provides all the key adaptations involved in the driver development based on the audio driver architecture. It elaborates how to adapt the audio driver and use HDI APIs. You can easily develop your audio drivers based on the chip you use by referring to this document. diff --git a/en/device-dev/driver/driver-peripherals-lcd-des.md b/en/device-dev/driver/driver-peripherals-lcd-des.md index e0c84c253904be7be5730355269de34eafb93ea0..5d647c1ef836e539597a9c8203020f7c03634b66 100644 --- a/en/device-dev/driver/driver-peripherals-lcd-des.md +++ b/en/device-dev/driver/driver-peripherals-lcd-des.md @@ -12,7 +12,7 @@ The Liquid Crystal Display \(LCD\) driver powers on the LCD and initializes inte **Figure 1** Architecture of the display driver model ![](figures/architecture-of-the-display-driver-model.png "architecture-of-the-display-driver-model") -**Display driver model** +**Display Driver Model** The display driver model consists of the display common driver layer, SoC adapter layer, and third-party chip driver layer. The display driver model is developed based on the HDF and hides the differences between kernel forms through platform and OSAL APIs so the LCD driver can be migrated between different OSs and chip platforms. The display driver connects to the display common HAL, supports the implementation of Hardware Driver Interfaces \(HDIs\), and provides various driver interfaces for the graphics service through the display HDI. @@ -105,7 +105,7 @@ display :: host { } ``` -The following example shows how to adapt to the MIPI device to the Hi35xx series chips at the SoC adapter layer: +The following example shows how to adapt the MIPI device to the Hi35xx series chips at the SoC adapter layer: ``` static int32_t MipiDsiInit(struct PanelInfo *info) diff --git a/en/device-dev/driver/driver-peripherals-touch-des.md b/en/device-dev/driver/driver-peripherals-touch-des.md index 55d22178fe22d5472685898095ed86df4701bbf5..efe110318e3066c708d341a7f6ef32f7f3703a4b 100644 --- a/en/device-dev/driver/driver-peripherals-touch-des.md +++ b/en/device-dev/driver/driver-peripherals-touch-des.md @@ -1,11 +1,11 @@ -# TOUCHSCREEN +# Touchscreen - [Overview](#section175431838101617) - [Available APIs](#section105459441659) - [How to Develop](#section65745222184) - [Development Example](#section263714411191) - - [Add the touchscreen driver-related descriptions.](#section18249155619195) - - [Board-level Hardware Configuration and Private Data Configuration](#section3571192072014) + - [Adding the Touchscreen Driver-related Description](#section18249155619195) + - [Adding Board Configuration and Touchscreen Private Configuration](#section3571192072014) - [Adding the Touchscreen Driver](#section6356758162015) @@ -13,7 +13,7 @@ - **Functions of the Touchscreen driver** - The Touchscreen driver is used to power on its integrated circuit \(IC\), configure and initialize hardware pins, register interrupts, configure Inter-Integrated Circuit \(I2C\) or SPI APIs, set input-related configurations, and download and update firmware. + The touchscreen driver is used to power on its integrated circuit \(IC\), configure and initialize hardware pins, register interrupts, configure Inter-Integrated Circuit \(I2C\) or SPI APIs, set input-related configurations, and download and update firmware. - **Layers of the Touchscreen driver** @@ -80,17 +80,18 @@ Regardless of the OS and system on a chip \(SoC\), the input driver is developed The following uses the touchscreen driver as an example to describe the loading process of the input driver model: -\(1\) Complete the device description configuration, such as the loading priority, board-level hardware information, and private data, by referring to the existing template. +1. Complete the device description configuration, such as the loading priority, board-level hardware information, and private data, by referring to the existing template. -\(2\) Load the input device management driver. The input management driver is loaded automatically by the HDF to create and initialize the device manager. +2. Load the input device management driver. The input management driver is loaded automatically by the HDF to create and initialize the device manager. -\(3\) Load the platform driver. The platform driver is loaded automatically by the HDF to parse the board-level configuration, initialize the hardware, and provide the API for registering the touchscreen. +3. Load the platform driver. The platform driver is loaded automatically by the HDF to parse the board-level configuration, initialize the hardware, and provide the API for registering the touchscreen. -\(4\) Load the touchscreen driver. The touchscreen driver is loaded automatically by the HDF to instantiate the touchscreen device, parse the private data, and implement differentiated APIs provided by the platform. +4. Load the touchscreen driver. The touchscreen driver is loaded automatically by the HDF to instantiate the touchscreen device, parse the private data, and implement differentiated APIs provided by the platform. -\(5\) Register the instantiated touchscreen device with the platform driver. Then bind this device to the platform driver, and complete touchscreen initialization such as interrupt registration and power-on and power-off. +5. Register the instantiated touchscreen device with the platform driver. Then bind this device to the platform driver, and complete touchscreen initialization such as interrupt registration and power-on and power-off. + +6. Instantiate the input device and register it with the input manager after the touchscreen is initialized. -\(6\) Instantiate the input device and register it with the input manager after the touchscreen is initialized. Perform the following steps: @@ -111,7 +112,7 @@ Perform the following steps: This example describes how to develop the touchscreen driver. -### Add the touchscreen driver-related descriptions. +### Adding the Touchscreen Driver-related Description The information about modules of the input driver model is shown as follows and enables the HDF to load the modules in sequence. For details, see [Driver Development](driver-hdf-development.md). @@ -156,7 +157,7 @@ input :: host { } ``` -### Board-level Hardware Configuration and Private Data Configuration +### Adding Board Configuration and Touchscreen Private Configuration The following describes the configuration of the board-level hardware and private data of the touchscreen. You can modify the configuration based on service requirements. diff --git a/en/device-dev/driver/driver-peripherals-usb-des.md b/en/device-dev/driver/driver-peripherals-usb-des.md index 0dd421ec369c8ff8d4deaee0560608a2090d6fef..0658b9dec90c975afe71f7f0e9d3edb6d1d215a6 100644 --- a/en/device-dev/driver/driver-peripherals-usb-des.md +++ b/en/device-dev/driver/driver-peripherals-usb-des.md @@ -1,20 +1,20 @@ -# USB +# USB -- [Overview](#section175431838101617) - - [Available APIs](#section17667171301711) +- [Overview](#section127mcpsimp) + - [Available APIs](#section141mcpsimp) -- [Development Guidelines](#section65745222184) - - [Developing Driver Using Host DDK APIs](#section865734181916) - - [Developing Driver Using Host Raw APIs](#section865734181916) - - [Developing Driver Using Device DDK APIs](#section865734181916) +- [Development Guidelines](#section581mcpsimp) + - [Developing Driver Using Host DDK APIs](#section584mcpsimp) + - [Developing Driver Using Host Raw APIs](#section594mcpsimp) + - [Developing Driver Using Device DDK APIs](#section600mcpsimp) -- [Development Examples](#section263714411191) - - [Developing Driver Using Host DDK APIs](#section18249155619195) - - [Developing Driver Using Host Raw APIs](#section3571192072014) - - [Developing Driver Using Device DDK APIs](#section6356758162015) +- [Development Examples](#section607mcpsimp) + - [Developing Driver Using Host DDK APIs](#section609mcpsimp) + - [Developing Driver Using Host Raw APIs](#section612mcpsimp) + - [Developing Driver Using Device DDK APIs](#section615mcpsimp) -## Overview +## Overview USB host development aims to provide host-related functions, including protocol encapsulation, device management, and driver installation and uninstall. @@ -22,379 +22,358 @@ USB device development aims to provide device-related functions, including devic The following figures show the UBS host and device driver models. -**Figure 1** USB host driver model +**Figure 1** USB host driver model ![](figures/USB_host_driver_model.png "USB host driver model") -**Figure 2** USB device driver model +**Figure 2** USB device driver model ![](figures/USB_device_driver_model.png "USB device driver model") The USB driver model offers the following APIs: -- The USB host Driver Development Kit (DDK) provides driver capability APIs that can be directly called in user mode. The APIs can be classified into the DDK initialization class, interface operation class, and request operation class by function. These APIs can be used to perform DDK initialization, bind/release and open/close an interface, allocate/release a request, and implement isochronous or non-isochronous transfer. -- The USB device DDK provides device management, I/O management, and configuration management APIs, which can be used to create and delete a device, obtain/open an interface, and perform isochronous or non-isochronous transfer. +- The USB host Driver Development Kit (DDK) provides driver capability APIs that can be directly called in user mode. The APIs can be classified into the DDK initialization class, interface operation class, and request operation class by function. These APIs can be used to perform DDK initialization, bind/release and open/close an interface, allocate/release a request, and implement synchronous or asynchronous transfer. +- The USB device DDK provides device management, I/O management, and configuration management APIs, which can be used to create and delete a device, obtain/open an interface, and perform synchronous or asynchronous transfer. -### Available APIs +### Available APIs() -Table 1 describes the APIs provided by the USB host driver model. +[Figure 1](#fig1649563542917) describes the APIs provided by the USB host driver model. **Table 1** APIs provided by the USB host driver model - - - @@ -81,7 +81,7 @@ struct MipiDsiCntlrMethod {// Member functions of the core layer structure - - @@ -104,7 +104,7 @@ struct MipiDsiCntlrMethod {// Member functions of the core layer structure - @@ -115,7 +115,7 @@ struct MipiDsiCntlrMethod {// Member functions of the core layer structure - @@ -133,7 +133,7 @@ The following uses **mipi\_tx\_hi35xx.c** as an example to present the content 1. Generally, you need to configure the device attributes in **xx\_config.hcs** and add the **deviceNode** information to the **device\_info.hcs** file. The device attribute values are closely related to the default values or value range of the **MipiDsiCntlr** members at the core layer. The **deviceNode** information is related to the driver entry registration. - In this example, no additional attribute needs to be configured for the MIPI-DSI controller. If required, you need to add the **deviceMatchAttr** information to **deviceNode** in the **device\_info** file and add the **mipidsi\_config** file. + In this example, no additional attribute needs to be configured for the MIPI DSI controller. If required, you need to add the **deviceMatchAttr** information to **deviceNode** in the **device\_info** file and add the **mipidsi\_config** file. - **device\_info.hcs** configuration reference @@ -162,7 +162,7 @@ The following uses **mipi\_tx\_hi35xx.c** as an example to present the content Generally, HDF calls the **Bind** function and then the **Init** function to load a driver. If **Init** fails to be called, HDF calls **Release** to release driver resources and exits. - - MIPI-DSI driver entry reference + - MIPI DSI driver entry reference ``` struct HdfDriverEntry g_mipiTxDriverEntry = { @@ -177,7 +177,7 @@ The following uses **mipi\_tx\_hi35xx.c** as an example to present the content 3. Initialize the **MipiDsiCntlr** object at the core layer, including initializing the vendor custom structure \(transferring parameters and data\), instantiating **MipiDsiCntlrMethod** \(used to call underlying functions of the driver\) in **MipiDsiCntlr**, and implementing the **HdfDriverEntry** member functions \(**Bind**, **Init**, and **Release**\). - Custom structure reference - To the driver, the custom structure carries parameters and data. The values in the **config** file are used to initialize the structure members. In this example, the MIPI-DSI has no device attribute file. Therefore, the basic member structure is similar to that of **MipiDsiCntlr**. + To the driver, the custom structure carries parameters and data. The values in the **config** file are used to initialize the structure members. In this example, the MIPI DSI has no device attribute file. Therefore, the basic member structure is similar to that of **MipiDsiCntlr**. ``` typedef struct { diff --git a/en/device-dev/driver/driver-platform-pwm-des.md b/en/device-dev/driver/driver-platform-pwm-des.md index 01e83c4c2ca5adf68aa0c719ba5bde666df88048..6c1e273c10eed66c2eedff8800dc89722e28b641 100644 --- a/en/device-dev/driver/driver-platform-pwm-des.md +++ b/en/device-dev/driver/driver-platform-pwm-des.md @@ -1,579 +1,476 @@ -# PWM - -- [Overview](#section1043395117296) -- [Available APIs](#section3939192652418) -- [Usage Guidelines](#section435718267334) - - [How to Use](#section113655616347) - - [Obtaining a PWM Device Handle](#section17816586359) - - [Setting the PWM Period](#section920214812397) - - [Setting the PWM Duty Cycle](#section519712820405) - - [Setting the PWM Polarity](#section12383334115) - - [Enabling the PWM Device](#section382684811414) - - [Disabling the PWM Device](#section16545114404218) - - [Obtaining PWM Device Configuration Parameters](#section117101243144311) - - [Setting PWM Device Configuration Parameters](#section13834163604414) - - [Releasing the PWM Device Handle](#section12987111511450) - -- [Usage Example](#section138636719469) - -## Overview - -- Pulse width modulation \(PWM\) is a method used to digitally encode analog signal levels and convert them into pulses. It can be used for motor control and backlight brightness adjustment. - -- The PWM APIs define a set of common functions for operating a PWM device, including those for: - - Obtaining and releasing a PWM device handle - - Setting the PWM period, duty cycle, and polarity - - Enabling and disabling a PWM device - - Obtaining and setting configuration parameters - - -## Available APIs - -**Table 1** APIs available for the PWM driver - - -

Header File

+ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Header File

API

+

API

Description

+

Description

usb_ddk_interface.h

-

-

+

usb_ddk_interface.h

int32_t UsbInitHostSdk(struct UsbSession **session);

+

int32_t UsbInitHostSdk(struct UsbSession **session);

Initializes the USB host driver DDK.

+

Initializes the USB host driver DDK.

int32_t UsbExitHostSdk(const struct UsbSession *session);

+

int32_t UsbExitHostSdk(const struct UsbSession *session);

Exits the USB host driver DDK.

+

Exits the USB host driver DDK.

const struct UsbInterface *UsbClaimInterface(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr, uint8_t interfaceIndex);

+

const struct UsbInterface *UsbClaimInterface(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr, uint8_t interfaceIndex);

Obtains a USB interface.

+

Obtains a USB interface.

int UsbReleaseInterface(const struct UsbInterface *interfaceObj);

+

int UsbReleaseInterface(const struct UsbInterface *interfaceObj);

Releases a USB interface.

+

Releases a USB interface.

int UsbAddOrRemoveInterface(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr, uint8_t interfaceIndex, UsbInterfaceStatus status);

+

int UsbAddOrRemoveInterface(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr, uint8_t interfaceIndex, UsbInterfaceStatus status);

Adds or removes a USB interface.

+

Adds or removes a USB interface.

UsbInterfaceHandle *UsbOpenInterface(const struct UsbInterface *interfaceObj);

+

UsbInterfaceHandle *UsbOpenInterface(const struct UsbInterface *interfaceObj);

Opens a USB interface.

+

Opens a USB interface.

int32_t UsbCloseInterface(const UsbInterfaceHandle *interfaceHandle);

+

int32_t UsbCloseInterface(const UsbInterfaceHandle *interfaceHandle);

Closes a USB interface.

+

Closes a USB interface.

int32_t UsbSelectInterfaceSetting(const UsbInterfaceHandle *interfaceHandle, uint8_t settingIndex, struct UsbInterface **interfaceObj);

+

int32_t UsbSelectInterfaceSetting(const UsbInterfaceHandle *interfaceHandle, uint8_t settingIndex, struct UsbInterface **interfaceObj);

Sets a USB interface.

+

Sets a USB interface.

int32_t UsbGetPipeInfo(const UsbInterfaceHandle *interfaceHandle, uint8_t settingIndex, uint8_t pipeId, struct UsbPipeInfo *pipeInfo);

+

int32_t UsbGetPipeInfo(const UsbInterfaceHandle *interfaceHandle, uint8_t settingIndex, uint8_t pipeId, struct UsbPipeInfo *pipeInfo);

Obtains USB pipe information.

+

Obtains USB pipe information.

int32_t UsbClearInterfaceHalt(const UsbInterfaceHandle *interfaceHandle, uint8_t pipeAddress);

+

int32_t UsbClearInterfaceHalt(const UsbInterfaceHandle *interfaceHandle, uint8_t pipeAddress);

Clears the state of the pipe with the specified index.

+

Clears the state of the pipe with the specified index.

struct UsbRequest *UsbAllocRequest(const UsbInterfaceHandle *interfaceHandle, int isoPackets, int length);

+

struct UsbRequest *UsbAllocRequest(const UsbInterfaceHandle *interfaceHandle, int isoPackets, int length);

Allocates a request object.

+

Allocates a request object.

int UsbFreeRequest(const struct UsbRequest *request);

+

int UsbFreeRequest(const struct UsbRequest *request);

Releases a request object.

+

Releases a request object.

int UsbSubmitRequestAsync(const struct UsbRequest *request);

+

int UsbSubmitRequestAsync(const struct UsbRequest *request);

Sends a request asynchronously.

+

Sends an asynchronous request.

int32_t UsbFillRequest(const struct UsbRequest *request, const UsbInterfaceHandle *interfaceHandle, const struct UsbRequestParams *params);

+

int32_t UsbFillRequest(const struct UsbRequest *request, const UsbInterfaceHandle *interfaceHandle, const struct UsbRequestParams *params);

Fills in a request.

+

Fills in a request.

sint UsbCancelRequest(const struct UsbRequest *request);

+

sint UsbCancelRequest(const struct UsbRequest *request);

Cancels an asynchronous request.

+

Cancels an asynchronous request.

int UsbSubmitRequestSync(const struct UsbRequest *request);

+

int UsbSubmitRequestSync(const struct UsbRequest *request);

Sends a synchronous request.

+

Sends a synchronous request.

usb_raw_api.h

-

-

-

-

-

+

usb_raw_api.h

int UsbRawInit(struct UsbSession **session);

+

int UsbRawInit(struct UsbSession **session);

Initializes the USB raw APIs.

+

Initializes the USB raw APIs.

int UsbRawExit(const struct UsbSession *session);

+

int UsbRawExit(const struct UsbSession *session);

Exits the USB raw APIs.

+

Exits the USB raw APIs.

UsbRawHandle *UsbRawOpenDevice(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr);

+

UsbRawHandle *UsbRawOpenDevice(const struct UsbSession *session, uint8_t busNum, uint8_t usbAddr);

Opens a USB device.

+

Opens a USB device.

int UsbRawCloseDevice(const UsbRawHandle *devHandle);

+

int UsbRawCloseDevice(const UsbRawHandle *devHandle);

Closes a USB device.

+

Closes a USB device.

int UsbRawSendControlRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbControlRequestData *requestData);

+

int UsbRawSendControlRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbControlRequestData *requestData);

Performs a control transfer synchronously.

+

Performs a control transfer synchronously.

int UsbRawSendBulkRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRequestData *requestData);

+

int UsbRawSendBulkRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRequestData *requestData);

Performs a bulk transfer synchronously.

+

Performs a bulk transfer synchronously.

int UsbRawSendInterruptRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRequestData *requestData);

+

int UsbRawSendInterruptRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRequestData *requestData);

Performs an interrupt transfer synchronously.

+

Performs an interrupt transfer synchronously.

int UsbRawGetConfigDescriptor(const UsbRawDevice *rawDev, uint8_t configIndex, struct UsbRawConfigDescriptor **config);

+

int UsbRawGetConfigDescriptor(const UsbRawDevice *rawDev, uint8_t configIndex, struct UsbRawConfigDescriptor **config);

Obtains the configuration descriptor of a device.

+

Obtains the configuration descriptor of a device.

void UsbRawFreeConfigDescriptor(const struct UsbRawConfigDescriptor *config);

+

void UsbRawFreeConfigDescriptor(const struct UsbRawConfigDescriptor *config);

Releases the memory space of a configuration descriptor.

+

Releases the memory space of a configuration descriptor.

int UsbRawGetConfiguration(const UsbRawHandle *devHandle, int *config);

+

int UsbRawGetConfiguration(const UsbRawHandle *devHandle, int *config);

Obtains the configuration in use.

+

Obtains the configuration in use.

int UsbRawSetConfiguration(const UsbRawHandle *devHandle, int config);

+

int UsbRawSetConfiguration(const UsbRawHandle *devHandle, int config);

Sets the configuration in use.

+

Sets the configuration in use.

int UsbRawGetDescriptor(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawDescriptorParam *param, const unsigned char *data);

+

int UsbRawGetDescriptor(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawDescriptorParam *param, const unsigned char *data);

Obtains descriptor information.

+

Obtains descriptor information.

UsbRawDevice *UsbRawGetDevice(const UsbRawHandle *devHandle);

+

UsbRawDevice *UsbRawGetDevice(const UsbRawHandle *devHandle);

Obtains the device pointer based on the device handle.

+

Obtains the device pointer based on the device handle.

int UsbRawGetDeviceDescriptor(const UsbRawDevice *rawDev, struct UsbDeviceDescriptor *desc);

+

int UsbRawGetDeviceDescriptor(const UsbRawDevice *rawDev, struct UsbDeviceDescriptor *desc);

Obtains the device descriptor of the specified USB device.

+

Obtains the device descriptor of the specified USB device.

int UsbRawClaimInterface(const UsbRawHandle *devHandle, int interfaceNumber);

+

int UsbRawClaimInterface(const UsbRawHandle *devHandle, int interfaceNumber);

Declares the interface on the specified device handle.

+

Declares the interface on the specified device handle.

int UsbRawReleaseInterface(const UsbRawHandle *devHandle, int interfaceNumber);

+

int UsbRawReleaseInterface(const UsbRawHandle *devHandle, int interfaceNumber);

Releases the previously declared interface.

+

Releases the previously declared interface.

int UsbRawResetDevice(const UsbRawHandle *devHandle);

+

int UsbRawResetDevice(const UsbRawHandle *devHandle);

Resets a device.

+

Resets a device.

struct UsbRawRequest *UsbRawAllocRequest(const UsbRawHandle *devHandle, int isoPackets, int length);

+

struct UsbRawRequest *UsbRawAllocRequest(const UsbRawHandle *devHandle, int isoPackets, int length);

Allocates a transfer request with the specified number of sync packet descriptors.

+

Allocates a transfer request with the specified number of sync packet descriptors.

int UsbRawFreeRequest(const struct UsbRawRequest *request);

+

int UsbRawFreeRequest(const struct UsbRawRequest *request);

Releases the previously allocated transfer request.

+

Releases the previously allocated transfer request.

int UsbRawFillBulkRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData);

+

int UsbRawFillBulkRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData);

Fills in the bulk transfer request.

+

Fills in a bulk transfer request.

int UsbRawFillControlSetup(const unsigned char *setup, const struct UsbControlRequestData *requestData);

+

int UsbRawFillControlSetup(const unsigned char *setup, const struct UsbControlRequestData *requestData);

Fills in the control setup packet.

+

Fills in a control setup packet.

int UsbRawFillControlRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData);

+

int UsbRawFillControlRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData);

Fills in the control transfer request.

+

Fills in a control transfer request.

int UsbRawFillInterruptRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData);

+

int UsbRawFillInterruptRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData);

Fills in the interrupt transfer request.

+

Fills in an interrupt transfer request.

int UsbRawFillIsoRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData);

+

int UsbRawFillIsoRequest(const struct UsbRawRequest *request, const UsbRawHandle *devHandle, const struct UsbRawFillRequestData *fillData);

Fills in the isochronous transfer request.

+

Fills in an isochronous transfer request.

int UsbRawSubmitRequest(const struct UsbRawRequest *request);

+

int UsbRawSubmitRequest(const struct UsbRawRequest *request);

Submits a transfer request.

+

Submits a transfer request.

int UsbRawCancelRequest(const struct UsbRawRequest *request);

+

int UsbRawCancelRequest(const struct UsbRawRequest *request);

Cancels a transfer request.

+

Cancels a transfer request.

int UsbRawHandleRequests(const UsbRawHandle *devHandle);

+

int UsbRawHandleRequests(const UsbRawHandle *devHandle);

Handles a transfer request event.

+

Handles a transfer request event.

-Table 2 describes the APIs provided by the USB device driver model. +[Figure 2](#fig8847615103013) describes the APIs provided by the USB device driver model. **Table 2** APIs provided by the USB device driver model - -

Header File

+ + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Header File

API

+

API

Description

+

Description

usbfn_device.h

-

-

+

usbfn_device.h

const struct UsbFnDevice *UsbFnCreateDevice(const char *udcName, const struct UsbFnDescriptorData *descriptor);

+

const struct UsbFnDevice *UsbFnCreateDevice(const char *udcName, const struct UsbFnDescriptorData *descriptor);

Creates a USB device.

+

Creates a USB device.

int UsbFnRemoveDevice(struct UsbFnDevice *fnDevice);

+

int UsbFnRemoveDevice(struct UsbFnDevice *fnDevice);

Deletes a USB device.

+

Deletes a USB device.

const struct UsbFnDevice *UsbFnGetDevice(const char *udcName);

+

const struct UsbFnDevice *UsbFnGetDevice(const char *udcName);

Obtains a USB device.

+

Obtains a USB device.

usbfn_interface.h

-

-

-

-

-

+

usbfn_interface.h

int UsbFnStartRecvInterfaceEvent(struct UsbFnInterface *interface, uint32_t eventMask, UsbFnEventCallback callback, void *context);

+

int UsbFnStartRecvInterfaceEvent(struct UsbFnInterface *interface, uint32_t eventMask, UsbFnEventCallback callback, void *context);

Starts to receive events.

+

Starts receiving events.

int UsbFnStopRecvInterfaceEvent(struct UsbFnInterface *interface);

+

int UsbFnStopRecvInterfaceEvent(struct UsbFnInterface *interface);

Stops receiving events.

+

Stops receiving events.

UsbFnInterfaceHandle UsbFnOpenInterface(struct UsbFnInterface *interface);

+

UsbFnInterfaceHandle UsbFnOpenInterface(struct UsbFnInterface *interface);

Opens an interface.

+

Opens an interface.

int UsbFnCloseInterface(UsbFnInterfaceHandle handle);

+

int UsbFnCloseInterface(UsbFnInterfaceHandle handle);

Closes an interface.

+

Closes an interface.

int UsbFnGetInterfacePipeInfo(struct UsbFnInterface *interface, uint8_t pipeId, struct UsbFnPipeInfo *info);

+

int UsbFnGetInterfacePipeInfo(struct UsbFnInterface *interface, uint8_t pipeId, struct UsbFnPipeInfo *info);

Obtains pipe information.

+

Obtains pipe information.

int UsbFnSetInterfaceProp(const struct UsbFnInterface *interface, const char *name, const char *value);

+

int UsbFnSetInterfaceProp(const struct UsbFnInterface *interface, const char *name, const char *value);

Sets custom properties.

+

Sets custom properties.

usbfn_request.h

-

-

-

-

-

-

-

+

usbfn_request.h

struct UsbFnRequest *UsbFnAllocCtrlRequest(UsbFnInterfaceHandle handle, uint32_t len);

+

struct UsbFnRequest *UsbFnAllocCtrlRequest(UsbFnInterfaceHandle handle, uint32_t len);

Applies for a control transfer request.

+

Applies for a control transfer request.

struct UsbFnRequest *UsbFnAllocRequest(UsbFnInterfaceHandle handle, uint8_t pipe, uint32_t len);

+

struct UsbFnRequest *UsbFnAllocRequest(UsbFnInterfaceHandle handle, uint8_t pipe, uint32_t len);

Applies for a data request.

+

Applies for a data request.

int UsbFnFreeRequest(struct UsbFnRequest *req);

+

int UsbFnFreeRequest(struct UsbFnRequest *req);

Releases a request.

+

Releases a request.

int UsbFnSubmitRequestAsync(struct UsbFnRequest *req);

+

int UsbFnSubmitRequestAsync(struct UsbFnRequest *req);

Sends a request asynchronously.

+

Sends an asynchronous request.

int UsbFnSubmitRequestSync(struct UsbFnRequest *req, uint32_t timeout);

+

int UsbFnSubmitRequestSync(struct UsbFnRequest *req, uint32_t timeout);

Sends a request synchronously.

+

Sends a synchronous request.

int UsbFnCancelRequest(struct UsbFnRequest *req);

+

int UsbFnCancelRequest(struct UsbFnRequest *req);

Cancels a request.

+

Cancels a request.

-## Development Guidelines +## Development Guidelines The USB driver is developed based on the Hardware Driver Foundation (HDF), platform, and Operating System Abstraction Layer (OSAL) APIs. A unified driver model is provided for USB devices, irrespective of the operating system and chip architecture. This document uses a serial port as an example to describe how to develop drivers for the USB host and USB device. -### How to Develop +### How to Develop -### Developing Driver Using Host DDK APIs +### Developing Driver Using Host DDK APIs 1. Configure the driver mapping table. 2. Initialize the USB host DDK. @@ -405,15 +384,14 @@ The USB driver is developed based on the Hardware Driver Foundation (HDF), platf 7. Fill in the I/O request based on the input parameters. 8. Submit the I/O request in synchronous or asynchronous mode. - -### Developing Driver Using Host Raw APIs +### Developing Driver Using Host Raw APIs 1. Configure the driver mapping table. 2. Initialize the host raw data, open the USB device, obtain the descriptor, and then obtain interface and endpoint information based on the descriptor. 3. Allocate a request and fill in the request based on the transfer type. -4. Submit the I/O request object in synchronous or asynchronous mode. +4. Submit the I/O request in synchronous or asynchronous mode. -### Developing Driver Using Device DDK APIs +### Developing Driver Using Device DDK APIs 1. Construct a descriptor. 2. Instantiate a USB device using the descriptor constructed. @@ -421,11 +399,11 @@ The USB driver is developed based on the Hardware Driver Foundation (HDF), platf 4. Call **UsbFnInterfaceStartRecvEvent** to receive events such as Enable and Setup, and respond to the events in **UsbFnEventCallback**. 5. Send and receive data in synchronous or asynchronous mode. -## Development Examples +## Development Examples -The following example helps you better understand the development of the USB serial port driver. +The following examples help you better understand the development of the USB serial port driver. -### Developing Driver Using Host DDK APIs +### Developing Driver Using Host DDK APIs ``` root { @@ -435,42 +413,42 @@ root { usb_pnp_device_id = "UsbPnpDeviceId"; UsbPnpDeviceId { idTableList = [ - "host_acm_table" - ]; - host_acm_table { - // Driver module name, which must be the same as the value of moduleName in the driver entry structure. - moduleName = "usbhost_acm"; - // Service name of the driver, which must be unique. - serviceName = "usbhost_acm_pnp_service"; - // Keyword for matching private driver data. - deviceMatchAttr = "usbhost_acm_pnp_matchAttr"; - // Data length starting from this field, in bytes. - length = 21; - // USB driver matching rule: vendorId+productId+interfaceSubClass+interfaceProtocol+interfaceNumber. - matchFlag = 0x0303; - // Vendor ID. - vendorId = 0x12D1; - // Product ID. - productId = 0x5000; - // The least significant 16 bits of the device sequence number. - bcdDeviceLow = 0x0000; - // The most significant 16 bits of the device sequence number. - bcdDeviceHigh = 0x0000; - // Device class code allocated by the USB. - deviceClass = 0; - // Child class code allocated by the USB. - deviceSubClass = 0; - // Device protocol code allocated by the USB. - deviceProtocol = 0; - // Interface type. You can enter multiple types as needed. - interfaceClass = [0]; - // Interface subtype. You can enter multiple subtypes as needed. - interfaceSubClass = [2, 0]; - // Protocol that the interface complies with. You can enter multiple protocols as needed. - interfaceProtocol = [1, 2]; - // Interface numer. You can enter multiple interface numbers as needed. - interfaceNumber = [2, 3]; - } + "host_acm_table" + ]; + host_acm_table { + // Driver module name, which must be the same as the value of moduleName in the driver entry structure. + moduleName = "usbhost_acm"; + // Service name of the driver, which must be unique. + serviceName = "usbhost_acm_pnp_service"; + // Keyword for matching private driver data. + deviceMatchAttr = "usbhost_acm_pnp_matchAttr"; + // Data length starting from this field, in bytes. + length = 21; + // USB driver matching rule: vendorId+productId+interfaceSubClass+interfaceProtocol+interfaceNumber. + matchFlag = 0x0303; + // Vendor ID. + vendorId = 0x12D1; + // Product ID. + productId = 0x5000; + // The least significant 16 bits of the device sequence number. + bcdDeviceLow = 0x0000; + // The most significant 16 bits of the device sequence number. + bcdDeviceHigh = 0x0000; + // Device class code allocated by the USB. + deviceClass = 0; + // Child class code allocated by the USB. + deviceSubClass = 0; + // Device protocol code allocated by the USB. + deviceProtocol = 0; + // Interface type. You can enter multiple types as needed. + interfaceClass = [0]; + // Interface subtype. You can enter multiple subtypes as needed. + interfaceSubClass = [2, 0]; + // Protocol that the interface complies with. You can enter multiple protocols as needed. + interfaceProtocol = [1, 2]; + // Interface number. You can enter multiple interface numbers as needed. + interfaceNumber = [2, 3]; + } } } } @@ -497,16 +475,16 @@ static int SerialCtrlMsg(struct AcmDevice *acm, uint8_t request, { int ret; uint16_t index = acm->intPipe->interfaceId; - struct UsbControlParams controlParams = {}; - struct UsbRequestParams parmas = {}; + struct UsbControlParams controlParams; + struct UsbRequestParams params; if (acm == NULL || buf == NULL) { - HDF_LOGE("%{public}s:invalid param", __func__); + HDF_LOGE("%s:invalid param", __func__); return HDF_ERR_IO; } if (acm->ctrlReq == NULL) { acm->ctrlReq = UsbAllocRequest(acm->ctrDevHandle, 0, len); if (acm->ctrlReq == NULL) { - HDF_LOGE("%{public}s: UsbAllocRequest failed", __func__); + HDF_LOGE("%s: UsbAllocRequest failed", __func__); return HDF_ERR_IO; } } @@ -520,24 +498,24 @@ static int SerialCtrlMsg(struct AcmDevice *acm, uint8_t request, controlParams.data = buf; controlParams.size = len; - parmas.interfaceId = USB_CTRL_INTERFACE_ID; - parmas.pipeAddress = acm->ctrPipe->pipeAddress; - parmas.pipeId = acm->ctrPipe->pipeId; - parmas.requestType = USB_REQUEST_PARAMS_CTRL_TYPE; - parmas.timeout = USB_CTRL_SET_TIMEOUT; - parmas.ctrlReq = UsbControlSetUp(&controlParams); - ret = UsbFillRequest(acm->ctrlReq, acm->ctrDevHandle, &parmas); + params.interfaceId = USB_CTRL_INTERFACE_ID; + params.pipeAddress = acm->ctrPipe->pipeAddress; + params.pipeId = acm->ctrPipe->pipeId; + params.requestType = USB_REQUEST_PARAMS_CTRL_TYPE; + params.timeout = USB_CTRL_SET_TIMEOUT; + params.ctrlReq = UsbControlSetUp(&controlParams); + ret = UsbFillRequest(acm->ctrlReq, acm->ctrDevHandle, ¶ms); if (HDF_SUCCESS != ret) { - HDF_LOGE("%{public}s: failed, ret=%{public}d ", __func__, ret); + HDF_LOGE("%s: failed, ret=%d ", __func__, ret); return ret; } - ret = UsbSubmitRequestSync(acm->ctrlReq); // Send an I/O request synchronously. + ret = UsbSubmitRequestSync(acm->ctrlReq); // Send an I/O request synchronously. if (HDF_SUCCESS != ret) { - HDF_LOGE("UsbSubmitRequestSync faile, ret=%{public}d ", ret); + HDF_LOGE("UsbSubmitRequestSync failed, ret=%d ", ret); return ret; } if (!acm->ctrlReq->compInfo.status) { - HDF_LOGE("%{public}s status=%{public}d ", __func__, acm->ctrlReq->compInfo.status); + HDF_LOGE("%s status=%d ", __func__, acm->ctrlReq->compInfo.status); } return HDF_SUCCESS; } @@ -546,8 +524,8 @@ static struct UsbInterface *GetUsbInterfaceById(const struct AcmDevice *acm, uint8_t interfaceIndex) { struct UsbInterface *tmpIf = NULL; - tmpIf = (struct UsbInterface *)UsbClaimInterface(acm->session, acm->busNum, \ - acm->devAddr, interfaceIndex); // Obtain the UsbInterface object. + tmpIf = (struct UsbInterface *)UsbClaimInterface(acm->session, acm->busNum, + acm->devAddr, interfaceIndex); // Obtain the UsbInterface object. return tmpIf; } ... @@ -578,7 +556,7 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm, if ((p.pipeDirection == pipeDirection) && (p.pipeType == pipeType)) { struct UsbPipeInfo *pi = OsalMemCalloc(sizeof(*pi)); if (pi == NULL) { - HDF_LOGE("%{public}s: Alloc pipe failed", __func__); + HDF_LOGE("%s: Alloc pipe failed", __func__); return NULL; } p.interfaceId = info->interfaceIndex; @@ -594,7 +572,7 @@ static struct UsbPipeInfo *GetPipe(const struct AcmDevice *acm, { uint8_t i; if (acm == NULL) { - HDF_LOGE("%{public}s: invalid parmas", __func__); + HDF_LOGE("%s: invalid params", __func__); return NULL; } for (i = 0; i < acm->interfaceCnt; i++) { @@ -627,12 +605,12 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) return HDF_FAILURE; } if (OsalMutexInit(&acm->lock) != HDF_SUCCESS) { - HDF_LOGE("%s:%d OsalMutexInit fail", __func__, __LINE__); + HDF_LOGE("%s:%d OsalMutexInit failed", __func__, __LINE__); goto error; } info = (struct UsbPnpNotifyServiceInfo *)device->priv; if (info != NULL) { - HDF_LOGD("%s:%d busNum=%d,devAddr=%d,interfaceLength=%d", \ + HDF_LOGD("%s:%d busNum=%d,devAddr=%d,interfaceLength=%d", __func__, __LINE__, info->busNum, info->devNum, info->interfaceLength); acm->busNum = info->busNum; acm->devAddr = info->devNum; @@ -640,7 +618,7 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) err = memcpy_s((void *)(acm->interfaceIndex), USB_MAX_INTERFACES, (const void*)info->interfaceNumber, info->interfaceLength); if (err != EOK) { - HDF_LOGE("%s:%d memcpy_s failed err=%d", \ + HDF_LOGE("%s:%d memcpy_s failed err=%d", __func__, __LINE__, err); goto lock_error; } @@ -656,7 +634,7 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) lock_error: if (OsalMutexDestroy(&acm->lock)) { - HDF_LOGE("%s:%d OsalMutexDestroy fail", __func__, __LINE__); + HDF_LOGE("%s:%d OsalMutexDestroy failed", __func__, __LINE__); } error: OsalMemFree(acm); @@ -667,26 +645,26 @@ error: static int AcmAllocReadRequests(struct AcmDevice *acm) { int ret; - struct UsbRequestParams readParmas = {}; + struct UsbRequestParams readParams; for (int i = 0; i < ACM_NR; i++) { - acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize); // Allocate the readReq I/O request object to be sent. + acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize); // Allocate the readReq I/O request to be sent. if (!acm->readReq[i]) { - HDF_LOGE("readReq request failed\n"); + HDF_LOGE("readReq request failed"); goto error; } - readParmas.userData = (void *)acm; - readParmas.pipeAddress = acm->dataInPipe->pipeAddress; - readParmas.pipeId = acm->dataInPipe->pipeId; - readParmas.interfaceId = acm->dataInPipe->interfaceId; - readParmas.callback = AcmReadBulk; - readParmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; - readParmas.timeout = USB_CTRL_SET_TIMEOUT; - readParmas.dataReq.numIsoPackets = 0; - readParmas.dataReq.directon = (acm->dataInPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; - readParmas.dataReq.length = acm->readSize; - ret = UsbFillRequest(acm->readReq[i], InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), &readParmas); // Fill in the readReq object to be sent. + readParams.userData = (void *)acm; + readParams.pipeAddress = acm->dataInPipe->pipeAddress; + readParams.pipeId = acm->dataInPipe->pipeId; + readParams.interfaceId = acm->dataInPipe->interfaceId; + readParams.callback = AcmReadBulk; + readParams.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + readParams.timeout = USB_CTRL_SET_TIMEOUT; + readParams.dataReq.numIsoPackets = 0; + readParams.dataReq.directon = (acm->dataInPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & 0x1; + readParams.dataReq.length = acm->readSize; + ret = UsbFillRequest(acm->readReq[i], InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), &readParams); // Fills in the readReq object to be sent. if (HDF_SUCCESS != ret) { - HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + HDF_LOGE("%s: UsbFillRequest failed, ret=%d n", __func__, ret); goto error; } } @@ -700,25 +678,25 @@ error: static int AcmAllocNotifyRequest(struct AcmDevice *acm) { int ret; - struct UsbRequestParams intParmas = {}; - acm->notifyReq = UsbAllocRequest(InterfaceIdToHandle(acm, acm->intPipe->interfaceId), 0, acm->intSize); // Allocate the interrupt I/O request object to be sent. + struct UsbRequestParams intParams = {}; + acm->notifyReq = UsbAllocRequest(InterfaceIdToHandle(acm, acm->intPipe->interfaceId), 0, acm->intSize); // Allocate the interrupt I/O request object to be sent. if (!acm->notifyReq) { - HDF_LOGE("notifyReq request fail\n"); + HDF_LOGE("notifyReq request failed"); return HDF_ERR_MALLOC_FAIL; } - intParmas.userData = (void *)acm; - intParmas.pipeAddress = acm->intPipe->pipeAddress; - intParmas.pipeId = acm->intPipe->pipeId; - intParmas.interfaceId = acm->intPipe->interfaceId; - intParmas.callback = AcmCtrlIrq; - intParmas.requestType = USB_REQUEST_PARAMS_DATA_TYPE; - intParmas.timeout = USB_CTRL_SET_TIMEOUT; - intParmas.dataReq.numIsoPackets = 0; - intParmas.dataReq.directon = (acm->intPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & DIRECTION_MASK; - intParmas.dataReq.length = acm->intSize; - ret = UsbFillRequest(acm->notifyReq, InterfaceIdToHandle(acm, acm->intPipe->interfaceId), &intParmas); // Fill in the interrupt I/O request. + intParams.userData = (void *)acm; + intParams.pipeAddress = acm->intPipe->pipeAddress; + intParams.pipeId = acm->intPipe->pipeId; + intParams.interfaceId = acm->intPipe->interfaceId; + intParams.callback = AcmCtrlIrq; + intParams.requestType = USB_REQUEST_PARAMS_DATA_TYPE; + intParams.timeout = USB_CTRL_SET_TIMEOUT; + intParams.dataReq.numIsoPackets = 0; + intParams.dataReq.directon = (acm->intPipe->pipeDirection >> USB_PIPE_DIR_OFFSET) & DIRECTION_MASK; + intParams.dataReq.length = acm->intSize; + ret = UsbFillRequest(acm->notifyReq, InterfaceIdToHandle(acm, acm->intPipe->interfaceId), &intParams); // Fill in the interrupt I/O request. if (HDF_SUCCESS != ret) { - HDF_LOGE("%{public}s: UsbFillRequest faile, ret=%{public}d \n", __func__, ret); + HDF_LOGE("%s: UsbFillRequest failed, ret=%d n", __func__, ret); goto error; } return HDF_SUCCESS; @@ -745,16 +723,16 @@ static void AcmReleaseInterfaces(struct AcmDevice *acm) static int32_t AcmClaimInterfaces(struct AcmDevice *acm) { for (int i = 0; i < acm->interfaceCnt; i++) { - acm->iface[i] = GetUsbInterfaceById((const struct AcmDevice *)acm, acm->interfaceIndex[i]); // Obtain the UsbInterface object. + acm->iface[i] = GetUsbInterfaceById((const struct AcmDevice *)acm, acm->interfaceIndex[i]); // Obtain the UsbInterface object. if (acm->iface[i] == NULL) { - HDF_LOGE("%{public}s: interface%{public}d is null", __func__, acm->interfaceIndex[i]); + HDF_LOGE("%s: interface%d is null", __func__, acm->interfaceIndex[i]); goto error; } } - acm->ctrIface = GetUsbInterfaceById((const struct AcmDevice *)acm, USB_CTRL_INTERFACE_ID); // Obtain the UsbInterface object corresponding to the control interface. + acm->ctrIface = GetUsbInterfaceById((const struct AcmDevice *)acm, USB_CTRL_INTERFACE_ID); // Obtain the UsbInterface object corresponding to the control interface. if (acm->ctrIface == NULL) { - HDF_LOGE("%{public}s: GetUsbInterfaceById null", __func__); + HDF_LOGE("%s: GetUsbInterfaceById null", __func__); goto error; } @@ -783,16 +761,16 @@ static int32_t AcmOpenInterfaces(struct AcmDevice *acm) { for (int i = 0; i < acm->interfaceCnt; i++) { if (acm->iface[i]) { - acm->devHandle[i] = UsbOpenInterface(acm->iface[i]); // Open the UsbInterface object obtained. + acm->devHandle[i] = UsbOpenInterface(acm->iface[i]); // Open the UsbInterface object obtained. if (acm->devHandle[i] == NULL) { - HDF_LOGE("%{public}s: UsbOpenInterface null", __func__); + HDF_LOGE("%s: UsbOpenInterface null", __func__); goto error; } } } acm->ctrDevHandle = UsbOpenInterface(acm->ctrIface); if (acm->ctrDevHandle == NULL) { - HDF_LOGE("%{public}s: ctrDevHandle UsbOpenInterface null", __func__); + HDF_LOGE("%s: ctrDevHandle UsbOpenInterface null", __func__); goto error; } @@ -805,7 +783,7 @@ error: static int32_t AcmGetPipes(struct AcmDevice *acm) { - acm->dataInPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_IN); // Obtain pipe information of dataInPipe. + acm->dataInPipe = GetPipe(acm, USB_PIPE_TYPE_BULK, USB_PIPE_DIRECTION_IN);// Obtain pipe information of dataInPipe. if (acm->dataInPipe == NULL) { HDF_LOGE("dataInPipe is NULL"); goto error; @@ -817,7 +795,7 @@ static int32_t AcmGetPipes(struct AcmDevice *acm) goto error; } - acm->ctrPipe = EnumePipe(acm, acm->ctrIface->info.interfaceIndex, USB_PIPE_TYPE_CONTROL, USB_PIPE_DIRECTION_OUT); // Obtain pipe information of the control pipe. + acm->ctrPipe = EnumePipe(acm, acm->ctrIface->info.interfaceIndex, USB_PIPE_TYPE_CONTROL, USB_PIPE_DIRECTION_OUT); // Obtain pipe information of the control pipe. if (acm->ctrPipe == NULL) { HDF_LOGE("ctrPipe is NULL"); goto error; @@ -858,29 +836,29 @@ static int32_t AcmAllocRequests(struct AcmDevice *acm) int32_t ret; if (AcmWriteBufAlloc(acm) < 0) { - HDF_LOGE("%{public}s: AcmWriteBufAlloc failed", __func__); + HDF_LOGE("%s: AcmWriteBufAlloc failed", __func__); return HDF_ERR_MALLOC_FAIL; } for (int i = 0; i < ACM_NW; i++) { struct AcmWb *snd = &(acm->wb[i]); - snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize); // Allocate the I/O request object to be sent. + snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize); // Allocate the I/O request object to be sent. snd->instance = acm; if (snd->request == NULL) { - HDF_LOGE("%{public}s:%{public}d snd request fail", __func__, __LINE__); + HDF_LOGE("%s:%d snd request failed", __func__, __LINE__); goto error_alloc_write_req; } } - ret = AcmAllocNotifyRequest(acm); // Allocate and fill in the interrupt I/O request object. + ret = AcmAllocNotifyRequest(acm); // Allocate and fill in the interrupt I/O request object. if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s:%{public}d AcmAllocNotifyRequest fail", __func__, __LINE__); + HDF_LOGE("%s:%d AcmAllocNotifyRequest failed", __func__, __LINE__); goto error_alloc_int_req; } - ret = AcmAllocReadRequests(acm); // Allocate and fill in the readReq I/O request object. + ret = AcmAllocReadRequests(acm); // Allocate and fill in the readReq I/O request object. if (ret) { - HDF_LOGE("%{public}s:%{public}d AcmAllocReadRequests fail", __func__, __LINE__); + HDF_LOGE("%s:%d AcmAllocReadRequests failed", __func__, __LINE__); goto error_alloc_read_req; } @@ -901,38 +879,38 @@ static int32_t AcmInit(struct AcmDevice *acm) struct UsbSession *session = NULL; if (acm->initFlag == true) { - HDF_LOGE("%{public}s:%{public}d: initFlag is true", __func__, __LINE__); + HDF_LOGE("%s:%d: initFlag is true", __func__, __LINE__); return HDF_SUCCESS; } - ret = UsbInitHostSdk(NULL); // Initialize the host DDK. + ret = UsbInitHostSdk(NULL); // Initialize the Host DDK. if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: UsbInitHostSdk failed", __func__); + HDF_LOGE("%s: UsbInitHostSdk failed", __func__); return HDF_ERR_IO; } acm->session = session; ret = AcmClaimInterfaces(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: AcmClaimInterfaces failed", __func__); + HDF_LOGE("%s: AcmClaimInterfaces failed", __func__); goto error_claim_interfaces; } ret = AcmOpenInterfaces(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: AcmOpenInterfaces failed", __func__); + HDF_LOGE("%s: AcmOpenInterfaces failed", __func__); goto error_open_interfaces; } ret = AcmGetPipes(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: AcmGetPipes failed", __func__); + HDF_LOGE("%s: AcmGetPipes failed", __func__); goto error_get_pipes; } ret = AcmAllocRequests(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: AcmAllocRequests failed", __func__); + HDF_LOGE("%s: AcmAllocRequests failed", __func__); goto error_alloc_reqs; } @@ -942,7 +920,7 @@ static int32_t AcmInit(struct AcmDevice *acm) acm->lineCoding.bDataBits = USB_CDC_1_STOP_BITS; acm->initFlag = true; - HDF_LOGD("%{public}s:%{public}d========OK", __func__, __LINE__); + HDF_LOGD("%s:%d========OK", __func__, __LINE__); return HDF_SUCCESS; error_alloc_reqs: @@ -960,7 +938,7 @@ error_claim_interfaces: static void AcmRelease(struct AcmDevice *acm) { if (acm->initFlag == false) { - HDF_LOGE("%{public}s:%{public}d: initFlag is false", __func__, __LINE__); + HDF_LOGE("%s:%d: initFlag is false", __func__, __LINE__); return; } @@ -980,24 +958,24 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) struct AcmDevice *acm = NULL; if (device == NULL) { - HDF_LOGE("%{public}s: device is null", __func__); + HDF_LOGE("%s: device is null", __func__); return HDF_ERR_INVALID_OBJECT; } acm = (struct AcmDevice *)device->service; OsalMutexInit(&acm->readLock); OsalMutexInit(&acm->writeLock); - HDF_LOGD("%{public}s:%{public}d busNum=%{public}d,devAddr=%{public}d", \ + HDF_LOGD("%s:%d busNum=%d,devAddr=%d", __func__, __LINE__, acm->busNum, acm->devAddr); ret = UsbSerialDeviceAlloc(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: Serial Device alloc failed", __func__); + HDF_LOGE("%s: Serial Device alloc failed", __func__); } acm->initFlag = false; g_acmReleaseFlag = false; - HDF_LOGD("%{public}s:%{public}d init ok!", __func__, __LINE__); + HDF_LOGD("%s:%d init ok!", __func__, __LINE__); return ret; } @@ -1007,19 +985,19 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) struct AcmDevice *acm = NULL; if (device == NULL) { - HDF_LOGE("%{public}s: device is NULL", __func__); + HDF_LOGE("%s: device is NULL", __func__); return; } acm = (struct AcmDevice *)device->service; if (acm == NULL) { - HDF_LOGE("%{public}s: acm is null", __func__); + HDF_LOGE("%s: acm is null", __func__); return; } g_acmReleaseFlag = true; if (acm->initFlag == true) { - HDF_LOGE("%{public}s:%{public}d AcmRelease", __func__, __LINE__); + HDF_LOGE("%s:%d AcmRelease", __func__, __LINE__); AcmRelease(acm); } UsbSeriaDevicelFree(acm); @@ -1028,12 +1006,12 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) OsalMutexDestroy(&acm->lock); OsalMemFree(acm); acm = NULL; - HDF_LOGD("%{public}s:%{public}d exit", __func__, __LINE__); + HDF_LOGD("%s:%d exit", __func__, __LINE__); } struct HdfDriverEntry g_usbSerialDriverEntry = { .moduleVersion = 1, - .moduleName = "usbhost_acm", // Driver module name, which must be the same as that configured in the .hcs file. + .moduleName = "usbhost_acm", // Driver module name, which must be the same as that configured in the .hcs file. .Bind = UsbSerialDriverBind, .Init = UsbSerialDriverInit, .Release = UsbSerialDriverRelease, @@ -1041,7 +1019,7 @@ struct HdfDriverEntry g_usbSerialDriverEntry = { HDF_INIT(g_usbSerialDriverEntry); ``` -### Developing Driver Using Host Raw APIs +### Developing Driver Using Host Raw APIs ``` root { @@ -1053,38 +1031,38 @@ root { idTableList = [ "host_acm_rawapi_table" ]; - host_acm_rawapi_table { // Driver mapping table information. - // Driver module name, which must be the same as the value of moduleName in the driver entry structure. + host_acm_rawapi_table { // Driver mapping table information. + // Driver module name, which must be the same as the value of moduleName in the driver entry structure. moduleName = "usbhost_acm_rawapi"; - // Service name of the driver, which must be unique. + // Service name of the driver, which must be unique. serviceName = "usbhost_acm_rawapi_service"; - // Keyword for matching private driver data. + // Keyword for matching private driver data. deviceMatchAttr = "usbhost_acm_rawapi_matchAttr"; - // Data length starting from this field, in bytes. - length = 21; - // USB driver matching rule: vendorId+productId+interfaceSubClass+interfaceProtocol+interfaceNumber. + // Data length starting from this field, in bytes. + length = 21; + // USB driver matching rule: vendorId+productId+interfaceSubClass+interfaceProtocol+interfaceNumber. matchFlag = 0x0303; - // Vendor ID. + // Vendor ID. vendorId = 0x12D1; - // Product ID. + // Product ID. productId = 0x5000; - // The least significant 16 bits of the device sequence number. + // The least significant 16 bits of the device sequence number. bcdDeviceLow = 0x0000; - // The most significant 16 bits of the device sequence number. + // The most significant 16 bits of the device sequence number. bcdDeviceHigh = 0x0000; - // Device class code allocated by the USB. + // Device class code allocated by the USB. deviceClass = 0; - // Child class code allocated by the USB. + // Child class code allocated by the USB. deviceSubClass = 0; - // Device protocol code allocated by the USB. + // Device protocol code allocated by the USB. deviceProtocol = 0; - // Interface type. You can enter multiple types as needed. + // Interface type. You can enter multiple types as needed. interfaceClass = [0]; - // Interface subtype. You can enter multiple subtypes as needed. + // Interface subtype. You can enter multiple subtypes as needed. interfaceSubClass = [2, 0]; - // Protocol that the interface complies with. You can enter multiple protocols as needed. + // Protocol that the interface complies with. You can enter multiple protocols as needed. interfaceProtocol = [1, 2]; - // Interface numer. You can enter multiple interface numbers as needed. + // Interface number. You can enter multiple interface numbers as needed. interfaceNumber = [2, 3]; } } @@ -1119,28 +1097,28 @@ static int UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDe int ret; if (devHandle == NULL) { - HDF_LOGE("%{public}s:%{public}d devHandle is NULL", + HDF_LOGE("%s:%d devHandle is NULL", __func__, __LINE__); return HDF_ERR_INVALID_PARAM; } ret = UsbRawGetConfiguration(devHandle, &activeConfig); if (ret) { - HDF_LOGE("%{public}s:%{public}d UsbRawGetConfiguration failed, ret=%{public}d", + HDF_LOGE("%s:%d UsbRawGetConfiguration failed, ret=%d", __func__, __LINE__, ret); return HDF_FAILURE; } - HDF_LOGE("%{public}s:%{public}d activeConfig=%{public}d", __func__, __LINE__, activeConfig); + HDF_LOGE("%s:%d activeConfig=%d", __func__, __LINE__, activeConfig); dev = UsbRawGetDevice(devHandle); if (dev == NULL) { - HDF_LOGE("%{public}s:%{public}d UsbRawGetDevice failed", + HDF_LOGE("%s:%d UsbRawGetDevice failed", __func__, __LINE__); return HDF_FAILURE; } ret = UsbRawGetConfigDescriptor(dev, activeConfig, config); if (ret) { - HDF_LOGE("UsbRawGetConfigDescriptor failed, ret=%{public}d\n", ret); + HDF_LOGE("UsbRawGetConfigDescriptor failed, ret=%dn", ret); return HDF_FAILURE; } @@ -1156,7 +1134,7 @@ static int UsbAllocWriteRequests(struct AcmDevice *acm) snd->request = UsbRawAllocRequest(acm->devHandle, 0, acm->dataOutEp->maxPacketSize); snd->instance = acm; if (snd->request == NULL) { - HDF_LOGE("%{public}s: UsbRawAllocRequest failed", __func__); + HDF_LOGE("%s: UsbRawAllocRequest failed", __func__); return HDF_ERR_MALLOC_FAIL; } } @@ -1182,7 +1160,7 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) return HDF_FAILURE; } if (OsalMutexInit(&acm->lock) != HDF_SUCCESS) { - HDF_LOGE("%s:%d OsalMutexInit fail", __func__, __LINE__); + HDF_LOGE("%s:%d OsalMutexInit failed", __func__, __LINE__); goto error; } @@ -1194,7 +1172,7 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) err = memcpy_s((void *)(acm->interfaceIndex), USB_MAX_INTERFACES, (const void*)info->interfaceNumber, info->interfaceLength); if (err != EOK) { - HDF_LOGE("%s:%d memcpy_s failed err=%d", \ + HDF_LOGE("%s:%d memcpy_s failed err=%d", __func__, __LINE__, err); goto lock_error; } @@ -1211,7 +1189,7 @@ static int32_t UsbSerialDriverBind(struct HdfDeviceObject *device) lock_error: if (OsalMutexDestroy(&acm->lock)) { - HDF_LOGE("%s:%d OsalMutexDestroy fail", __func__, __LINE__); + HDF_LOGE("%s:%d OsalMutexDestroy failed", __func__, __LINE__); } error: OsalMemFree(acm); @@ -1228,7 +1206,7 @@ static int UsbAllocReadRequests(struct AcmDevice *acm) for (int i = 0; i < ACM_NR; i++) { acm->readReq[i] = UsbRawAllocRequest(acm->devHandle, 0, size); if (!acm->readReq[i]) { - HDF_LOGE("readReq request failed\n"); + HDF_LOGE("readReq request failed"); return HDF_ERR_MALLOC_FAIL; } @@ -1241,7 +1219,7 @@ static int UsbAllocReadRequests(struct AcmDevice *acm) ret = UsbRawFillBulkRequest(acm->readReq[i], acm->devHandle, &reqData); if (ret) { - HDF_LOGE("%{public}s: FillBulkRequest faile, ret=%{public}d \n", + HDF_LOGE("%s: FillBulkRequest failed, ret=%d n", __func__, ret); return HDF_FAILURE; } @@ -1258,7 +1236,7 @@ static int UsbAllocNotifyRequest(struct AcmDevice *acm) acm->notifyReq = UsbRawAllocRequest(acm->devHandle, 0, size); if (!acm->notifyReq) { - HDF_LOGE("notifyReq request fail\n"); + HDF_LOGE("notifyReq request failed"); return HDF_ERR_MALLOC_FAIL; } @@ -1271,7 +1249,7 @@ static int UsbAllocNotifyRequest(struct AcmDevice *acm) ret = UsbRawFillInterruptRequest(acm->notifyReq, acm->devHandle, &fillRequestData); if (ret) { - HDF_LOGE("%{public}s: FillInterruptRequest faile, ret=%{public}d", __func__, ret); + HDF_LOGE("%s: FillInterruptRequest failed, ret=%d", __func__, ret); return HDF_FAILURE; } @@ -1285,62 +1263,62 @@ static int32_t UsbSerialInit(struct AcmDevice *acm) int32_t ret; if (acm->initFlag == true) { - HDF_LOGE("%{public}s:%{public}d: initFlag is true", __func__, __LINE__); + HDF_LOGE("%s:%d: initFlag is true", __func__, __LINE__); return HDF_SUCCESS; } ret = UsbRawInit(NULL); if (ret) { - HDF_LOGE("%{public}s:%{public}d UsbRawInit failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbRawInit failed", __func__, __LINE__); return HDF_ERR_IO; } acm->session = session; devHandle = UsbRawOpenDevice(session, acm->busNum, acm->devAddr); if (devHandle == NULL) { - HDF_LOGE("%{public}s:%{public}d UsbRawOpenDevice failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbRawOpenDevice failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_open_device; } acm->devHandle = devHandle; ret = UsbGetConfigDescriptor(devHandle, &acm->config); if (ret) { - HDF_LOGE("%{public}s:%{public}d UsbGetConfigDescriptor failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbGetConfigDescriptor failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_get_desc; } ret = UsbParseConfigDescriptor(acm, acm->config); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s:%{public}d UsbParseConfigDescriptor failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbParseConfigDescriptor failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_parse_desc; } ret = AcmWriteBufAlloc(acm); if (ret < 0) { - HDF_LOGE("%{public}s:%{public}d AcmWriteBufAlloc failed", __func__, __LINE__); + HDF_LOGE("%s:%d AcmWriteBufAlloc failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_alloc_write_buf; } ret = UsbAllocWriteRequests(acm); if (ret < 0) { - HDF_LOGE("%{public}s:%{public}d UsbAllocWriteRequests failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbAllocWriteRequests failed", __func__, __LINE__); ret = HDF_FAILURE; goto err_alloc_write_reqs; } ret = UsbAllocNotifyRequest(acm); if (ret) { - HDF_LOGE("%{public}s:%{public}d UsbAllocNotifyRequests failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbAllocNotifyRequests failed", __func__, __LINE__); goto err_alloc_notify_req; } ret = UsbAllocReadRequests(acm); if (ret) { - HDF_LOGE("%{public}s:%{public}d UsbAllocReadRequests failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbAllocReadRequests failed", __func__, __LINE__); goto err_alloc_read_reqs; } ret = UsbStartIo(acm); if (ret) { - HDF_LOGE("%{public}s:%{public}d UsbAllocReadRequests failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbAllocReadRequests failed", __func__, __LINE__); goto err_start_io; } @@ -1351,13 +1329,13 @@ static int32_t UsbSerialInit(struct AcmDevice *acm) ret = UsbRawSubmitRequest(acm->notifyReq); if (ret) { - HDF_LOGE("%{public}s:%{public}d UsbRawSubmitRequest failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbRawSubmitRequest failed", __func__, __LINE__); goto err_submit_req; } acm->initFlag = true; - HDF_LOGD("%{public}s:%{public}d=========================OK", __func__, __LINE__); + HDF_LOGD("%s:%d=========================OK", __func__, __LINE__); return HDF_SUCCESS; @@ -1387,7 +1365,7 @@ err_open_device: static void UsbSerialRelease(struct AcmDevice *acm) { if (acm->initFlag == false) { - HDF_LOGE("%{public}s:%{public}d: initFlag is false", __func__, __LINE__); + HDF_LOGE("%s:%d: initFlag is false", __func__, __LINE__); return; } @@ -1416,7 +1394,7 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) int32_t ret; if (device == NULL) { - HDF_LOGE("%{public}s:%{public}d device is null", __func__, __LINE__); + HDF_LOGE("%s:%d device is null", __func__, __LINE__); return HDF_ERR_INVALID_OBJECT; } acm = (struct AcmDevice *)device->service; @@ -1425,13 +1403,13 @@ static int32_t UsbSerialDriverInit(struct HdfDeviceObject *device) ret = UsbSerialDeviceAlloc(acm); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s:%{public}d UsbSerialDeviceAlloc failed", __func__, __LINE__); + HDF_LOGE("%s:%d UsbSerialDeviceAlloc failed", __func__, __LINE__); } acm->initFlag = false; g_rawAcmReleaseFlag = false; - HDF_LOGD("%{public}s:%{public}d init ok!", __func__, __LINE__); + HDF_LOGD("%s:%d init ok!", __func__, __LINE__); return ret; } @@ -1440,20 +1418,20 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) { struct AcmDevice *acm = NULL; if (device == NULL) { - HDF_LOGE("%{public}s: device is NULL", __func__); + HDF_LOGE("%s: device is NULL", __func__); return; } acm = (struct AcmDevice *)device->service; if (acm == NULL) { - HDF_LOGE("%{public}s: acm is null", __func__); + HDF_LOGE("%s: acm is null", __func__); return; } g_rawAcmReleaseFlag = true; if (acm->initFlag == true) { - HDF_LOGE("%{public}s:%{public}d UsbSerialRelease", __func__, __LINE__); + HDF_LOGE("%s:%d UsbSerialRelease", __func__, __LINE__); UsbSerialRelease(acm); } UsbSeriaDevicelFree(acm); @@ -1462,12 +1440,12 @@ static void UsbSerialDriverRelease(struct HdfDeviceObject *device) OsalMutexDestroy(&acm->lock); OsalMemFree(acm); acm = NULL; - HDF_LOGD("%{public}s:%{public}d exit", __func__, __LINE__); + HDF_LOGD("%s:%d exit", __func__, __LINE__); } struct HdfDriverEntry g_usbSerialRawDriverEntry = { .moduleVersion = 1, - .moduleName = "usbhost_acm_rawapi", // Driver module name, which must be the same as that configured in the .hcs file. + ..moduleName = "usbhost_acm_rawapi", // Driver module name, which must be the same as that configured in the .hcs file. .Bind = UsbSerialDriverBind, .Init = UsbSerialDriverInit, .Release = UsbSerialDriverRelease, @@ -1475,8 +1453,9 @@ struct HdfDriverEntry g_usbSerialRawDriverEntry = { HDF_INIT(g_usbSerialRawDriverEntry); ``` -### Developing Driver Using Device DDK APIs -The core code of the USB Abstract Control Model (ACM) device is available in **drivers\peripheral\usb\gadget\function\acm\cdcacm.c**. The following is an example. +### Developing Driver Using Device DDK APIs + +The core code of the USB Abstract Control Model (ACM) device is available in **drivers/peripheral/usb/gadget/function/acm/cdcacm.c**. The following is an example: ``` 1. Create a device. @@ -1486,7 +1465,7 @@ static int32_t AcmCreateFuncDevice(struct UsbAcmDevice *acm, struct UsbFnDevice *fnDev = NULL; struct UsbFnDescriptorData descData; uint8_t useHcs; - ... + ... if (useHcs == 0) { descData.type = USBFN_DESC_DATA_TYPE_DESC; descData.descriptor = &g_masterFuncDevice; @@ -1497,7 +1476,7 @@ if (useHcs == 0) { /* Create a device. */ fnDev = (struct UsbFnDevice *)UsbFnDeviceCreate(acm->udcName, &descData); if (fnDev == NULL) { - HDF_LOGE("%{public}s: create usb function device failed", __func__); + HDF_LOGE("%s: create usb function device failed", __func__); return HDF_FAILURE; } ... @@ -1548,7 +1527,7 @@ static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type, uint16_t value, void *data, uint32_t length) { ... -/* Send a request asynchronously. */ +/* Send an asynchronous request.*/ ret = UsbFnRequestSubmitAsync(req); ... } @@ -1564,7 +1543,7 @@ int32_t ret; /* Remove the device. */ ret = UsbFnDeviceRemove(acm->fnDev); if (ret != HDF_SUCCESS) { - HDF_LOGE("%{public}s: remove usb function device failed", __func__); + HDF_LOGE("%s: remove usb function device failed", __func__); } return ret; } diff --git a/en/device-dev/driver/driver-peripherals.md b/en/device-dev/driver/driver-peripherals.md index aee10257e65791a1c04ddea0bfd4e998544fc387..4b65137ea60186915ec84487a46d73e125b2b95c 100644 --- a/en/device-dev/driver/driver-peripherals.md +++ b/en/device-dev/driver/driver-peripherals.md @@ -2,10 +2,12 @@ - **[LCD](driver-peripherals-lcd-des.md)** -- **[TOUCHSCREEN](driver-peripherals-touch-des.md)** +- **[Touchscreen](driver-peripherals-touch-des.md)** - **[Sensor](driver-peripherals-sensor-des.md)** - **[WLAN](driver-peripherals-external-des.md)** +- **[Audio](driver-peripherals-audio-des.md)** + diff --git a/en/device-dev/driver/driver-platform-gpio-develop.md b/en/device-dev/driver/driver-platform-gpio-develop.md index b2efad86b0e769de2ce4acad6b116c3a8563407b..1b31e3a4ff503ca1bcc4e84fc5eadf1bdc4d93bd 100644 --- a/en/device-dev/driver/driver-platform-gpio-develop.md +++ b/en/device-dev/driver/driver-platform-gpio-develop.md @@ -1,11 +1,10 @@ # GPIO - [Overview](#section1826197354103451) +- [Available APIs](#section752964871810) - [How to Develop](#section731175315103451) - - [GpioMethod](#section20369125172319) - - [Development Example](#section800425816103451) - - [\#section83834353114](#section83834353114) + ## Overview @@ -15,50 +14,25 @@ In the Hardware Driver Foundation \(HDF\) framework, the general-purpose input/o **Figure 1** Service-free mode ![](figures/service-free-mode.png "service-free-mode") -## How to Develop - -The GPIO controller manages all pins by group. The related parameters are described in the attribute file. Instantiating the driver entry and API functions is the core for the vendor driver to access the HDF. - -The GPIO module adaptation involves the following steps: - -1. Instantiate the driver entry. - - Instantiate the **HdfDriverEntry** structure. - - Call **HDF\_INIT** to register the **HdfDriverEntry** instance with the HDF framework. - -2. Configure attribute files. - - Add the **deviceNode** information to the **device\_info.hcs** file. - - \(Optional\) Add the **gpio\_config.hcs** file. - -3. Instantiate the GPIO controller object. - - Initialize **GpioCntlr**. - - Instantiate **GpioMethod** in the **GpioCntlr** object. - - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >For details, see [GpioMethod](#section20369125172319) and [Table 1](#table151341544111). - - -4. Debug the driver. - - \(Optional\) For new drivers, verify the basic functions, such as the GPIO control status and response to interrupts. +## Available APIs - -### GpioMethod +GpioMethod ``` struct GpioMethod { - int32_t (*request)(struct GpioCntlr *cntlr, uint16_t local);// (Optional) - int32_t (*release)(struct GpioCntlr *cntlr, uint16_t local);// (Optional) + int32_t (*request)(struct GpioCntlr *cntlr, uint16_t local);// Reserved + int32_t (*release)(struct GpioCntlr *cntlr, uint16_t local);// Reserved int32_t (*write)(struct GpioCntlr *cntlr, uint16_t local, uint16_t val); int32_t (*read)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *val); int32_t (*setDir)(struct GpioCntlr *cntlr, uint16_t local, uint16_t dir); int32_t (*getDir)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *dir); - int32_t (*toIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *irq);// (Optional) + int32_t (*toIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t *irq);// Reserved int32_t (*setIrq)(struct GpioCntlr *cntlr, uint16_t local, uint16_t mode, GpioIrqFunc func, void *arg); int32_t (*unsetIrq)(struct GpioCntlr *cntlr, uint16_t local); int32_t (*enableIrq)(struct GpioCntlr *cntlr, uint16_t local); int32_t (*disableIrq)(struct GpioCntlr *cntlr, uint16_t local); } ``` - **Table 1** Callbacks for the members in the GpioMethod structure @@ -178,6 +152,32 @@ struct GpioMethod {
+## How to Develop + +The GPIO controller manages all pins by group. The related parameters are described in the attribute file. Instantiating the driver entry and API functions is the core for the vendor driver to access the HDF. + +The GPIO module adaptation involves the following steps: + +1. Instantiate the driver entry. + - Instantiate the **HdfDriverEntry** structure. + - Call **HDF\_INIT** to register the **HdfDriverEntry** instance with the HDF framework. + +2. Configure attribute files. + - Add the **deviceNode** information to the **device\_info.hcs** file. + - \(Optional\) Add the **gpio\_config.hcs** file. + +3. Instantiate the GPIO controller object. + - Initialize **GpioCntlr**. + - Instantiate **GpioMethod** in the **GpioCntlr** object. + + >![](../public_sys-resources/icon-note.gif) **NOTE:** + >For details, see [Available APIs](#section752964871810). + + +4. Debug the driver. + - \(Optional\) For new drivers, verify the basic functions, such as the GPIO control status and response to interrupts. + + ## Development Example The following uses **gpio\_hi35xx.c** as an example to present the contents that need to be provided by the vendor to implement device functions. @@ -409,24 +409,27 @@ The following uses **gpio\_hi35xx.c** as an example to present the contents th Releases the memory and deletes the controller. This function assigns a value to the **Release** API in the driver entry structure. When the HDF framework fails to call the **Init** function to initialize the driver, the **Release** function can be called to release driver resources. All forced conversion operations for obtaining the corresponding object can be successful only when the **Init** function has the corresponding value assignment operations. - ``` - static void Pl061GpioRelease(struct HdfDeviceObject *device) - { - struct GpioCntlr *cntlr = NULL; - struct Pl061GpioCntlr *pl061 = NULL; - ... - cntlr = GpioCntlrFromDevice(device);// (Mandatory) Obtain the control object of the core layer through forced conversion. - //return (device == NULL) ? NULL : (struct GpioCntlr *)device->service; - ... - #ifdef PL061_GPIO_USER_SUPPORT - GpioRemoveVfs();// Perform operations reverse to GpioAddVfs in Init. - #endif - GpioCntlrRemove(cntlr); // (Mandatory) Remove the device information and services from the core layer. - pl061 = ToPl061GpioCntlr(cntlr); //return (struct Pl061GpioCntlr *)cntlr; - Pl061GpioRleaseCntlrMem(pl061); // (Mandatory) Release the lock and memory. - OsalIoUnmap((void *)pl061->regBase);// (Mandatory) Remove the address mapping. - pl061->regBase = NULL; - } - ``` + + ``` + static void Pl061GpioRelease(struct HdfDeviceObject *device) + { + struct GpioCntlr *cntlr = NULL; + struct Pl061GpioCntlr *pl061 = NULL; + ... + cntlr = GpioCntlrFromDevice(device);// (Mandatory) Obtain the control object of the core layer through forced conversion. + //return (device == NULL) ? NULL : (struct GpioCntlr *)device->service; + ... + #ifdef PL061_GPIO_USER_SUPPORT + GpioRemoveVfs();// Perform operations reverse to GpioAddVfs in Init. + #endif + GpioCntlrRemove(cntlr); // (Mandatory) Remove the device information and services from the core layer. + pl061 = ToPl061GpioCntlr(cntlr); //return (struct Pl061GpioCntlr *)cntlr; + Pl061GpioRleaseCntlrMem(pl061); // (Mandatory) Release the lock and memory. + OsalIoUnmap((void *)pl061->regBase);// (Mandatory) Remove the address mapping. + pl061->regBase = NULL; + } + ``` + + diff --git a/en/device-dev/driver/driver-platform-mipidsi-des.md b/en/device-dev/driver/driver-platform-mipidsi-des.md index faba7009a138b2d34bed9f52e4fbabc625c020a8..0bb5db5da12730afc9e4653ba00b64895dd4ec69 100644 --- a/en/device-dev/driver/driver-platform-mipidsi-des.md +++ b/en/device-dev/driver/driver-platform-mipidsi-des.md @@ -4,7 +4,7 @@ - [Available APIs](#section12720125432316) - [Usage Guidelines](#section037231715335) - [How to Use](#section49299119344) - - [Obtains a MIPI DSI device handle.](#section5126155683811) + - [Obtaining a MIPI DSI Device Handle](#section5126155683811) - [Setting MIPI DSI Configuration Parameters](#section201164274344) - [Sending/Receiving the Pointer to a Command](#section199401342173415) - [Releasing the MIPI DSI Device Handle](#section161011610357) @@ -96,9 +96,9 @@ [Figure 2](#fig129103491241) shows the process of using a MIPI DSI device. **Figure 2** Process of using a MIPI DSI device -![](figures/process-of-using-a-mipi-dsi-device.png "process-of-using-a-mipi-dsi-device") +![](figures/process-of-using-a-mipi-dsi-device.png) -### Obtains a MIPI DSI device handle. +### Obtaining a MIPI DSI Device Handle Before performing MIPI DSI communication, obtain a MIPI DSI device handle by calling **MipiDsiOpen**. This function returns a MIPI DSI device handle with a specified channel ID. @@ -213,7 +213,7 @@ cfg.timingInfo.vsaLines = 76; cfg.timingInfo.vfpLines = 120; cfg.timingInfo.xResPixels = 1342; /* Set MIPI DSI configuration parameters. */ -ret = MipiDsiSetCfg(g_handle, &cfg); +ret = MipiDsiSetCfg(mipiDsiHandle, &cfg); if (ret != 0) { HDF_LOGE("%s: SetMipiCfg fail! ret=%d\n", __func__, ret); return -1; @@ -265,7 +265,7 @@ int32\_t MipiDsiGetCfg\(DevHandle handle, struct MipiCfg \*cfg\); int32_t ret; struct MipiCfg cfg; memset(&cfg, 0, sizeof(struct MipiCfg)); -ret = MipiDsiGetCfg(g_handle, &cfg); +ret = MipiDsiGetCfg(mipiDsiHandle, &cfg); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: GetMipiCfg fail!\n", __func__); return HDF_FAILURE; @@ -409,9 +409,9 @@ if (cmdRead->payload == NULL) { return HDF_FAILURE; } *(cmdRead->payload) = DDIC_REG_STATUS; -MipiDsiSetLpMode(g_handle); -ret = MipiDsiRx(g_handle, cmdRead, sizeof(readVal), &readVal); -MipiDsiSetHsMode(g_handle); +MipiDsiSetLpMode(mipiDsiHandle); +ret = MipiDsiRx(mipiDsiHandle, cmdRead, sizeof(readVal), &readVal); +MipiDsiSetHsMode(mipiDsiHandle); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: MipiDsiRx fail! ret=%d\n", __func__, ret); HdfFree(cmdRead->payload); @@ -463,13 +463,13 @@ void PalMipiDsiTestSample(void) { uint8_t chnId; int32_t ret; - DevHandle handle = NULL; + DevHandle mipiDsiHandle = NULL; /* Device channel ID */ chnId = 0; /* Obtain the MIPI DSI device handle based on a specified channel ID. */ - handle = MipiDsiOpen(chnId); - if (handle == NULL) { + mipiDsiHandle = MipiDsiOpen(chnId); + if (mipiDsiHandle == NULL) { HDF_LOGE("MipiDsiOpen: failed!\n"); return; } @@ -490,7 +490,7 @@ void PalMipiDsiTestSample(void) cfg.timingInfo.vfpLines = 120; cfg.timingInfo.xResPixels = 1342; /* Set MIPI DSI configuration parameters. */ - ret = MipiDsiSetCfg(g_handle, &cfg); + ret = MipiDsiSetCfg(mipiDsiHandle, &cfg); if (ret != 0) { HDF_LOGE("%s: SetMipiCfg fail! ret=%d\n", __func__, ret); return; @@ -533,9 +533,9 @@ void PalMipiDsiTestSample(void) return; } *(cmdRead->payload) = DDIC_REG_STATUS; - MipiDsiSetLpMode(g_handle); - ret = MipiDsiRx(g_handle, cmdRead, sizeof(readVal), &readVal); - MipiDsiSetHsMode(g_handle); + MipiDsiSetLpMode(mipiDsiHandle); + ret = MipiDsiRx(mipiDsiHandle, cmdRead, sizeof(readVal), &readVal); + MipiDsiSetHsMode(mipiDsiHandle); if (ret != HDF_SUCCESS) { HDF_LOGE("%s: MipiDsiRx fail! ret=%d\n", __func__, ret); HdfFree(cmdRead->payload); diff --git a/en/device-dev/driver/driver-platform-mipidsi-develop.md b/en/device-dev/driver/driver-platform-mipidsi-develop.md index 2677bd2c7040ca07c5356d8448d4fdbb2e2e20b3..38461bae03cc51ab53fdef786f03d63879c179dd 100644 --- a/en/device-dev/driver/driver-platform-mipidsi-develop.md +++ b/en/device-dev/driver/driver-platform-mipidsi-develop.md @@ -1,4 +1,4 @@ -# MIPI-DSI +# MIPI DSI - [Overview](#section1266787503161538) - [How to Develop](#section545182932161538) @@ -8,14 +8,14 @@ ## Overview -The Display Serial Interface \(DSI\) is a specification developed by the Mobile Industry Processor Interface \(MIPI\) Alliance to reduce the cost of display controllers in mobile devices. In the Hardware Driver Foundation (HDF) framework, the MIPI-DSI module uses the service-free mode for API adaptation. The service-free mode applies to the devices that do not provide user-mode APIs or the OS system that does not distinguish the user mode and the kernel mode. In the service-free mode, **DevHandle** \(a void pointer\) directly points to the kernel-mode address of the device object. +The Display Serial Interface \(DSI\) is a specification developed by the Mobile Industry Processor Interface \(MIPI\) Alliance to reduce the cost of display controllers in mobile devices. In the Hardware Driver Foundation (HDF) framework, the MIPI DSI module uses the service-free mode for API adaptation. The service-free mode applies to the devices that do not provide user-mode APIs or the OS system that does not distinguish the user mode and the kernel mode. In the service-free mode, **DevHandle** \(a void pointer\) directly points to the kernel-mode address of the device object. **Figure 1** Service-free mode -![](figures/service-free-mode-9.png "service-free-mode-9") +![](figures/service-free-mode.png "service-free-mode") ## How to Develop -The MIPI-DSI module adaptation involves the following steps: +The MIPI DSI module adaptation involves the following steps: 1. Instantiate the driver entry. - Instantiate the **HdfDriverEntry** structure. @@ -25,7 +25,7 @@ The MIPI-DSI module adaptation involves the following steps: - Add the **deviceNode** information to the **device\_info.hcs** file. - \(Optional\) Add the **mipidsi\_config.hcs** file. -3. Instantiate the MIPI-DSI controller object. +3. Instantiate the MIPI DSI controller object. - Initialize **MipiDsiCntlr**. - Instantiate **MipiDsiCntlrMethod** in the **MipiDsiCntlr** object. @@ -70,7 +70,7 @@ struct MipiDsiCntlrMethod {// Member functions of the core layer structure

setCntlrCfg

cntlr: structure pointer to the MIPI-DSI controller.

+

cntlr: structure pointer to the MIPI DSI controller.

setCmd

cntlr: structure pointer to the MIPI-DSI controller.

+

cntlr: structure pointer to the MIPI DSI controller.

cmd: structure pointer to the input instruction.

@@ -93,7 +93,7 @@ struct MipiDsiCntlrMethod {// Member functions of the core layer structure

getCmd

cntlr: structure pointer to the MIPI-DSI controller.

+

cntlr: structure pointer to the MIPI DSI controller.

cmd: structure pointer to the instruction to output.

toHs

cntlr: structure pointer to the MIPI-DSI controller.

+

cntlr: structure pointer to the MIPI DSI controller.

toLp

cntlr: structure pointer to the MIPI-DSI controller.

+

cntlr: structure pointer to the MIPI DSI controller.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Capability

-

Function

-

Description

-

Obtaining/Releasing device handles

-

PwmOpen

-

Obtains a PWM device handle.

-

PwmClose

-

Releases a PWM device handle.

-

Setting the PWM period, duty cycle, and polarity

-

PwmSetPeriod

-

Sets the PWM period.

-

PwmSetDuty

-

Sets the PWM duty cycle.

-

PwmSetPolarity

-

Sets the PWM polarity.

-

Enabling/Disabling devices

-

PwmEnable

-

Enables a PWM device.

-

PwmDisable

-

Disables a PWM device.

-

Obtaining/Setting configuration parameters

-

-

PwmSetConfig

-

Sets PWM device configuration parameters.

-

PwmGetConfig

-

Obtains PWM device configuration parameters.

-
- ->![](../public_sys-resources/icon-note.gif) **NOTE:** ->All functions described in this document can be called only in kernel space. - -## Usage Guidelines - -### How to Use - -[Figure 1](#fig23885455594) shows the process of using a PWM device. - -**Figure 1** Process of using a PWM device - - -![](figures/en-us_image_0000001206372673.png) - -### Obtaining a PWM Device Handle - -Before performing operations on a PWM device, obtain a PWM device handle by calling **PwmOpen**. This function returns a PWM device handle with the specified device number. - -DevHandle PwmOpen\(uint32\_t num\); - -**Table 2** Description of PwmOpen - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

num

-

PWM device number.

-

Return Value

-

Description

-

NULL

-

Failed to obtain the PWM device handle.

-

Device handle

-

PWM device handle.

-
- -The following example shows how to obtain a PWM device handle with the device number **0**: - +# PWM + +- [Overview](#section1_PWM_des) + - [PwmConfig Structure](#section1.1_PWM_des) +- [Available APIs](#section2_PWM_des) +- [Usage Guidelines](#section3_PWM_des) + - [How to Use](#section3.1_PWM_des) + - [Opening a PWM Device Handle](#section3.2_PWM_des) + - [Closing a PWM Device Handle](#section3.3_PWM_des) + - [Enabling a PWM Device](#section3.4_PWM_des) + - [Disabling a PWM Device](#section3.5_PWM_des) + - [Setting the PWM Period](#section3.6_PWM_des) + - [Setting the PWM Signal ON-State Time](#section3.7_PWM_des) + - [Setting the PWM Polarity](#section3.8_PWM_des) + - [Setting PWM Device Parameters](#section3.9_PWM_des) + - [Obtaining PWM Device Parameters](#section3.10_PWM_des) + +- [Usage Example](#section3_PWM_des) + +## Overview + +Pulse width modulation (PWM) is a method used to digitally encode analog signal levels and convert them into pulses. It can be used for motor control and backlight brightness adjustment. + +The PWM APIs provide a set of functions for operating a PWM device, including those for: +- Obtaining and releasing a PWM device handle +- Setting the PWM period, signal ON-state time, and polarity +- Enabling and disabling a PWM device +- Obtaining and setting PWM parameters + +### PwmConfig Structure + +**Table 1** PwmConfig structure + + + +| Parameter| Description| +| -------- | ------------------------------------------------------------ | +| duty | Time that a signal is in the ON state, in ns.| +| period | Time for a signal to complete an on-and-off cycle, in ns.| +| number | Number of square waves to generate. A positive value indicates the number of square waves to generate. The value 0 means to generate square waves repeatedly.| +| polarity | PWM signal polarity, which can be **PWM\_NORMAL\_POLARITY** or **PWM\_INVERTED\_POLARITY**.| +| status | PWM device status, which can be enabled or disabled.| + +## Available APIs + +**Table 2** PWM device APIs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
CategoryAPIDescription
Operating PWM handlesPwmOpenOpens the handle of a PWM device.
PwmCloseCloses the handle of a PWM device.
Enabling or disabling PWMPwmEnableEnables a PWM device.
PwmDisableDisables a PWM device.
Performing PWM configurationPwmSetPeriodSets the PWM period.
PwmSetDutySets the signal ON-state time.
PwmSetPolaritySets the PWM signal polarity.
Setting or obtaining the PWM configurationPwmSetConfigSets PWM device parameters.
PwmGetConfigObtains PWM device parameters.
+ + + +>![](W:\doc\docs\en\device-dev\public_sys-resources\icon-note.gif) **NOTE:** +>The PWM module can be used in kernel mode but not in user mode. + +## Usage Guidelines + +### How to Use + +During the OS startup process, the driver management module loads the PWM driver based on the configuration file. Then, the PWM driver detects the PWM device and initializes the driver. + +[Figure 1](#fig1_PWM_des) shows the general process of using the PWM module. + +**Figure 1** Process of using the PWM module + + +![](figures/process-of-using-PWM.png) + +### Opening a PWM Device Handle + +Before performing operations on a PWM device, call **PwmOpen** to open the device handle. + +```c +DevHandle PwmOpen(uint32_t num); ``` -uint32_t num = 0; /* PWM device number */ -DevHandle pwm = NULL; /* PWM device handle */ + +**Table 3** PwmOpen + + + +| Parameter| Description| +| ---------- | ----------------------- | +| num | PWM device number.| +| **Return Value** | **Description**| +| handle | Handle of the PWM device obtained.| +| NULL | The operation fails.| + + +```c +uint32_t num = 0; /* PWM device number. */ +DevHandle handle = NULL; /* Obtain the PWM device handle. */ -pwm = PwmOpen(num); -if (pwm == NULL) { - HDF_LOGE("PwmOpen: pwm%d failed", num); - return; +handle = PwmOpen(num); +if (handle == NULL) { + /* Error handling. */ } ``` -### Setting the PWM Period - -int32\_t PwmSetPeriod\(DevHandle handle, uint32\_t period\); - -**Table 3** Description of PwmSetPeriod - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

handle

-

PWM device handle.

-

period

-

Period, in nanoseconds.

-

Return Value

-

Description

-

0

-

Succeeded in setting the PWM period.

-

Negative value

-

Failed to set the period.

-
+### Closing a PWM Device Handle + +Close a PWM device to release resources. +```c +void PwmClose(DevHandle handle); ``` -int32_t ret; -uint32_t period = 1000; /* Period: 1000 ns */ -ret = PwmSetPeriod(pwm, period); /* Set the PWM period. */ -if (ret != 0) { - HDF_LOGE("PwmSetPeriod: failed, ret %d", ret); -} + +**Table 4** PwmClose + + + +| Parameter| Description| +| ------ | ----------- | +| handle | PWM device handle to close.| + + +```c +/* Close a PWM device handle. */ +PwmClose(handle); ``` -### Setting the PWM Duty Cycle - -int32\_t PwmSetDuty\(DevHandle handle, uint32\_t duty\); - -**Table 4** Description of PwmSetDuty - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

handle

-

PWM device handle.

-

duty

-

Duty cycle, in nanoseconds.

-

Return Value

-

Description

-

0

-

Succeeded in setting the duty cycle.

-

Negative value

-

Failed to set the duty cycle.

-
+### Enabling a PWM Device +Enable a PWM device. + +```c +int32_t PwmEnable(DevHandle handle); ``` + +**Table 5** PwmEnable + + + +| Parameter| Description| +| ---------- | -------------- | +| handle | PWM device handle.| +| **Return Value** | **Description** | +| 0 | The operation is successful.| +| Negative number| The operation fails.| + +```c int32_t ret; -uint32_t duty = 500; /* Duty cycle: 500 ns */ -ret = PwmSetDuty(pwm, duty); /* Set the PWM duty cycle. */ + +/* Enable a PWM device. */ +ret = PwmEnable(handle); if (ret != 0) { - HDF_LOGE("PwmSetDuty: failed, ret %d", ret); + /* Error handling. */ } ``` -### Setting the PWM Polarity - -int32\_t PwmSetPolarity\(DevHandle handle, uint8\_t polarity\); - -**Table 5** Description of PwmSetPolarity - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

handle

-

PWM device handle.

-

polarity

-

Polarity, which can be PWM_NORMAL_POLARITY or PWM_INVERTED_POLARITY.

-

Return Value

-

Description

-

0

-

Succeed in setting the polarity.

-

Negative value

-

Failed to set the polarity.

-
+### Disabling a PWM Device + +Disable a PWM device. +```c +int32_t PwmDisable(DevHandle handle); ``` + +**Table 6** PwmDisable + + + +| Parameter| Description| +| ---------- | -------------- | +| handle | PWM device handle.| +| **Return Value** | **Description** | +| 0 | The operation is successful.| +| Negative number| The operation fails.| + +```c int32_t ret; -uint8_t polarity = PWM_INVERTED_POLARITY; /* Inverted polarity */ -ret = PwmSetPolarity(pwm, polarity); /* Set PWM polarity to inverted polarity. */ + +/* Disable a PWM device. */ +ret = PwmDisable(handle); if (ret != 0) { - HDF_LOGE("PwmSetPolarity: failed, ret %d", ret); + /* Error handling. */ } ``` -### Enabling the PWM Device - -int32\_t PwmEnable\(DevHandle handle\); - -**Table 6** Description of PwmEnable - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

handle

-

PWM device handle.

-

Return Value

-

Description

-

0

-

Succeeded in enabling the PWM device.

-

Negative value

-

Failed to enable the PWM device.

-
+### Setting the PWM Period + +Set the PWM period. +```c +int32_t PwmSetPeriod(DevHandle handle, uint32_t period); ``` + +**Table 7** PwmSetPeriod + + + +| Parameter| Description| +| ---------- | ------------------------ | +| handle | PWM device handle.| +| period | PWM period to set, in ns.| +| **Return Value**| **Description**| +| 0 | The operation is successful.| +| Negative number| The operation fails.| + +```c int32_t ret; -ret = PwmEnable(pwm); /* Enable the PWM device. */ + +/* Set the PWM period to 50000000 ns.*/ +ret = PwmSetPeriod(handle, 50000000); if (ret != 0) { - HDF_LOGE("PwmEnable: failed, ret %d", ret); + /* Error handling. */ } ``` +### Setting the PWM Signal ON-State Time -### Disabling the PWM Device - -int32\_t PwmDisable\(DevHandle handle\); - -**Table 7** Description of PwmDisable - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

handle

-

PWM device handle.

-

Return Value

-

Description

-

0

-

Succeeded in disabling the PWM device.

-

Negative value

-

Failed to disable the PWM device.

-
+Set the time that the PWM signal is in the ON state. +```c +int32_t PwmSetDuty(DevHandle handle, uint32_t duty); ``` + +**Table 8** PwmSetDuty + + + +| Parameter| Description| +| ---------- | ---------------------------- | +| handle | PWM device handle.| +| duty | Time that the signal is in the ON state, in ns.| +| **Return Value**| **Description**| +| 0 | The operation is successful.| +| Negative number| The operation fails.| + +```c int32_t ret; -ret = PwmDisable(pwm); /* Disable the PWM device. */ + +/* Set the signal ON-state time to 25000000 ns. */ +ret = PwmSetDuty(handle, 25000000); if (ret != 0) { - HDF_LOGE("PwmDisable: failed, ret %d", ret); + /* Error handling. */ } ``` +### Setting the PWM Polarity -### Obtaining PWM Device Configuration Parameters - -int32\_t PwmGetConfig\(DevHandle handle, struct PwmConfig \*config\); - -**Table 8** Description of PwmGetConfig - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

handle

-

PWM device handle.

-

config

-

Pointer to the PwmConfig structure containing PWM device configuration parameters.

-

Return Value

-

Description

-

0

-

Succeeded in obtaining PWM device configuration parameters.

-

Negative value

-

Failed to obtain PWM device configuration parameters.

-
+Set the signal polarity for a PWM device. +```c +int32_t PwmSetPolarity(DevHandle handle, uint8_t polarity); ``` + +**Table 9** PwmSetPolarity + + + +| Parameter| Description| +| ---------- | ------------------- | +| handle | PWM device handle.| +| polarity | Polarity to set, which can be **PWM\_NORMAL\_POLARITY** or **PWM\_INVERTED\_POLARITY**.| +| **Return Value**| **Description**| +| 0 | The operation is successful.| +| Negative number| The operation fails.| + +```c int32_t ret; -struct PwmConfig config= {0}; /* PWM configuration parameters */ -ret = PwmGetConfig(pwm, &config); /* Obtain PWM device configuration parameters. */ + +/* Set the PWM polarity to PWM_INVERTED_POLARITY. */ +ret = PwmSetPolarity(handle, PWM_INVERTED_POLARITY); if (ret != 0) { - HDF_LOGE("PwmGetConfig: failed, ret %d", ret); + /* Error handling. */ } ``` -### Setting PWM Device Configuration Parameters - -int32\_t PwmSetConfig\(DevHandle handle, struct PwmConfig \*config\); - -**Table 9** Description of PwmSetConfig - - - - - - - - - - - - - - - - - - - - - -

Parameter

-

Description

-

handle

-

PWM device handle.

-

config

-

Pointer to the PwmConfig structure containing PWM device configuration parameters.

-

Return Value

-

Description

-

0

-

Succeeded in setting PWM configuration parameters.

-

Negative value

-

Failed to set PWM configuration parameters.

-
+### Setting PWM Device Parameters + +Set PWM device parameters. + +```c +int32_t PwmSetConfig(DevHandle handle, struct PwmConfig *config); ``` + +**Table 10** PwmSetConfig + + + +| Parameter| Description| +| ---------- | -------------- | +| handle | PWM device handle.| +| *config | Pointer to PWM parameters.| +| **Return Value**| **Description**| +| 0 | The operation is successful.| +| Negative number| The operation fails.| + +```c int32_t ret; -struct PwmConfig config= {0}; /* PWM configuration parameters */ -config.duty = 500; /* Duty cycle: 500 ns */ -config.period = 1000; /* Period: 1000 ns */ -config.number = 0; /* Continuous output of square waves */ -config.polarity = PWM_NORMAL_POLARITY; /* Normal polarity */ -ret = PwmSetConfig(pwm, &config); /* Set PWM device configuration parameters. */ +struct PwmConfig pcfg; +pcfg.duty = 25000000; /* Set the signal ON-state time to 25000000 ns. */ +pcfg.period = 50000000; /* Set the PWM period to 50000000 ns. */ +pcfg.number = 0; /* Generate square waves repeatedly. */ +pcfg.polarity = PWM_INVERTED_POLARITY; /* Set the PWM polarity to PWM_INVERTED_POLARITY. */ +pcfg.status = PWM_ENABLE_STATUS; /* Set the running status to Enabled. */ + +/* Set PWM device parameters. */ +ret = PwmSetConfig(handle, &pcfg); if (ret != 0) { - HDF_LOGE("PwmSetConfig: failed, ret %d\n", ret); + /* Error handling. */ } ``` -### Releasing the PWM Device Handle +### Obtaining PWM Device Parameters -void PwmClose\(DevHandle handle\); +Obtain PWM device parameters. -This function will release the resources obtained by calling **PwmClose**. +```c +int32_t PwmGetConfig(DevHandle handle, struct PwmConfig *config); +``` -**Table 10** Description of PwmClose +**Table 11** PwmGetConfig - - - - - - - - -

Parameter

-

Description

-

handle

-

PWM device handle.

-
+ -``` -PwmClose(pwm); /* Release the PWM device handle */ +| Parameter| Description| +| ---------- | -------------- | +| handle | PWM device handle.| +| *config | Pointer to PWM parameters.| +| **Return Value**| **Description**| +| 0 | The operation is successful.| +| Negative number| The operation fails.| + +```c +int32_t ret; +struct PwmConfig pcfg; + +/* Obtain PWM device parameters. */ +ret = PwmGetConfig(handle, &pcfg); +if (ret != 0) { + /* Error handling. */ +} ``` -## Usage Example +## Usage Example -The following example shows how to obtain a PWM device handle, set the PWM configuration parameters, enable the PWM device, and finally release the PWM device handle. +The following example shows how to use the APIs to implement a PWM driver and manage the PWM device. ``` -#include "hdf_log.h" -#include "osal_time.h" -#include "pwm_if.h" - void PwmTestSample(void) { int32_t ret; - struct PwmConfig config; /* PWM configuration parameters */ - DevHandle pwm = NULL; /* PWM device handle */ - - pwm = PwmOpen(0); /* Obtain the PWM device handle. */ - if (pwm == NULL) { - HDF_LOGE("PwmOpen: pwm0 failed"); + uint32_t num; + DevHandle handle = NULL; + + struct PwmConfig pcfg; + pcfg.duty = 20000000; /* Set the signal ON-state time to 20000000 ns. */ + pcfg.period = 40000000; /* Set the PWM period to 40000000 ns. */ + pcfg.number = 100; /* Generate 100 square waves. */ + pcfg.polarity = PWM_NORMAL_POLARITY; /* Set the polarity to PWM_NORMAL_POLARITY. */ + pcfg.status = PWM_ENABLE_STATUS; /* Set the running status to Enabled. */ + + /* Enter the PWM device number. */ + num = 1; + + /* Open the PWM device handle. */ + handle = PwmOpen(num); + if (handle == NULL) { + HDF_LOGE("PwmOpen: failed!\n"); return; } - /* Obtain the PWM device configuration parameters. */ - ret = PwmGetConfig(pwm, &config); + + /* Set the PWM period to 50000000 ns.*/ + ret = PwmSetPeriod(handle, 50000000); if (ret != 0) { - HDF_LOGE("PwmGetConfig: failed, ret %d\n", ret); - goto err; + HDF_LOGE("PwmSetPeriod: failed, ret %d\n", ret); + goto _ERR; } - config.duty = 500; /* Duty cycle: 500 ns */ - config.period = 1000; /* Period: 1000 ns */ - /* Set the PWM device configuration parameters. */ - ret = PwmSetConfig(pwm, &config); + + /* Set the signal ON-state time to 25000000 ns. */ + ret = PwmSetDuty(handle, 25000000); if (ret != 0) { - HDF_LOGE("PwmSetConfig: failed, ret %d\n", ret); - goto err; + HDF_LOGE("PwmSetDuty: failed, ret %d\n", ret); + goto _ERR; + } + + /* Set the PWM polarity to PWM_INVERTED_POLARITY. */ + ret = PwmSetPolarity(handle, PWM_INVERTED_POLARITY); + if (ret != 0) { + HDF_LOGE("PwmSetPolarity: failed, ret %d\n", ret); + goto _ERR; } + + /* Obtain PWM device parameters. */ + ret = PwmGetConfig(handle, &pcfg); + if (ret != 0) { + HDF_LOGE("PwmGetConfig: failed, ret %d\n", ret); + goto _ERR; + } + /* Enable the PWM device. */ - ret = PwmEnable(pwm); + ret = PwmEnable(handle); if (ret != 0) { - HDF_LOGE("PwmEnable: failed, ret %d\n", ret); - goto err; + HDF_LOGE("PwmEnable: failed, ret %d\n", ret); + goto _ERR; } - /* Sleep for 10 seconds */ - OsalSleep(10); + + /* Set PWM device parameters. */ + ret = PwmSetConfig(handle, &pcfg); + if (ret != 0) { + HDF_LOGE("PwmSetConfig: failed, ret %d\n", ret); + goto _ERR; + } + /* Disable the PWM device. */ - ret = PwmDisable(pwm); + ret = PwmDisable(handle); if (ret != 0) { HDF_LOGE("PwmDisable: failed, ret %d\n", ret); - goto err; + goto _ERR; } -err: - /* Release the PWM device handle. */ - PwmClose(pwm); + +_ERR: + /* Close the PWM device handle. */ + PwmClose(handle); } ``` - diff --git a/en/device-dev/driver/driver-platform-spi-develop.md b/en/device-dev/driver/driver-platform-spi-develop.md index b970a9598d78a0be8f3f78b1dab32266a5e777ae..b09cf5f47158fcd3855da7a92993914030256049 100644 --- a/en/device-dev/driver/driver-platform-spi-develop.md +++ b/en/device-dev/driver/driver-platform-spi-develop.md @@ -1,43 +1,21 @@ # SPI - [Overview](#section84922229152909) +- [Available APIs](#section752964871810) - [How to Develop](#section799667984152909) - - [SpiCntlrMethod](#section715682993110) - - [Development Example](#section956157227152909) + ## Overview In the Hardware Driver Foundation \(HDF\) framework, the Serial Peripheral Interface \(SPI\) uses the independent service mode for API adaptation. In this mode, each device independently publishes a device service to handle external access requests. After receiving an access request from an API, the device manager extracts the parameters in the request to call the internal method of the target device. In the independent service mode, the service management capabilities of the HDFDeviceManager can be directly used. However, you need to configure a device node for each device, which increases the memory usage. **Figure 1** Independent service mode -![](figures/independent-service-mode-13.png "independent-service-mode-13") - -## How to Develop - -The SPI module adaptation involves the following steps: - -1. Instantiate the driver entry. - - Instantiate the **HdfDriverEntry** structure. - - Call **HDF\_INIT** to register the **HdfDriverEntry** instance with the HDF framework. - -2. Configure attribute files. - - Add the **deviceNode** information to the **device\_info.hcs** file. - - \(Optional\) Add the **spi\_config.hcs** file. - -3. Instantiate the SPI controller object. - - Initialize **SpiCntlr**. - - Instantiate **SpiCntlrMethod** in the **SpiCntlr** object. - - >![](../public_sys-resources/icon-note.gif) **NOTE:** - >For details, see [SpiCntlrMethod](#section715682993110) and [Table 1](#table7167123615321). - - -4. Debug the driver. - - \(Optional\) For new drivers, verify the basic functions, such as the SPI control status and response to interrupts. +![](figures/independent-service-mode.png "SPI-independent-service-mode") +## Available APIs -### SpiCntlrMethod +SpiCntlrMethod: ``` struct SpiCntlrMethod { @@ -48,7 +26,6 @@ struct SpiCntlrMethod { int32_t (*Close)(struct SpiCntlr *cntlr); }; ``` - **Table 1** Callbacks for the members in the SpiCntlrMethod structure @@ -114,6 +91,29 @@ struct SpiCntlrMethod {
+## How to Develop + +The SPI module adaptation involves the following steps: + +1. Instantiate the driver entry. + - Instantiate the **HdfDriverEntry** structure. + - Call **HDF\_INIT** to register the **HdfDriverEntry** instance with the HDF framework. + +2. Configure attribute files. + - Add the **deviceNode** information to the **device\_info.hcs** file. + - \(Optional\) Add the **spi\_config.hcs** file. + +3. Instantiate the SPI controller object. + - Initialize **SpiCntlr**. + - Instantiate **SpiCntlrMethod** in the **SpiCntlr** object. + + >![](../public_sys-resources/icon-note.gif) **NOTE:** + >For details, see [Available APIs](#section752964871810). + +4. Debug the driver. + - \(Optional\) For new drivers, verify the basic functions, such as the SPI control status and response to interrupts. + + ## Development Example The following uses **spi\_hi35xx.c** as an example to present the contents that need to be provided by the vendor to implement device functions. @@ -222,7 +222,7 @@ The following uses **spi\_hi35xx.c** as an example to present the contents tha } ``` -3. Initialize the **SpiCntlr** object at the core layer, including initializing the vendor custom structure \(transferring parameters and data\), instantiating **SpiCntlrMethod** \(used to call underlying functions of the driver\) in **SpiCntlr**, and implementing the **HdfDriverEntry** member functions \(**Bind**, **Init**, and **Release**\). +3. Initialize the **SpiCntlr** object at the core layer, including initializing the vendor custom structure \(transferring parameters and data\), instantiating **SpiCntlrMethod** \(used to call underlying functions of the driver\) in **SpiCntlr**, and implementing the **HdfDriverEntry** member functions \(**Bind**, **Init**, and **Release**\). - Custom structure reference To the driver, the custom structure carries parameters and data. The values in the **spi\_config.hcs** file are read by HDF, and the structure members are initialized through **DeviceResourceIface**. Some important values, such as the device number and bus number, are also passed to the object at the core layer. @@ -325,7 +325,7 @@ The following uses **spi\_hi35xx.c** as an example to present the contents tha Return values: - HDF\_STATUS \(The following table lists some status. For details about other status, see **HDF\_STATUS** in the **//drivers/framework/include/utils/hdf\_base.h** file.\) + HDF\_STATUS \(The following table lists some status. For details about other status, see **HDF\_STATUS** in the **/drivers/framework/include/utils/hdf\_base.h** file.\) **Table 2** Input parameters and return values of the init function @@ -404,20 +404,20 @@ The following uses **spi\_hi35xx.c** as an example to present the contents tha pl022->maxSpeedHz = (pl022->clkRate) / ((SCR_MIN + 1) * CPSDVSR_MIN); pl022->minSpeedHz = (pl022->clkRate) / ((SCR_MAX + 1) * CPSDVSR_MAX); DListHeadInit(&pl022->deviceList);// Initialize the DList linked list. - pl022->cntlr = cntlr; // Enable conversion between Pl022 and SpiCntlr. - cntlr->priv = pl022; // Enable conversion between Pl022 and SpiCntlr. - cntlr->busNum = pl022->busNum; // Assign a value to busNum in SpiCntlr. - cntlr->method = &g_method; // Connect to the SpiCntlrMethod instance. + pl022->cntlr = cntlr; // Enable conversion between Pl022 and SpiCntlr. + cntlr->priv = pl022; // Enable conversion between Pl022 and SpiCntlr. + cntlr->busNum = pl022->busNum; // Assign a value to busNum in SpiCntlr. + cntlr->method = &g_method; // Connect to the SpiCntlrMethod instance. ... ret = Pl022CreatAndInitDevice(pl022); if (ret != 0) { - Pl022Release(pl022); // Release the Pl022 object if the initialization fails. + Pl022Release(pl022); // Release the Pl022 object if the initialization fails. return ret; } return 0; } ``` - + - Release function Input parameters: @@ -441,11 +441,12 @@ The following uses **spi\_hi35xx.c** as an example to present the contents tha // return (device==NULL) ?NULL:(struct SpiCntlr *)device->service; ... if (cntlr->priv != NULL) { - Pl022Remove((struct Pl022 *)cntlr->priv);// A forced conversion from SpiCntlr to Pl022 is involved. + Pl022Remove((struct Pl022 *)cntlr->priv);// A forced conversion from SpiCntlr to Pl022 is involved. } - SpiCntlrDestroy(cntlr); // Release the Pl022 object. + SpiCntlrDestroy(cntlr); // Release the Pl022 object. } ``` + diff --git a/en/device-dev/driver/figures/ADM_control_flowchart.png b/en/device-dev/driver/figures/ADM_control_flowchart.png new file mode 100644 index 0000000000000000000000000000000000000000..5f0b075983cb6cea46c33e15c9abbeeb0ea7bdd0 Binary files /dev/null and b/en/device-dev/driver/figures/ADM_control_flowchart.png differ diff --git a/en/device-dev/driver/figures/ADM_playback_flowchart.png b/en/device-dev/driver/figures/ADM_playback_flowchart.png new file mode 100644 index 0000000000000000000000000000000000000000..ceed4237ad2033c06db504165a3f5fd75fbd46c2 Binary files /dev/null and b/en/device-dev/driver/figures/ADM_playback_flowchart.png differ diff --git a/en/device-dev/driver/figures/ADM_startup_flowchart.png b/en/device-dev/driver/figures/ADM_startup_flowchart.png new file mode 100644 index 0000000000000000000000000000000000000000..db07e421198faf154f30682c63e2b7b361ae3cf6 Binary files /dev/null and b/en/device-dev/driver/figures/ADM_startup_flowchart.png differ diff --git a/en/device-dev/driver/figures/Audio_architecture.png b/en/device-dev/driver/figures/Audio_architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..19c24f59eed43828f00f4bbff012b0e087fb927a Binary files /dev/null and b/en/device-dev/driver/figures/Audio_architecture.png differ diff --git a/en/device-dev/driver/figures/CSI_TX-RX_interface.png b/en/device-dev/driver/figures/CSI_TX-RX_interface.png new file mode 100644 index 0000000000000000000000000000000000000000..dd7ba3d83aa7ba505b4907e61f4712c413851e2d Binary files /dev/null and b/en/device-dev/driver/figures/CSI_TX-RX_interface.png differ diff --git a/en/device-dev/driver/figures/HAL_flowchart.png b/en/device-dev/driver/figures/HAL_flowchart.png new file mode 100644 index 0000000000000000000000000000000000000000..f477dbceaf5c76b29d3c40f3912e00dbdb617e86 Binary files /dev/null and b/en/device-dev/driver/figures/HAL_flowchart.png differ diff --git a/en/device-dev/driver/figures/development_flowchart_1.png b/en/device-dev/driver/figures/development_flowchart_1.png new file mode 100644 index 0000000000000000000000000000000000000000..16c6571b586b28f19ca8db4626c65fb3fcb65c1a Binary files /dev/null and b/en/device-dev/driver/figures/development_flowchart_1.png differ diff --git a/en/device-dev/driver/figures/development_flowchart_2.png b/en/device-dev/driver/figures/development_flowchart_2.png new file mode 100644 index 0000000000000000000000000000000000000000..bd820389e4e5f5e8ee39e3d5208513c20a64d494 Binary files /dev/null and b/en/device-dev/driver/figures/development_flowchart_2.png differ diff --git a/en/device-dev/driver/figures/independent-service-mode-10.png b/en/device-dev/driver/figures/independent-service-mode-10.png deleted file mode 100644 index c1457af7a0512dbd08436c3dd9d24654c200b85a..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/independent-service-mode-10.png and /dev/null differ diff --git a/en/device-dev/driver/figures/independent-service-mode-11.png b/en/device-dev/driver/figures/independent-service-mode-11.png deleted file mode 100644 index c1457af7a0512dbd08436c3dd9d24654c200b85a..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/independent-service-mode-11.png and /dev/null differ diff --git a/en/device-dev/driver/figures/independent-service-mode-12.png b/en/device-dev/driver/figures/independent-service-mode-12.png deleted file mode 100644 index c1457af7a0512dbd08436c3dd9d24654c200b85a..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/independent-service-mode-12.png and /dev/null differ diff --git a/en/device-dev/driver/figures/independent-service-mode-13.png b/en/device-dev/driver/figures/independent-service-mode-13.png deleted file mode 100644 index c1457af7a0512dbd08436c3dd9d24654c200b85a..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/independent-service-mode-13.png and /dev/null differ diff --git a/en/device-dev/driver/figures/independent-service-mode-14.png b/en/device-dev/driver/figures/independent-service-mode-14.png deleted file mode 100644 index c1457af7a0512dbd08436c3dd9d24654c200b85a..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/independent-service-mode-14.png and /dev/null differ diff --git a/en/device-dev/driver/figures/independent-service-mode-15.png b/en/device-dev/driver/figures/independent-service-mode-15.png deleted file mode 100644 index c1457af7a0512dbd08436c3dd9d24654c200b85a..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/independent-service-mode-15.png and /dev/null differ diff --git a/en/device-dev/driver/figures/process-of-using-MIPI-CSI.png b/en/device-dev/driver/figures/process-of-using-MIPI-CSI.png new file mode 100644 index 0000000000000000000000000000000000000000..433774c644171cc6eeb267db5d08990e13606178 Binary files /dev/null and b/en/device-dev/driver/figures/process-of-using-MIPI-CSI.png differ diff --git a/en/device-dev/driver/figures/process-of-using-PWM.png b/en/device-dev/driver/figures/process-of-using-PWM.png new file mode 100644 index 0000000000000000000000000000000000000000..7d2c8befd805532d94f9742cc3b28248db5f76e3 Binary files /dev/null and b/en/device-dev/driver/figures/process-of-using-PWM.png differ diff --git a/en/device-dev/driver/figures/service-free-mode-9.png b/en/device-dev/driver/figures/service-free-mode-9.png deleted file mode 100644 index b6e5bd670bfa33120969b239d7564cff888a8fc3..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/service-free-mode-9.png and /dev/null differ diff --git a/en/device-dev/driver/figures/unified-service-mode-8.png b/en/device-dev/driver/figures/unified-service-mode-8.png deleted file mode 100644 index 6e922299f648f02da320ed101119f1a1698bc609..0000000000000000000000000000000000000000 Binary files a/en/device-dev/driver/figures/unified-service-mode-8.png and /dev/null differ diff --git a/en/device-dev/get-code/gettools-acquire.md b/en/device-dev/get-code/gettools-acquire.md index c2f9ba20abb9ef92bcdcb46d67968542ed9c7a8a..e3ae77ea8fbd29fb22bdf330c6e22dd724c2ac0e 100644 --- a/en/device-dev/get-code/gettools-acquire.md +++ b/en/device-dev/get-code/gettools-acquire.md @@ -52,7 +52,7 @@ OpenHarmony provides the following two types of Docker environments for you to q

swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard

-

0.0.5

+

0.0.7

HPM-based Docker environment

@@ -71,6 +71,8 @@ OpenHarmony provides the following two types of Docker environments for you to q + + ## Preparations Before using the Docker environment, perform the following operations: @@ -180,13 +182,13 @@ hb set 1. Obtain the Docker image. ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` 2. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` @@ -208,7 +210,7 @@ hb set 3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.5 + docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 ``` @@ -217,10 +219,10 @@ hb set Run the following script to start building for standard-system devices \(reference memory ≥ 128 MB\). ``` -./build.sh --product-name {product_name} +./build.sh --product-name {product_name} --ccache ``` -**product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300. +**product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300 and RK3568. Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory. diff --git a/en/device-dev/get-code/sourcecode-acquire.md b/en/device-dev/get-code/sourcecode-acquire.md index 2f00491cc1ff1919411fd26d5c925456b97a1192..7b283e10cd64fdab6052fa9a723424f52a3591af 100644 --- a/en/device-dev/get-code/sourcecode-acquire.md +++ b/en/device-dev/get-code/sourcecode-acquire.md @@ -6,14 +6,15 @@ - [When to Use](#section10881513459) - [Prerequisites](#section102871547153314) - [How to Use](#section429012478331) + - [Method 2: Acquiring Source Code from DevEco Marketplace](#section463013147412) - [When to Use](#section26661067443) - [Prerequisites](#section17544943123315) - [How to Use](#section954619433333) + - [Method 3: Acquiring Source Code from a Mirror Site](#section1186691118430) - [Method 4: Acquiring Source Code from the GitHub Image Repository \(at 23:00 UTC Every Day\)](#section23448418360) -- [ Source Code Directories](#section1072115612811) - +- [Source Code Directories](#section1072115612811) ## About OpenHarmony @@ -91,7 +92,6 @@ This document describes how to acquire OpenHarmony source code and provides its repo forall -c 'git lfs pull' ``` - - **Obtaining OpenHarmony release code** For details about how to obtain the source code of an OpenHarmony release, see the [Release-Notes](../../release-notes/Readme.md). @@ -178,121 +178,167 @@ The table below provides only the sites for downloading the latest OpenHarmony m **Table 1** Sites for acquiring source code -

LTS Code

+ + + + + + + + + + + + + + + + + + + + + + + + + + + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -316,7 +362,7 @@ repo sync -c repo forall -c 'git lfs pull' ``` -## Source Code Directories +## Source Code Directories The following table describes the OpenHarmony source code directories. diff --git a/en/device-dev/kernel/Readme-EN.md b/en/device-dev/kernel/Readme-EN.md index 20c103bd6b92eeee833c7f35a7e5b688446af02a..3ef7872307076d761e98cb917836a4a9f03c72d4 100644 --- a/en/device-dev/kernel/Readme-EN.md +++ b/en/device-dev/kernel/Readme-EN.md @@ -53,6 +53,7 @@ - [Memory Corruption Check](kernel-mini-memory-debug-cet.md) - [Exception Debugging](kernel-mini-memory-exception.md) - [Trace](kernel-mini-memory-trace.md) + - [LMS](kernel-mini-debug-lms.md) - [Appendix](kernel-mini-app.md) - [Kernel Coding Specification](kernel-mini-appx-code.md) - [Basic Data Structure](kernel-mini-appx-data.md) @@ -166,6 +167,8 @@ - [Magic Key](kernel-small-debug-shell-magickey.md) - [User-Space Exception Information](kernel-small-debug-shell-error.md) - [Trace](kernel-small-debug-trace.md) + - [perf](kernel-small-debug-perf.md) + - [LMS](kernel-small-debug-lms.md) - [Process Commissioning](kernel-small-debug-process.md) - [CPUP](kernel-small-debug-process-cpu.md) - [Memory Debugging](kernel-small-debug-memory.md) diff --git a/en/device-dev/kernel/kernel-mini-extend-file-littlefs-guide.md b/en/device-dev/kernel/kernel-mini-extend-file-littlefs-guide.md index 02df1a0dab78b18e948956ae9ede4177f05a322f..ab97aff7d89897b05d10c19a8fad5c959a7442d0 100644 --- a/en/device-dev/kernel/kernel-mini-extend-file-littlefs-guide.md +++ b/en/device-dev/kernel/kernel-mini-extend-file-littlefs-guide.md @@ -2,7 +2,7 @@ - [Sample Code](#section1034515054620) -When porting LittleFS to a new hardware device, you need to declare **lfs\_config**: +Before porting LittleFS to a new hardware device, declare **lfs\_config**: ``` const struct lfs_config cfg = { @@ -23,21 +23,44 @@ const struct lfs_config cfg = { }; ``` -**.read**, **.prog**, **.erase**, and **.sync** correspond to the read, write, erase, and synchronization APIs at the bottom layer of the hardware platform, respectively. +**.read**, **.prog**, **.erase**, and **.sync** correspond to the underlying read, write, erase, and synchronization APIs of the hardware platform, respectively. -**read\_size** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed. +**read\_size** indicates the number of bytes read each time. You can set it to a value greater than the physical read unit to improve performance. This value determines the size of the read cache. However, if the value is too large, more memory is consumed. -**prog\_size** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **read\_size**. However, if the value is too large, more memory is consumed. +**prog\_size** indicates the number of bytes written each time. You can set it to a value greater than the physical write unit to improve performance. This value determines the size of the write cache and must be an integral multiple of **read\_size**. However, if the value is too large, more memory is consumed. -**block\_size**: indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **prog\_size**. +**block\_size** indicates the number of bytes in each erase block. The value can be greater than that of the physical erase unit. However, a smaller value is recommended because each file occupies at least one block. The value must be an integral multiple of **prog\_size**. -**block\_count** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased \(**block\_size**\). +**block\_count** indicates the number of blocks that can be erased, which depends on the capacity of the block device and the size of the block to be erased \(**block\_size**\). ## Sample Code The sample code is as follows: ``` +#include "lfs.h" +#include "stdio.h" + +lfs_t lfs; +lfs_file_t file; + +const struct lfs_config cfg = { + // block device operations + .read = user_provided_block_device_read, + .prog = user_provided_block_device_prog, + .erase = user_provided_block_device_erase, + .sync = user_provided_block_device_sync, + + // block device configuration + .read_size = 16, + .prog_size = 16, + .block_size = 4096, + .block_count = 128, + .cache_size = 16, + .lookahead_size = 16, + .block_cycles = 500, +}; + int main(void) { // mount the filesystem int err = lfs_mount(&lfs, &cfg); diff --git a/en/device-dev/kernel/kernel-standard-overview.md b/en/device-dev/kernel/kernel-standard-overview.md index 30ed851caef2c4f48d5be2cd260649ebd96babea..b6046050d7a6047bee5bc899b59de6cf044ba07e 100644 --- a/en/device-dev/kernel/kernel-standard-overview.md +++ b/en/device-dev/kernel/kernel-standard-overview.md @@ -3,7 +3,7 @@ - [Linux Kernel Versions](#section152847516485) - [OpenHarmony Kernel Version Selection](#section2716416191715) -OpenHarmony adopts the Linux kernel as the basic kernel for standard-system devices \(reference memory ≥ 128 MB\) so that appropriate OS kernels can be selected for the devices subject to resource limitations and therefore provide basic capabilities for upper-layer apps. +OpenHarmony adopts the Linux kernel as the basic kernel for standard-system devices \(reference memory ≥ 128 MiB\) so that appropriate OS kernels can be selected for the devices subject to resource limitations and therefore provide basic capabilities for upper-layer apps. ## Linux Kernel Versions diff --git a/en/device-dev/porting/Readme-EN.md b/en/device-dev/porting/Readme-EN.md index afad91900a056f6940c3df29fa813e8823cb916f..57b44217b5c89af5611218a2581abd4d8994e7d8 100644 --- a/en/device-dev/porting/Readme-EN.md +++ b/en/device-dev/porting/Readme-EN.md @@ -1,4 +1,4 @@ -# Development Board Porting +# Introduction OpenHarmony has organized a Special Interest Group (SIG) [SIG_DevBoard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard.md) to provide support for third-party development boards. Before learning about how to port the code of a development board, take a look at the device classification on OpenHarmony. The porting methods vary according to the device type. @@ -9,7 +9,7 @@ Before learning about how to port the code of a development board, take a look a | Small-system devices| Memory > 1 MB, with MMU| LiteOS-A and Linux| | Standard-system devices| Memory > 128 MB| Linux | -## Code Preparation +# Code Preparation OpenHarmony has created repositories for vendors in openharmony-sig. To participate in the repository development, you need to use the following method to initialize and download the code. @@ -19,7 +19,7 @@ repo init -u https://gitee.com/openharmony-sig/manifest.git -b master -m devboar The download steps for other resources are the same as those in the mainline version. -## Porting Procedure +# Porting Procedure - [Mini System SoC Porting Guide](porting-minichip.md) - [Porting Preparations](porting-chip-prepare.md) @@ -34,6 +34,7 @@ The download steps for other resources are the same as those in the mainline ver - [Board-Level Driver Adaptation](porting-chip-board-driver.md) - [Implementation of APIs at the HAL](porting-chip-board-hal.md) - [System Modules](porting-chip-board-component.md) + - [lwIP Module Adaptation](porting-chip-board-lwip.md) - [Third-party Module Adaptation](porting-chip-board-bundle.md) - [XTS](porting-chip-board-xts.md) - [FAQ](porting-chip-faqs.md) @@ -48,11 +49,10 @@ The download steps for other resources are the same as those in the mainline ver - [Overview](porting-smallchip-driver-overview.md) - [Platform Driver Porting](porting-smallchip-driver-plat.md) - [Device Driver Porting](porting-smallchip-driver-oom.md) -- [Standard System Porting Guide](standard-system-porting-guide.md) -- [A Method for Rapidly Porting the OpenHarmony Linux Kernel](porting-linux-kernel-overview.md) - -# Third-Party Library Porting Guide - -- [Overview](porting-thirdparty-overview.md) -- [Porting a Library Built Using CMake](porting-thirdparty-cmake.md) -- [Porting a Library Built Using Makefile](porting-thirdparty-makefile.md) +- Standard System SoC Porting Guide + - [Standard System Porting Guide](standard-system-porting-guide.md) + - [A Method for Rapidly Porting the OpenHarmony Linux Kernel](porting-linux-kernel.md) +- [Third-Party Library Porting Guide for Mini and Small Systems](porting-thirdparty.md) + - [Overview](porting-thirdparty-overview.md) + - [Porting a Library Built Using CMake](porting-thirdparty-cmake.md) + - [Porting a Library Built Using Makefile](porting-thirdparty-makefile.md) \ No newline at end of file diff --git a/en/device-dev/porting/porting-linux-kernel-overview.md b/en/device-dev/porting/porting-linux-kernel.md similarity index 100% rename from en/device-dev/porting/porting-linux-kernel-overview.md rename to en/device-dev/porting/porting-linux-kernel.md diff --git a/en/device-dev/quick-start/oem_minitinier_des_3516.md b/en/device-dev/quick-start/quickstart-lite-introduction-hi3516.md similarity index 100% rename from en/device-dev/quick-start/oem_minitinier_des_3516.md rename to en/device-dev/quick-start/quickstart-lite-introduction-hi3516.md diff --git a/en/device-dev/quick-start/oem_minitinier_des_3518.md b/en/device-dev/quick-start/quickstart-lite-introduction-hi3518.md similarity index 100% rename from en/device-dev/quick-start/oem_minitinier_des_3518.md rename to en/device-dev/quick-start/quickstart-lite-introduction-hi3518.md diff --git a/en/device-dev/quick-start/oem_minitinier_des_3861.md b/en/device-dev/quick-start/quickstart-lite-introduction-hi3861.md similarity index 100% rename from en/device-dev/quick-start/oem_minitinier_des_3861.md rename to en/device-dev/quick-start/quickstart-lite-introduction-hi3861.md diff --git a/en/device-dev/quick-start/quickstart-standard-docker-environment.md b/en/device-dev/quick-start/quickstart-standard-docker-environment.md index 93f11715dc1ce148831f9c1afb7a3536a316faec..5101d177a23fc2724394313d8a9ba2c4cfd89dfe 100644 --- a/en/device-dev/quick-start/quickstart-standard-docker-environment.md +++ b/en/device-dev/quick-start/quickstart-standard-docker-environment.md @@ -74,13 +74,13 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. 1. Obtain the Docker image. ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` 2. Go to the root directory of source code and run the following command to access the Docker build environment: ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` @@ -102,7 +102,7 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. 3. Go to the root directory of source code and run the following command to access the Docker build environment: ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.5 + docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 ``` @@ -111,10 +111,10 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. 1. Run the following script to start building for standard-system devices \(reference memory ≥ 128 MB\). ``` - ./build.sh --product-name {product_name} + ./build.sh --product-name {product_name} --ccache ``` - **product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300. + **product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300, rk3568. Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory. diff --git a/en/device-dev/subsystems/Readme-EN.md b/en/device-dev/subsystems/Readme-EN.md index 90d19a51f44f7845c2ae865d43a43f23fedcc8ed..2c0dfb30758c6fb43cef85c2c473ad267fa23261 100644 --- a/en/device-dev/subsystems/Readme-EN.md +++ b/en/device-dev/subsystems/Readme-EN.md @@ -39,6 +39,13 @@ - [KWS SDK](subsys-aiframework-demo-sdk.md) - [KWS Plug-in](subsys-aiframework-demo-plugin.md) - [KWS Configuration File](subsys-aiframework-demo-conf.md) +- [Data Management](subsys-data.md) + - [RDB](subsys-data-relational-database.md) + - [RDB Overview](subsys-data-relational-database-overview.md) + - [RDB Development](subsys-data-relational-database-guide.md) + - [Lightweight Data Store](subsys-data-storage.md) + - [Lightweight Data Store Overview](subsys-data-storage-overview.md) + - [Lightweight Data Store Development](subsys-data-storage-guide.md) - [Sensors](subsys-sensor.md) - [Sensors Overview](subsys-sensor-overview.md) - [Sensors Usage Guidelines](subsys-sensor-guide.md) @@ -70,7 +77,13 @@ - [DFX](subsys-dfx-overview.md) - [Development Guidelines on HiLog ](subsys-dfx-hilog-rich.md) - [Development Guidelines on HiLog\_Lite](subsys-dfx-hilog-lite.md) + - [Development Guidelines on HiTrace](subsys-dfx-hitrace-development.md) + - [Development Guidelines on HiCollie](subsys-dfx-hicollie-development.md) - [Development Guidelines on HiSysEvent](subsys-dfx-hisysevent.md) + - [subsys-dfx-hisysevent-logging](subsys-dfx-hisysevent-logging.md) + - [subsys-dfx-hisysevent-listening](subsys-dfx-hisysevent-listening.md) + - [subsys-dfx-hisysevent-query](subsys-dfx-hisysevent-query.md) + - [subsys-dfx-hisysevent-tool-usage](subsys-dfx-hisysevent-tool-usage.md) - [R&D Tools](subsys-toolchain.md) - [bytrace Usage Guidelines](subsys-toolchain-bytrace-guide.md) - [hdc\_std Usage Guidelines](oem_subsys_toolchain_hdc_guide.md) diff --git a/en/device-dev/subsystems/figure/USB_service_architecture.png b/en/device-dev/subsystems/figure/USB_service_architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..3aaf512454de1bee6a16925ec2346f894c5b724a Binary files /dev/null and b/en/device-dev/subsystems/figure/USB_service_architecture.png differ diff --git a/en/device-dev/subsystems/figure/call-chain-tracing-in-synchronous-communication.png b/en/device-dev/subsystems/figure/call-chain-tracing-in-synchronous-communication.png new file mode 100644 index 0000000000000000000000000000000000000000..585d8aac7b4857645b78ab11effbe900e5350f9d Binary files /dev/null and b/en/device-dev/subsystems/figure/call-chain-tracing-in-synchronous-communication.png differ diff --git a/en/device-dev/subsystems/figure/en-us_image_0000001115980740.png b/en/device-dev/subsystems/figure/en-us_image_0000001115980740.png new file mode 100644 index 0000000000000000000000000000000000000000..c343579a89f8e1c8bec5523c843424f89ca1b825 Binary files /dev/null and b/en/device-dev/subsystems/figure/en-us_image_0000001115980740.png differ diff --git a/en/device-dev/subsystems/figure/en-us_image_0000001192123772.png b/en/device-dev/subsystems/figure/en-us_image_0000001192123772.png new file mode 100644 index 0000000000000000000000000000000000000000..8d1dabae78c438928544864ca2cada41260aa2f5 Binary files /dev/null and b/en/device-dev/subsystems/figure/en-us_image_0000001192123772.png differ diff --git a/en/device-dev/subsystems/figure/service-calling-process-(inter-device-and-inter-process-synchronous-call).png b/en/device-dev/subsystems/figure/service-calling-process-(inter-device-and-inter-process-synchronous-call).png new file mode 100644 index 0000000000000000000000000000000000000000..8d2f131151856e03e63ae906687a7a570a953540 Binary files /dev/null and b/en/device-dev/subsystems/figure/service-calling-process-(inter-device-and-inter-process-synchronous-call).png differ diff --git a/en/device-dev/subsystems/figure/service-calling-process.png b/en/device-dev/subsystems/figure/service-calling-process.png new file mode 100644 index 0000000000000000000000000000000000000000..e2564fab03924ea36fbc371dbafeb6b4724bb5b3 Binary files /dev/null and b/en/device-dev/subsystems/figure/service-calling-process.png differ diff --git a/en/device-dev/subsystems/figure/time-delay-in-the-service-calling-process.png b/en/device-dev/subsystems/figure/time-delay-in-the-service-calling-process.png new file mode 100644 index 0000000000000000000000000000000000000000..d04fc58ea7b7f87148d86f6c5cd3423a042a82be Binary files /dev/null and b/en/device-dev/subsystems/figure/time-delay-in-the-service-calling-process.png differ diff --git a/en/device-dev/subsystems/figure/use-cases-of-hitrace.png b/en/device-dev/subsystems/figure/use-cases-of-hitrace.png new file mode 100644 index 0000000000000000000000000000000000000000..20e4592ac077d3d7b63f072d3d640732ac9ee3ac Binary files /dev/null and b/en/device-dev/subsystems/figure/use-cases-of-hitrace.png differ diff --git a/en/device-dev/subsystems/subsys-build-mini-lite.md b/en/device-dev/subsystems/subsys-build-mini-lite.md index 4cd0b642ab5c7523a7896846ad3cf9e774288561..49420b052f99566096f0b91c1d188f5eae2e936e 100644 --- a/en/device-dev/subsystems/subsys-build-mini-lite.md +++ b/en/device-dev/subsystems/subsys-build-mini-lite.md @@ -156,7 +156,7 @@ Observe the following rules when building the **BUILD.gn** module: - Define macros in the **OHOS\_**\{_SUBSYSTEM_\}**\_**\{_MODULE_\}**\_**\{_FEATURE_\} format. >![](../public_sys-resources/icon-note.gif) **NOTE:** - >GN is used as the build script language for modules. For details about how to use GN, see the [GN Quick Start Guide](https://gn.googlesource.com/gn/+/master/docs/quick_start.md). In GN, a module is a build target, which can be a static library, a dynamic library, an executable file, or a group. + >GN is used as the build script language for modules. For details about how to use GN, see https://gn.googlesource.com/gn/+/master/docs/quick_start.md. In GN, a module is a build target, which can be a static library, a dynamic library, an executable file, or a group. The following example shows how to build the **foundation/graphic/ui/BUILD.gn** file for a graphics UI module: @@ -338,6 +338,8 @@ The key directories and files are described as follows: ``` { "product_name": "ipcamera", # Product name + "version": "3.0", # config.json version, which is 3.0 + "type": "small", # System type, which can be mini, small, or standard "ohos_version": "OpenHarmony 1.0", # OS version "device_company": "hisilicon", # Chipset vendor "board": "hispark_taurus", # Name of the development board @@ -623,7 +625,7 @@ The following uses the RTL8720 development board provided by Realtek as an examp 2. Create a directory for kernel adaptation and build the **config.gni** file of the development board. - For example, to adapt the LiteOS Cortex-M kernel to the RTL8720 development board, configure the **device/realtek/rtl8720/liteos\_a/config.gni** file as follows: + For example, to adapt the LiteOS-A kernel to the RTL8720 development board, configure the **device/realtek/rtl8720/liteos\_a/config.gni** file as follows: ``` # Kernel type, e.g. "linux", "liteos_a", "liteos_m". @@ -695,6 +697,8 @@ You can use the Compilation and Building subsystem to customize product solution ``` { "product_name": "wifiiot", # Product name + "version": "3.0", # config.json version, which is 3.0 + "type": "small", # System type, which can be mini, small, or standard "ohos_version": "OpenHarmony 1.0", # OS version "device_company": "realtek", # Name of the chipset solution vendor "board": "rtl8720", # Name of the development board @@ -925,7 +929,7 @@ You can use the Compilation and Building subsystem to customize product solution - **Solution** ``` - ​sudo apt-get install dosfstools mtools + sudo apt-get install dosfstools mtools ``` @@ -994,4 +998,3 @@ You can use the Compilation and Building subsystem to customize product solution sudo ln -s /bin/bash /bin/sh ``` - diff --git a/en/device-dev/subsystems/subsys-data-relational-database-guide.md b/en/device-dev/subsystems/subsys-data-relational-database-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..44a0b1829249264fb99aff7cf998dd6a4de43b38 --- /dev/null +++ b/en/device-dev/subsystems/subsys-data-relational-database-guide.md @@ -0,0 +1,188 @@ +# RDB Development + +## When to Use + +On the basis of the SQLite database, the RDB allows you to operate data with or without native SQL statements. In OpenHarmony, an RDB is also called RDB store. + +## Available APIs +### Creating and Deleting an RDB Store + +The following table describes APIs available for creating and deleting an RDB store. + +Table 1 APIs for creating and deleting an RDB store + +| Class| API| Description| +| ---- | ---- | ---- | +| RdbStoreConfig | RdbStoreConfig(const std::string &path,
StorageMode storageMode = StorageMode::MODE_DISK,
bool readOnly = false,
const std::vector &encryptKey = std::vector(),
const std::string &journalMode = "",
const std::string &syncMode = "",
const std::string &databaseFileType = "",
const std::string &databaseFileSecurityLevel = "") | Configures an RDB store, including setting the name, storage mode, log mode, synchronization mode, and read-only mode, and encrypting the database.
  • **path**: path of the database.
  • **readOnly**: whether the database is read-only.
  • **storageMode**: storage mode.
  • **encryptKey**: key used for database encryption.
  • **journalMode**: database logging mode.
  • **syncMode**: data synchronization mode.
  • **databaseFileType**: database type.
  • **databaseFileSecurityLevel**: security level.
| +| RdbOpenCallback | int OnCreate(RdbStore &rdbStore) | Called when an RDB store is created. You can add the method for initializing the table structure and add initialization data used by your application in the callback.| +| RdbOpenCallback | int OnUpgrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is upgraded.| +| RdbOpenCallback | int OnDowngrade(RdbStore &rdbStore, int currentVersion, int targetVersion) | Called when the RDB store is downgraded.| +| RdbHelper | std::shared_ptr\ GetRdbStore(const RdbStoreConfig &config, int version, RdbOpenCallback &openCallback, int &errCode) | Creates or obtains an RDB store.| +| RdbHelper | int DeleteRdbStore(const std::string &path) | Deletes the specified RDB store.| + +### Encrypting an RDB Store + +The RDB provides the database encryption capability. When creating an RDB store , you can add a key for security purposes. After that, the RDB store can be accessed only with the correct key. + +Table 2 API for changing the key +| Class| API| Description| +| ---- | ---- | ---- | +| RdbStore | int ChangeEncryptKey(const std::vector &newKey) | Changes the encryption key for an RDB store.
Note: The encryption key can be changed only for an encrypted database.| + +### Using Predicates + +The RDB provides **AbsRdbPredicates** for you to set database operation conditions. The **AbsRdbPredicates** has the following child classes: + +- **RdbPredicates**: With this class, you do not need to write complex SQL statements. Instead, you can combine SQL statements simply by calling methods in this class, such as **equalTo**, **notEqualTo**, **groupBy**, **orderByAsc**, and **beginsWith**. +- **RawRdbPredicates**: With this class, you can set **whereClause** and **whereArgs**, but cannot call methods such as **equalTo**. + + Table 7 APIs for RDB predicates + | Class| API| Description| + | ---- | ---- | ---- | + | RdbPredicates | AbsPredicates *EqualTo(std::string field, std::string value) | Sets the **AbsPredicates** to match the field that is equal to the specified value.| + | RdbPredicates | AbsPredicates *NotEqualTo(std::string field, std::string value) | Sets the **AbsPredicates** to match the field that is not equal to the specified value.| + | RdbPredicates | AbsPredicates *BeginsWith(std::string field, std::string value) | Sets the **AbsPredicates** to match the field that starts with the specified value.| + | RdbPredicates | AbsPredicates *Between(std::string field, std::string low, std::string high) | Sets the **AbsPredicates** to match the field that is within the range specified by **low** and **high**.| + | RdbPredicates | AbsPredicates *OrderByAsc(std::string field) | Sets the **AbsPredicates** to match the column with values sorted in ascending order.| + | RdbPredicates | void SetWhereClause(std::string whereClause) | Sets **whereClause**.| + | RdbPredicates | void SetWhereArgs(std::vector\ whereArgs) | Sets **whereArgs**, which indicates the value of the placeholder in **whereClause**.| + +### Managing Data in an RDB Store + +The RDB provides APIs for inserting, deleting, updating, and querying data in the local RDB store. + +- Inserting data + + The RDB provides an API for inserting data through **ValuesBucket** in a data table. If the data is added, the row number of the data inserted is returned; otherwise, **-1** is returned. + + Table 3 API for inserting data to a data table + + | Class| API| Description| + | ---- | ---- | ---- | + | RdbStore | int Insert(int64_t &outRowId, const std::string &table, const ValuesBucket &initialValues) | Inserts data based on the passed table name and data in **ValuesBucket**.
  • **table**: specifies the name of the target table.
  • **initialValues**: specifies the data, stored in **ValuesBucket**, to insert. A series of **put()** methods, such as **PutString(const std::string &columnName, const std::string &value)** and **PutDouble(const std::string &columnName, double value)**, are provided to add data to **ValuesBucket**.
| + +- Deleting data + + Call the **delete()** method to delete data meeting the conditions specified by **AbsRdbPredicates**. If the data is deleted, the row number of the deleted data is returned; otherwise, **0** is returned. + + Table 5 API for deleting data + | Class| API| Description| + | ---- | ---- | ---- | + | RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data.
  • **deletedRows**: specifies the number of rows to delete.
  • **predicates**: specifies the table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes:
    • **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.
| + +- Updating data + + Call the **update()** method to modify data based on the passed data and the conditions specified by **AbsRdbPredicates**. If the data is updated, the row number of the updated data is returned; otherwise, **0** is returned. + + Table 4 API for updating data + | Class| API| Description| + | ---- | ---- | ---- | + | RdbStore | int Update(int &changedRows, const ValuesBucket &values, const AbsRdbPredicates &predicates) | Updates the data that meets the conditions specified by predicates.
  • **changedRows**: specifies the number of rows to update.
  • **values**: specifies the new data stored in **ValuesBucket**.
  • **predicates**: specifies the table name and conditions for the update operation. **AbsRdbPredicates** has the following classes:
    • **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.
| + +- Querying data + + You can query data in an RDB store in either of the following ways: + + - Call the **query()** method to query data based on the predicates, without passing any SQL statement. + - Run the native SQL statement. + + Table 6 APIs for querying data + | Class| API| Description| + | ---- | ---- | ---- | + | RdbStore | std::unique_ptr Query(const AbsRdbPredicates &predicates, const std::vector\ columns) | Queries data.
  • **predicates**: specifies the query conditions. **AbsRdbPredicates** has the following classes:
    • **RdbPredicates**: specifies the query conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause**, and **whereArgs** only.
  • **columns**: specifies the number of columns returned.
| + | RdbStore | std::unique_ptr QuerySql(const std::string &sql, const std::vector\ &selectionArgs = std::vector\()) | Executes the native SQL statements to query data.
  • **sql**: specifies the native SQL statement.
  • **selectionArgs**: specifies the parameter values corresponding to the placeholders in the SQL statements. Set it to **null** if the **select** statement has no placeholder.
| + +### Using the Result Set + +A result set can be regarded as rows 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**. + + Table 8 APIs for using the result set + | Class| API| Description| + | ---- | ---- | ---- | + | ResultSet | int GoTo(int offset) | Moves the result set forwards or backwards by the specified offset relative to its current position.| + | ResultSet | int GoToRow(int position) | Moves the result set to the specified row.| + | ResultSet | int GoToNextRow() | Moves the result set to the next row.| + | ResultSet | int GoToPreviousRow() | Moves the result set to the previous row.| + | ResultSet | int IsStarted(bool &result) | Checks whether the result set has been moved.| + | ResultSet | int IsEnded(bool &result) | Checks whether the result set is moved after the last line.| + | ResultSet | int IsAtFirstRow(bool &result) | Checks whether the result set is located in the first row.| + | ResultSet | int IsAtLastRow(bool &result) | Checks whether the result set is located in the last row.| + | ResultSet | int GetRowCount(int &count) | Obtains the number of rows in the result set.| + | ResultSet | int GetColumnCount(int &count) | Obtains the number of columns in the result set.| + | ResultSet | int GetString(int columnIndex, std::string &value) | Obtains the values in the specified column of the current row, in strings.| + | ResultSet | int GetBlob(int columnIndex, std::vector\ &blob) | Obtains the values in the specified column of the current row, in a byte array.| + | ResultSet | int GetDouble(int columnIndex, double &value) | Obtains the values in the specified column of the current row, in double.| + +## Constraints + +None. + +## How to Develop + +1. Create an RDB store. + + a. Configure the RDB store attributes, including the database name, storage mode, and read-only mode. + + b. Initialize the table structure and related data in the RDB store. + + c. Create an RDB store. + + The sample code is as follows: + ``` + const std::string DATABASE_NAME = RDB_TEST_PATH + "RdbStoreTest.db"; + const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, salary REAL, blobType BLOB)"; + + class OpenCallback : public RdbOpenCallback { + public: + int OnCreate(RdbStore &rdbStore) override; + int OnUpgrade(RdbStore &rdbStore, int oldVersion, int newVersion) override; + }; + + int OpenCallback::OnCreate(RdbStore &store) + { + return store.ExecuteSql(CREATE_TABLE_TEST); + } + + RdbStoreConfig config(DATABASE_NAME); + OpenCallback callback; + + std::shared_ptr store = RdbHelper::GetRdbStore(config, 1, callback, 0); + ``` + +2. Insert data. + + a. Create a **ValuesBucket** to store the data you need to insert. + + b. Call the **insert()** method to insert data into the RDB store. + + The sample code is as follows: + ``` + ValuesBucket values; + + values.PutInt("id", 1); + values.PutString("name", std::string("Tom")); + values.PutInt("age", 18); + values.PutDouble("salary", 100.5); + values.PutBlob("blobType", std::vector{ 1, 2, 3 }); + store->Insert(id, "test", values); + ``` + +3. Query data. + + a. Create a predicate that specifies query conditions. + + b. Specify the data columns to return in the result set. + + c. Call the **query()** method to query data. + + d. Call the **ResultSet** APIs to traverse data in the result set. + + The sample code is as follows: + ``` + std::vector columns = {"id", "name", "age", "salary"}; + + RdbPredicates predicates("test"); + predicates.EqualTo("age", "25")->OrderByAsc("salary"); + std::unique_ptr resultSet = store->Query(predicates, columns) + resultSet.goToNextRow(); + ``` diff --git a/en/device-dev/subsystems/subsys-data-relational-database-overview.md b/en/device-dev/subsystems/subsys-data-relational-database-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..e152fd38c14b2b10a465547e1359b6ce175fd099 --- /dev/null +++ b/en/device-dev/subsystems/subsys-data-relational-database-overview.md @@ -0,0 +1,37 @@ +# RDB Overview + +The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the OpenHarmony RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. + +## Basic Concepts + +- RDB + + A type of database created on the basis of relational models. The RDB stores data in rows and columns. + +- Predicate + + A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions. + +- Result set + + A set of query results used to access data. You can access the required data in a result set in flexible modes. + +- SQLite database + + A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability (ACID). + +## Working Principles +The OpenHarmony RDB provides a common operation interface (**RdbStore**) for external systems. It uses the third-party open-source SQLite as the underlying persistent storage engine, which supports all SQLite database features. + +**Figure 1** How RDB works + +![](figure/en-us_image_0000001115980740.png) + +## Default Settings +- The default database logging mode is write-ahead logging (WAL). +- The default database flush mode is Full mode. +- The default shared memory is 8 MB for the OpenHarmony database and 2 MB for a single query. + +## Constraints +- A maximum of four connection pools can be connected to an RDB to manage read and write operations. +- To ensure data accuracy, the RDB supports only one write operation at a time. diff --git a/en/device-dev/subsystems/subsys-data-relational-database.md b/en/device-dev/subsystems/subsys-data-relational-database.md new file mode 100644 index 0000000000000000000000000000000000000000..b1b3c1b15503b45874a2c6886458e7d904af9388 --- /dev/null +++ b/en/device-dev/subsystems/subsys-data-relational-database.md @@ -0,0 +1,5 @@ +# RDB + +- **[RDB Overview](subsys-data-relational-database-overview.md)** + +- **[RDB Development](subsys-data-relational-database-guide.md)** diff --git a/en/device-dev/subsystems/subsys-data-storage-guide.md b/en/device-dev/subsystems/subsys-data-storage-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..152935dc1a60c17cfda5ba745e98321ec3a2c912 --- /dev/null +++ b/en/device-dev/subsystems/subsys-data-storage-guide.md @@ -0,0 +1,193 @@ +# Lightweight Data Store Development + +## When to Use + +The lightweight data store is ideal for storing lightweight and frequently used data, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the Preferences APIs. + +## Available APIs + +The lightweight data store provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value pairs. Keys are of the string type, and values can be of the string, Boolean, integer, long integer, float, double, or string array type. + +**Creating a Preferences Instance** + +Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance. + +**Table 1** API for creating a Preferences instance + +| Class| Method| Description| +| --- | ----- | ----| +| PreferencesHelper | static std::shared_ptr GetPreferences(const std::string &path, int &errCode); | Creates a **Preferences** instance.
**path**: storage path of the application data.
**errCode**: error code.
Return value: **Preferences** instance created.| + +**Writing Data** + +Call the **put()** method to add or modify data in a **Preferences** instance. + +**Table 2** APIs for writing data + +| Class| Method| Description| +| --- | ----- | ----| +| Preferences | int PutInt(const std::string &key, int value); | **key**: key of the data to write. It cannot be empty.
**value**: value of the data to write.
Return value: error code.| +| Preferences | int PutString(const std::string &key, const std::string &value); | **key**: key of the data to write. It cannot be empty.
**value**: value of the data to write.
Return value: error code.| +| Preferences | int PutBool(const std::string &key, bool value); | **key**: key of the data to write. It cannot be empty.
**value**: value of the data to write.
Return value: error code.| +| Preferences | int PutLong(const std::string &key, int64_t value); | **key**: key of the data to write. It cannot be empty.
**value**: value of the data to write.
Return value: error code.| +| Preferences | int PutFloat(const std::string &key, float value); | **key**: key of the data to write. It cannot be empty.
**value**: value of the data to write.
Return value: error code.| +| Preferences | int PutDouble(const std::string &key, double value); | **key**: key of the data to write. It cannot be empty.
**value**: value of the data to write.
Return value: error code.| +| Preferences | int PutStringSet(const std::string &key, const std::set\ &value); | **key**: key of the data to write. It cannot be empty.
**value**: value of the data to write.
Return value: error code.| + +**Reading Data** + +Call the **get()** method to read data from a **Preferences** instance. + +**Table 3** APIs for reading data + +| Class| Method| Description| +| --- | ----- | ----| +| Preferences | bool GetBool(const std::string &key, bool defValue); | **key**: key of the data to read. It cannot be empty.
**defValue**: default value to return if the operation fails or the value does not exist.
Return value: Returns the value read if the operation is successful; returns **defValue** otherwise.| +| Preferences | std::string GetString(const std::string &key, const std::string &defValue); | **key**: key of the data to read. It cannot be empty.
**defValue**: default value to return if the operation fails or the value does not exist.
Return value: Returns the value read if the operation is successful; returns **defValue** otherwise.| +| Preferences | bool GetBool(const std::string &key, bool defValue); | **key**: key of the data to read. It cannot be empty.
**defValue**: default value to return if the operation fails or the value does not exist.
Return value: Returns the value read if the operation is successful; returns **defValue** otherwise.| +| Preferences | float GetFloat(const std::string &key, float defValue); | **key**: key of the data to read. It cannot be empty.
**defValue**: default value to return if the operation fails or the value does not exist.
Return value: Returns the value read if the operation is successful; returns **defValue** otherwise.| +| Preferences | double GetDouble(const std::string &key, double defValue); | **key**: key of the data to read. It cannot be empty.
**defValue**: default value to return if the operation fails or the value does not exist.
Return value: Returns the value read if the operation is successful; returns **defValue** otherwise.| +| Preferences | int64_t GetLong(const std::string &key, int64_t defValue); | **key**: key of the data to read. It cannot be empty.
**defValue**: default value to return if the operation fails or the value does not exist.
Return value: Returns the value read if the operation is successful; returns **defValue** otherwise.| +| Preferences | std::set\ GetStringSet(const std::string &key, std::set\ &defValue); | **key**: key of the data to read. It cannot be empty.
**defValue**: default value to return if the operation fails or the value does not exist.
Return value: Returns the value read if the operation is successful; returns **defValue** otherwise.| + +**Storing Data Persistently** + +Call the **flush()** or **flushSync** method to write the cached data back to its text file for persistent storage. + +**Table 4** APIs for data persistence + +| Class| Method| Description| +| --- | ----- | ----| +| Preferences | void Flush(); | Writes data in the **Preferences** instance back to its file through an asynchronous thread.| +| Preferences | int FlushSync(); | Writes data in the **Preferences** instance back to its file through a synchronous thread.| + +**Observing Data Changes** + +Specify **PreferencesObserver** as the callback to subscribe to data changes. When the value of the subscribed key is changed and the **flush()** method is executed, **PreferencesObserver** will be invoked. + +**Table 5** APIs for subscribing to data changes + +| Class| Method| Description| +| --- | ----- | ----| +| Preferences | void RegisterObserver(std::shared_ptr preferencesObserver); | Subscribes to data changes.
**preferencesObserver**: callback invoked to return the data changes.| +| Preferences | void UnRegisterObserver(std::shared_ptr preferencesObserver); | Unsubscribes from data changes.
**preferencesObserver**: callback used to report data changes.| + +**Deleting Data** + +Use the following APIs to delete a **Preferences** instance or data file. + +**Table 6** APIs for deleting data + +| Class| Method| Description| +| --- | ----- | ----| +| PreferencesHelper | int DeletePreferences(const std::string &path); | Deletes a **Preferences** instance from the memory and deletes its file from the device.
**path**: storage path of the application data.
Return value: error code.| +| PreferencesHelper | int RemovePreferencesFromCache(const std::string &path); | Deletes a **Preferences** instance from the memory.
**path**: storage path of the application data.
Return value: error code.| + +## How to Develop + +1. Import the Preferences module and related header files to the development environment. + + ``` C++ + Header file path: //distributeddatamgr_appdatamgr/interfaces/innerkits/native_preferences/include + ``` + +2. Create a **Preferences** instance. + + Read the specified file and load its data to the **Preferences** instance for data operations. + + ``` C++ + int errCode = E_OK; + Preferences pref = PreferencesHelper::GetPreferences(PREF_TEST_PATH + "test.xml", errCode); // PREF_TEST_PATH must be the application sandbox path. + EXPECT_EQ(errCode, E_OK); + ``` + + +3. Write data. + + Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance. + + ```C++ + pref->PutString("test", "remove"); + ``` + +4. Read data. + + Use the **get()** method of the **Preferences** class to read data. + + ``` C++ + std::string ret = pref->GetString("test", "defaultValue"); + EXPECT_EQ(ret, "remove"); + ``` + + +5. Store data persistently. + + Use the **flush()** or **flushSync()** method to flush data in the **Preferences** instance to its file. + + ```C++ + int err = pref->FlushSync(); + EXPECT_EQ(ret, E_OK); + ``` + + +6. Subscribe to data changes. + + Specify **PreferencesObserver** as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** or **flushSync()** method is executed, **PreferencesObserver** will be invoked. Unregister the **PreferencesObserver** when it is no longer required. + + Customize a class to implement the **PreferencesObserver**: + ``` C++ + class PreferencesObserverCounter : public PreferencesObserver { + public: + virtual ~PreferencesObserverCounter(); + void OnChange(Preferences &preferences, const std::string &key) override; + + std::atomic_int notifyTimes; + static const std::vector NOTIFY_KEYS_VECTOR; + }; + + PreferencesObserverCounter::~PreferencesObserverCounter() {} + + void PreferencesObserverCounter::OnChange(Preferences &preferences, const std::string &key) + { + for (auto it = NOTIFY_KEYS_VECTOR.cbegin(); it != NOTIFY_KEYS_VECTOR.cend(); it++) { + if (key.compare(*it)) { + notifyTimes++; + break; + } + } + } + + const std::vector PreferencesObserverCounter::NOTIFY_KEYS_VECTOR = { PreferencesTest::KEY_TEST_INT_ELEMENT, + PreferencesTest::KEY_TEST_LONG_ELEMENT, PreferencesTest::KEY_TEST_FLOAT_ELEMENT, + PreferencesTest::KEY_TEST_BOOL_ELEMENT, PreferencesTest::KEY_TEST_STRING_ELEMENT }; + ``` + + Subscribe to data changes and invoke the callback: + ``` C++ + std::shared_ptr counter = + std::shared_ptr(new PreferencesObserverCounter()); + pref->RegisterObserver(counter); // Register a callback to return data changes. + + pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + pref->Flush(); // Trigger the onChanged callback of the counter. + EXPECT_EQ(static_cast(counter.get())->notifyTimes, 1); + + /* same value */ + pref->PutInt(PreferencesTest::KEY_TEST_INT_ELEMENT, 2); + pref->PutString(PreferencesTest::KEY_TEST_STRING_ELEMENT, "test"); + pref->Flush(); + EXPECT_EQ(static_cast(counter.get())->notifyTimes, 2); + + pref->UnRegisterObserver(counter); // Unregister the callback for data changes. + ``` + + +7. Delete the specified file. + + Delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored. + + ``` C++ + pref = nullptr; + int ret = PreferencesHelper::DeletePreferences("/data/test/test"); + EXPECT_EQ(ret, E_OK); + ``` diff --git a/en/device-dev/subsystems/subsys-data-storage-overview.md b/en/device-dev/subsystems/subsys-data-storage-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..fee188e448354c1a09825b2880d7a2485c69818f --- /dev/null +++ b/en/device-dev/subsystems/subsys-data-storage-overview.md @@ -0,0 +1,31 @@ +# Lightweight Data Store Overview + +The lightweight data store is applicable to access and persistence operations on the data in key-value pairs. When an application accesses a lightweight store instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files. + +## Basic Concepts + +- **Key-Value data structure** + + A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified. + +- **Non-relational databases** + + A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) database management properties of relational data transactions. The data in a non-relational database is independent. + + +## Working Principles + +When an application loads data from a specified Preferences file to a **Preferences** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** file. + +When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the instance can be flushed to its **Preferences** file by calling the **flush()** or **flushSync()** method. + +**Figure 1** How lightweight data store works + + +![](figure/en-us_image_0000001192123772.png) + +## Constraints + +- **Preferences** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a Preferences instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner. +- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 characters. +- If the value in the key-value pairs is of the string type, it can be empty or contain a maximum of 8192 characters. diff --git a/en/device-dev/subsystems/subsys-data-storage.md b/en/device-dev/subsystems/subsys-data-storage.md new file mode 100644 index 0000000000000000000000000000000000000000..504f220b7b85bc4d942ae0b35c0ad60c295729cd --- /dev/null +++ b/en/device-dev/subsystems/subsys-data-storage.md @@ -0,0 +1,5 @@ +# Lightweight Data Store + +- **[Lightweight Data Store Overview](subsys-data-storage-overview.md)** + +- **[Lightweight Data Store Development](subsys-data-storage-guide.md)** diff --git a/en/device-dev/subsystems/subsys-data.md b/en/device-dev/subsystems/subsys-data.md new file mode 100644 index 0000000000000000000000000000000000000000..f74c8f5cf30d86ba342205b1ced63d5fa6b47804 --- /dev/null +++ b/en/device-dev/subsystems/subsys-data.md @@ -0,0 +1,4 @@ +# Data Management + +- **[RDB](subsys-data-relational-database.md)** +- **[Lightweight Data Store](subsys-data-storage.md)** diff --git a/en/device-dev/subsystems/subsys-dfx-hicollie-development.md b/en/device-dev/subsystems/subsys-dfx-hicollie-development.md new file mode 100644 index 0000000000000000000000000000000000000000..8bfeecbdde0a26de7371ec864ff9794c4a55b10f --- /dev/null +++ b/en/device-dev/subsystems/subsys-dfx-hicollie-development.md @@ -0,0 +1,194 @@ +# HiCollie Development + +- [Overview](#section3432134085116) +- [Available APIs](#section139261151145116) +- [Example](#section1589120102458) +- [How to Develop](#section13905646534) + - [C++](#section9797199145316) + - [Thread Suspension Monitoring](#section1734221332) + - [Timeout Monitoring](#section2186947140) + + +## Overview + +HiCollie provides the software watchdog function. It provides a unified framework for fault detection and fault log generation to help you locate software timeout faults resulting from system service deadlock, application main thread blocking, and service process timeout. + +## Available APIs + +**Table 1** Description of C++ APIs + + +

LTS Code

+

Version Information

+

Site

+

SHA-256 Verification Code

+

Full code base (for mini, small, and standard systems)

+

3.0

+

Download

+

Download

+

Standard system solution (binary)

+

3.0

+

Download

+

Download

+

Hi3861 solution (binary)

+

3.0

+

Download

+

Download

+

Hi3518 solution (binary)

+

3.0

+

Download

+

Download

+

Hi3516 solution-LiteOS (binary)

Version Information

+

3.0

Site

+

Download

SHA-256 Verification Code

+

Download

Full code (for mini, small, and standard systems)

+

Hi3516 solution-Linux (binary)

3.0

+

3.0

Download

+

Download

Download

+

Download

Standard system solution (binary)

+

RELEASE-NOTES

3.0

+

3.0

Download

+

Download

Download

+

-

Hi3861 solution (binary)

+

Master Code

3.0

+

Version Information

Download

+

Site

Download

+

SHA-256 Verification Code

Hi3518 solution (binary)

+

Full code base (for mini, small, and standard systems)

3.0

+

3.1 Beta

Download

+

Download

Download

+

Download

Hi3516 solution-LiteOS (binary)

+

Hi3516 standard system solution (binary)

3.0

+

3.1 Beta

Download

+

Download

Download

+

Download

Hi3516 solution-Linux (binary)

+

RK3568 standard system solution (binary)

3.0

+

3.1 Beta

Download

+

Download

Download

+

Download

RELEASE-NOTES

+

Hi3861 solution (binary)

3.0

+

3.1 Beta

Download

+

Download

-

+

Download

Master Code

+

Hi3516 solution-LiteOS (binary)

Version Information

+

3.1 Beta

Site

+

Download

SHA-256 Verification Code

+

Download

Beta version (for standard systems)

+

Hi3516 solution-Linux (binary)

2.2 Beta2

+

3.1 Beta

Download

+

Download

Download

+

Download

RELEASE-NOTES

+

RELEASE-NOTES

2.2 Beta2

+

3.1 Beta

Download

+

Download

-

+

-

Compiler Toolchain

+

Compiler Toolchain

Version Information

+

Version Information

Site

+

Site

SHA-256 Verification Code

+

SHA-256 Verification Code

Compiler toolchain

+

Compiler toolchain

-

+

-

Download

+

Download

-

+

-

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

XCollieChecker

+

virtual void CheckBlock()

+

Provides the callback of the suspension detection result.

+

Input arguments: none

+

Output arguments: none

+

Return value: none

+

XCollieChecker

+

virtual void CheckThreadBlock()

+

Provides the callback of the thread suspension detection result.

+

Input arguments: none

+

Output arguments: none

+

Return value: none

+

XCollie

+

void RegisterXCollieChecker(const sptr<XCollieChecker> &checker, unsigned int type)

+

Registers the callback of the thread suspension detection result.

+

Input arguments:

+
  • checker: Indicates the pointer to the XCollieChecker instance.
  • type: Indicates the suspension detection type. Set it to XCOLLIE_THREAD.
+

Output arguments: none

+

Return value: none

+

XCollie

+

int SetTimer(const std::string &name, unsigned int timeout, std::function<void (void *)> func, void *arg, unsigned int flag)

+

Adds timers.

+

Input arguments:

+
  • name: Indicates the timer name.
  • timeout: Indicates the timeout duration, in seconds.
  • func: Indicates the timeout callback.
  • arg: Indicates the pointer to the timeout callback.
  • flag: Indicates the timer operation type.

    XCOLLIE_FLAG_DEFAULT // Indicates the default flag, which is the combination of the other three options.

    +

    XCOLLIE_FLAG_NOOP // Calls only the timeout callback.

    +

    XCOLLIE_FLAG_LOG // Generates a timeout fault log.

    +

    XCOLLIE_FLAG_RECOVERY // Exits the process.

    +
+

Output arguments: none

+

Return value: Returns the timer ID if the operation is successful; returns -1 otherwise.

+

XCollie

+

bool UpdateTimer(int id, unsigned int timeout)

+

Updates timers.

+

Input arguments:

+
  • id: Indicates the timer ID.
  • timeout: Indicates the timeout duration, in seconds.
+

Output arguments: none

+

Return value: Returns true if the operation is successful; returns false otherwise.

+

XCollie

+

void CancelTimer(int id)

+

Cancels timers.

+

Input arguments:

+

id: Indicates the timer ID.

+

Output arguments: none

+

Return value: none

+
+ +## Example + +Print logs. + +``` +timeout: TimeoutTimer start at 1611040305 to check 1s ago + +----------StacktraceCatcher CurrentTime:2021-01-19 15:11:45 Unexecuted(-1)(LogType:Stacktrace Pid:27689 Process:XCollieTimeoutModuleTest)---------- + + +----- pid 27689 at 2021-01-19 15:11:45 ----- +Cmd line: ./XCollieTimeoutModuleTest +ABI: 'arm64' + +"XCollieTimeoutM" sysTid=27689 + #01 pc 00000000000174cc /data/test/XCollieTimeoutModuleTest +``` + +## How to Develop + +### C++ + +### Thread Suspension Monitoring + +This function requires you to implement two callback functions: **CheckBlock** and **CheckThreadBlock** of the **XCollieChecker** class. After the callbacks are implemented, you need to use the **RegisterXCollieChecker** function of the **XCollie** class to register their instances. The suspension monitoring thread periodically executes all successfully registered callbacks, checks the thread logic completion flag, and determines whether the service logic of any registered thread is suspended. + +1. Develop the source code. + + Include the **xcollie** header file in the source file. + + ``` + #include "xcollie.h" + ``` + + Add the following code to the service code: + + ``` + void MyXCollieChecker::CheckLock() + { + /* time consuming job */ + } + + void MyXCollieChecker::CheckThreadBlock() + { + /* time consuming job */ + } + + sptr checker = new MyXCollieChecker("MyXCollieChecker"); + XCollie::GetInstance().RegisterXCollieChecker(checker, + (XCOLLIE_LOCK | XCOLLIE_THREAD)); + ... + ``` + +2. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**. + + ``` + external_deps = [ "hiviewdfx:libxcollie" ] + ``` + + +### Timeout Monitoring + +You can add a maximum of 128 timers for a single process by using the **SetTimer** function. Adding timers will fail if the number of timers has reached the upper limit. + +1. Develop the source code. + + Include the **xcollie** header file in the source file. + + ``` + #include "xcollie.h" + ``` + + Add the code to add, update, and cancel timers. + + ``` + std::function callback = [](void *args) + { + /* dump helpful information */ + }; + + int id = XCollie::GetInstance().SetTimer("MyXCollieTimer", 10, callback ,nullptr, XCOLLIE_FLAG_LOG); + /* time consuming job */ + XCollie::GetInstance().UpdateTimer(id, 5); + /* time consuming job */ + XCollie::GetInstance().CancelTimer(id); + ... + ``` + +2. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**. + + ``` + external_deps = [ "hiviewdfx:libxcollie" ] + ``` + + diff --git a/en/device-dev/subsystems/subsys-dfx-hilog-lite.md b/en/device-dev/subsystems/subsys-dfx-hilog-lite.md index 8ba38a3c8a56b6037efbc407af558797eaa921f5..8581d4f00286bcf7d490e40ba3501974433c6eb7 100644 --- a/en/device-dev/subsystems/subsys-dfx-hilog-lite.md +++ b/en/device-dev/subsystems/subsys-dfx-hilog-lite.md @@ -1,4 +1,4 @@ -# Development Guidelines on HiLog\_Lite +# Development Guidelines on HiLog\_Lite - [Overview](#section775017517390) - [Available APIs](#section114412157402) @@ -6,7 +6,7 @@ ## Overview -HiLog\_Lite is the HiLog framework for Mini-System Devices \(reference memory ≥ 128 KB\) and Small-System Devices \(reference memory ≥ 1 MB\). It implements functions such as log printing, log output, and flow control. +HiLog\_Lite is the HiLog framework for Mini-System Devices \(reference memory ≥ 128 KiB\) and Small-System Devices \(reference memory ≥ 1 MiB\). It implements functions such as log printing, log output, and flow control. ## Available APIs diff --git a/en/device-dev/subsystems/subsys-dfx-hilog-rich.md b/en/device-dev/subsystems/subsys-dfx-hilog-rich.md index 762d0fca3279ccad9b9fe0a6ee6fb23871ff47e0..287e312ea2bfe4cafeac830969933f8d3a780f13 100644 --- a/en/device-dev/subsystems/subsys-dfx-hilog-rich.md +++ b/en/device-dev/subsystems/subsys-dfx-hilog-rich.md @@ -1,4 +1,4 @@ -# Development Guidelines on HiLog +# HiLog Development - [Overview](#section8154107175019) - [Available APIs](#section6748124155012) @@ -18,61 +18,68 @@ This development guide is applicable to Standard-System Devices \(reference memo **Table 1** Description of C++ and C APIs -

C++

+ - + - - - - - - - - - - - - - - - @@ -91,6 +98,11 @@ This development guide is applicable to Standard-System Devices \(reference memo diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md new file mode 100644 index 0000000000000000000000000000000000000000..3144455e1b1fadad7bca25448c421d666e6fc3ca --- /dev/null +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md @@ -0,0 +1,152 @@ +# HiSysEvent Listening + +- [Overview](#section315316685112) +- [Available APIs](#section0342191810519) +- [How to Develop](#section123181432175110) + - [C++](#section2016116181902) + + +## Overview + +HiSysEvent supports listening for events across processes. You can register a listener to listen for concerned events on a real-time basis. For example, you can enable the battery module to listen for power consumption event for power usage analysis. + +## Available APIs + +**Table 1** HiSysEvent listener APIs + + +

C++

C

+
  

C

Class

+

Class

API

+

API

API/Macro

+

API/Macro

HiLog

+

HiLog

+

+

+

+

+

+

int Debug(const HiLogLabel &label, const char *fmt, ...)

+

int Debug(const HiLogLabel &label, const char *fmt, ...)

HILOG_DEBUG(type, ...)

+

HILOG_DEBUG(type, ...)

int Info(const HiLogLabel &label, const char *fmt, ...)

HILOG_INFO(type, ...)

+

HILOG_INFO(type, ...)

int Warn(const HiLogLabel &label, const char *fmt, ...)

HILOG_WARN(type, ...)

+

HILOG_WARN(type, ...)

int Error(const HiLogLabel &label, const char *fmt, ...)

HILOG_ERROR(type, ...)

+

HILOG_ERROR(type, ...)

int Fatal(const HiLogLabel &label, const char *fmt, ...)

HILOG_FATAL(type, ...)

+

HILOG_FATAL(type, ...)

NA

int HiLogPrint(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...)

+

int HiLogPrint(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...)

boolean IsLoggable(unsigned int domain, const char *tag, LogLevel level)

bool HiLogIsLoggable(unsigned int domain, const char *tag, LogLevel level)

+

bool HiLogIsLoggable(unsigned int domain, const char *tag, LogLevel level)

HiLogLabel

+

HiLogLabel

struct HiLogLabel

+

struct HiLogLabel

LOG_DOMAIN

+

LOG_DOMAIN

LOG_TAG

HiLog

+

+

+

+

+

int Debug(const HiLogLabel &label, const char *fmt, ...)

+ + + + + + + + + + +

API

+

Description

+

int HiSysEventManager::AddEventListener(std::shared_ptr<HiSysEventSubscribeCallBackBase> listener, std::vector<struct ListenerRule>& rules)

+

Registers a listener for system events. You can listen for certain events by specifying rules.

+

Input arguments:

+
  • listener: callback object for system events.
  • rules: rules for event listening.
+

Return values

+
  • 0: Repeated registration is successful.
  • 1: Initial registration is successful.
  • Other values: Registration has failed.
+

void HiSysEventManager::RemoveListener(std::shared_ptr<HiSysEventSubscribeCallBackBase> listener)

+

Removes the listener for system events.

+

Input arguments:

+
  • listener: callback object for system events.
+

Return value: none

+
+ +**Table 2** HiSysEvent listener rules + + + + + + + + + + + + + + + + +

Attribute

+

Description

+

uint32_t ruleType

+

Rule type. The matching scope includes domain and eventName. The value can be any of the following:

+
  • 1: whole word matching.
  • 2: prefix matching.
  • 3: regular expression matching.
  • Other values: invalid matching mode.
+

std::string domain

+
  • domain: domain to which the event belongs. By default, an empty string indicates that the domain is successfully matched.
+

std::string eventName

+
  • eventName: event name. By default, an empty string indicates that the event name is successfully matched.
+
+ +**Table 3** HiSysEvent callback object + + + + + + + + + + +

API

+

Description

+

void HiSysEventSubscribeCallBackBase::OnHandle(const std::string& domain, const std::string& eventName, const int eventType, const std::string& eventDetail)

+

Callback object for system events.

+

Input arguments:

+
  • domain: domain to which the event belongs.
  • eventName: event name.
  • eventType: event type.
  • eventDetail: JSON string containing event information.
+

Return value: none

+
+ +## How to Develop + +### **C++** + +In this example, you'll be instructed to register a listener for all system events that belong to the **HIVIEWDFX** domain. + +1. Develop the source code. + + - Import the corresponding header file: + + hisysevent\_manager.h + + - Implement the callback API. + + HiSysEventSubscribeCallBackBase::OnHandle\(const std::string& domain, const std::string& eventName, const int eventType, const std::string& eventDetail\) + + - Register a callback object. + + HiSysEventManager::AddEventListener\(std::shared\_ptr listener, std::vector& rules\) + + + ``` + // Register a listener for all system events that belong to the HIVIEWDFX domain. + #include "hisysevent_manager.h" + #include + namespace OHOS { + namespace HiviewDFX { + // Implement the API for registering a listener for callback objects. + void HiSysEventToolListener::OnHandle(const std::string& domain, const std::string& eventName, + const int eventType, const std::string& eventDetail) + { + std::cout << eventDetail << std::endl; + } + + void HiSysEventToolListener::OnServiceDied() + { + std::cout << std::string("service disconnect, exit") << std::endl; + exit(0); + } + } // namespace HiviewDFX + } // namespace OHOS + + // Register a listener for callback objects. + auto toolListener = std::make_shared(); + struct ListenerRule rule; + rule.ruleType = 1; // 1: default type + rule.domain = "HIVIEWDFX"; + std::vector sysRules; + sysRules.push_back(rule); + HiSysEventManager::AddEventListener(toolListener, sysRules); + ``` + +2. Modify the **BUILD.gn** file. + + In the **BUILD.gn** file, add the **libhisyseventmanager** library that depends on the** hisysevent\_native** component. + + ``` + external_deps = [ "hisysevent_native:libhisyseventmanager", ] + ``` + + diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging.md new file mode 100644 index 0000000000000000000000000000000000000000..b0acfd53ca0f801bfc5ffcacfbfb5751e7666762 --- /dev/null +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging.md @@ -0,0 +1,285 @@ +# HiSysEvent Logging + +- [Overview](#section77571101789) +- [Available APIs](#section13480315886) +- [How to Develop](#section112771171317) + +## Overview + +HiSysEvent provides event logging APIs for OpenHarmony to record important information of key processes during system running, helping you locate faults. In addition, you can upload the log data to the cloud for big data analytics. + +## Available APIs + +The following table lists the C++ APIs provided by the **HiSysEvent** class. + +For details about the **HiSysEvent** class, see the API reference. + +**Table 1** C++ APIs provided by HiSysEvent + + + + + + + + + + +

API

+

Description

+

template<typename... Types> static int Write(const std::string &domain, const std::string &eventName, EventType type, Types... keyValues)

+

Logs system events.

+

Input arguments:

+
  • domain: Indicates the domain related to the event. You can use a preconfigured domain or customize a domain as needed. The name of a custom domain can contain a maximum of 16 characters, including digits (0-9) and uppercase letters (A-Z). It must start with a letter.
  • eventName: Indicates the event name. The value contains a maximum of 32 characters, including digits (0 to 9), letters (A-Z), and underscore (_). It must start with a letter and cannot end with an underscore (_).
  • type: Indicates the event type. For details, see EventType.
  • keyValues: Indicates the key-value pairs of event parameters. It can be in the format of the basic data type, std::string, std::vector<basic data type>, or std:vector<std::string>. The value contains a maximum of 48 characters, including digits (0 to 9), letters (A-Z), and underscore (_). It must start with a letter and cannot end with an underscore (_). The number of parameter names cannot exceed 32.
+

Return value: Returns 0 if the operation is successful; returns a value less than 0 otherwise.

+
+ +**Table 2** Description of HiSysEvent::Domain APIs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

API

+

Description

+

static const std::string AAFWK

+

Ability management framework

+

static const std::string APPEXECFWK

+

Application framework

+

static const std::string ACCOUNT

+

Account subsystem

+

static const std::string ACE

+

ACE subsystem

+

static const std::string AI

+

AI subsystem

+

static const std::string BARRIER_FREE

+

Accessibility subsystem

+

static const std::string BIOMETRICS

+

Biometric recognition subsystem

+

static const std::string CCRUNTIME

+

C/C++ operating environment subsystem

+

static const std::string COMMUNICATION

+

Communication subsystem

+

static const std::string DEVELOPTOOLS

+

Development toolchain subsystem

+

static const std::string DISTRIBUTED_DATAMGR

+

Distributed data management subsystem

+

static const std::string DISTRIBUTED_SCHEDULE

+

Distributed scheduler subsystem

+

static const std::string GLOBAL

+

Globalization subsystem

+

static const std::string GRAPHIC

+

Graphics subsystem

+

static const std::string HIVIEWDFX

+

DFX subsystem

+

static const std::string IAWARE

+

Scheduling and resource management subsystem

+

static const std::string INTELLI_ACCESSORIES

+

Smart accessory subsystem

+

static const std::string INTELLI_TV

+

Smart TV subsystem

+

static const std::string IVI_HARDWARE

+

IVI-dedicated hardware subsystem

+

static const std::string LOCATION

+

Location subsystem

+

static const std::string MSDP

+

MSDP subsystem

+

static const std::string MULTI_MEDIA

+

Multimedia subsystem

+

static const std::string MULTI_MODAL_INPUT

+

Multimodal input subsystem

+

static const std::string NOTIFICATION

+

Common event and notification subsystem

+

static const std::string POWERMGR

+

Power management subsystem

+

static const std::string ROUTER

+

Router subsystem

+

static const std::string SECURITY

+

Security subsystem

+

static const std::string SENSORS

+

Pan-sensor subsystem

+

static const std::string SOURCE_CODE_TRANSFORMER

+

Application porting subsystem

+

static const std::string STARTUP

+

Startup subsystem

+

static const std::string TELEPHONY

+

Telephony subsystem

+

static const std::string UPDATE

+

Update subsystem

+

static const std::string USB

+

USB subsystem

+

static const std::string WEARABLE_HARDWARE

+

Wearable-dedicated hardware subsystem

+

static const std::string WEARABLE

+

Wearable-dedicated service subsystem

+

static const std::string OTHERS

+

Others

+
+ +**Table 3** Description of HiSysEvent::EventType APIs + + + + + + + + + + + + + + + + + + + +

API

+

Description

+

FAULT

+

Fault event

+

STATISTIC

+

Statistical event

+

SECURITY

+

Security event

+

BEHAVIOR

+

System behavior event

+
+ +## How to Develop + +**C++** + +1. Develop the source code. + + Include the **HiSysEvent** header file in the class definition header file or class implementation source file. For example: + + ``` + #include "hisysevent.h" + ``` + + Add the event logging code. For example, if you want to log events specific to the app start time \(**start\_app**\), then add the following code to the service implementation source file: + + ``` + HiSysEvent::Write(HiSysEvent::Domain::AAFWK, "start_app", HiSysEvent::EventType::FAULT, "app_name", "com.demo"); + ``` + +2. Configure compilation information. Specifically, add the subsystem SDK dependency to **BUILD.gn**. + + ``` + external_deps = [ "hisysevent_native:libhisysevent" ] + ``` + + diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md new file mode 100644 index 0000000000000000000000000000000000000000..979e02f2662309c172f7e66db59d9030828d060f --- /dev/null +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md @@ -0,0 +1,179 @@ +# HiSysEvent Query + +- [Overview](#section279684125212) +- [Available APIs](#section03869128521) +- [How to Develop](#section14286111855212) + - [C++](#section162045551743) + + +## Overview + +HiSysEvent provides an API for you to query system events. You can query concerned events by specifying search criteria. For example, for a power consumption module, you can query required system events for analysis. + +## Available APIs + +**Table 1** HiSysEvent query API + + + + + + + + + + +

API

+

Description

+

bool HiSysEventManager::QueryHiSysEvent(struct QueryArg& queryArg, std::vector<struct QueryRule>& queryRules, std::shared_ptr<HiSysEventQueryCallBackBase> queryCallBack)

+

Queries system events by specifying search criteria such as the time segment, event domain, and event name.

+

Input arguments:

+
  • queryArg: event query parameter.
  • queryRules: event filtering rules.
  • queryCallBack: callback object for query results.
+

Return values

+
  • true: Operation successful.
  • false: Operation failed.
+
+ +**Table 2** HiSysEvent query parameters + + + + + + + + + + + + + + + + +

Attribute

+

Description

+

long long beginTime

+

Start time.

+

long long endTime

+

End time.

+

int maxEvents

+

Maximum number of query records.

+
+ +**Table 3** HiSysEvent query rules + + + + + + + + + + + + + + + + +

Attribute

+

Description

+

uint32_t ruleType

+

Rule type. The default value is 0.

+

std::string domain;

+
  • domain: domain to which the event belongs. By default, an empty string indicates that the domain is successfully matched.
+

std::vector<std::string> eventList

+
  • eventList: event name list. By default, an empty string indicates that the event names on the list are successfully matched.
+
+ +**Table 4** HiSysEvent query callback objects + + + + + + + + + + + + + +

API

+

Description

+

void HiSysEventQueryCallBackBase::OnQuery(const ::std::vector<std::string>& sysEvent, const ::std::vector<int64_t>& seq)

+

Callback object for event query.

+

Input arguments:

+
  • sysEvent: event set.
  • seq: event sequence set.
+

Return value: none

+

void HiSysEventQueryCallBackBase::OnComplete(int32_t reason, int32_t total)

+

Callback object for completion of event query.

+

Input arguments:

+
  • reason: reason for completion of event query. The default value is 0.
  • total: total number of events returned in this query.
+

Return value: none

+
+ +## How to Develop + +### **C++** + +In this example, you'll be instructed to query all system events. + +1. Develop the source code. + + - Import the corresponding header file: + + hisysevent\_manager.h + + - Implement the callback API. + + void HiSysEventQueryCallBackBase::OnQuery\(const ::std::vector& sysEvent, const ::std::vector& seq\) + + void HiSysEventQueryCallBackBase::OnComplete\(int32\_t reason, int32\_t total\) + + - Invoke the query API in the corresponding service logic. + + HiSysEventManager::QueryHiSysEvent\(struct QueryArg& queryArg, std::vector& queryRules, std::shared\_ptr queryCallBack\) + + + ``` + // In this example, you'll query all system events. + #include "hisysevent_manager.h" + #include + + namespace OHOS { + namespace HiviewDFX { + // Implement the query callback API. + void HiSysEventToolQuery::OnQuery(const ::std::vector& sysEvent, + const ::std::vector& seq) + { + for_each(sysEvent.cbegin(), sysEvent.cend(), [](const std::string &tmp) { + std::cout << tmp << std::endl; + }); + } + + void HiSysEventToolQuery::OnComplete(int32_t reason, int32_t total) + { + return; + } + } // namespace HiviewDFX + } // namespace OHOS + + // Invoke the query callback API to obtain system events. + auto queryCallBack = std::make_shared(); + struct QueryArg args(clientCmdArg.beginTime, clientCmdArg.endTime, clientCmdArg.maxEvents); + std::vector mRules; + HiSysEventManager::QueryHiSysEvent(args, mRules, queryCallBack); + ``` + +2. Modify the **BUILD.gn** file. + + In the **BUILD.gn** file, add the **libhisyseventmanager** library that depends on the** hisysevent\_native** component. + + ``` + external_deps = [ "hisysevent_native:libhisyseventmanager", ] + ``` + + diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-tool-usage.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-tool-usage.md new file mode 100644 index 0000000000000000000000000000000000000000..65e7def2d36eb85ea7b3c088936ef20898ef59ab --- /dev/null +++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-tool-usage.md @@ -0,0 +1,41 @@ +# HiSysEvent Tool Usage + +- [Overview](#section1886702718521) +- [Usage](#section1210623418527) + +## Overview + +The HiSysEvent tool is a command line tool preconfigured in the system. You can specify search criteria to query system events that meet your requirement. Using this tool, you can debug event logging during development or query system events for fault locating. + +## Usage + +1. Run the HiSysEvent tool. + + The tool is preconfigured in the **/system/bin** directory. You can run the following command in any directory: + + ``` + hisysevent [-r | -l [-s