diff --git a/README.md b/README.md index fc832338276d73545d58daf37d0b01719fc473e0..b25f5b980ff7abba3df8236d4a69fa2838af0089 100644 --- a/README.md +++ b/README.md @@ -14,15 +14,17 @@ This repository stores device and application development documents provided by ### Latest Versions -master: the latest version. + - master: the latest version. -OpenHarmony 3.1 Beta. [Learn more](en/release-notes/OpenHarmony-v3.1-beta.md) + - OpenHarmony 3.1 Beta. [Learn more](en/release-notes/OpenHarmony-v3.1-beta.md) -OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md) + - OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md) -OpenHarmony v2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md) + This version is upgraded to OpenHarmony 3.0.1 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.1-LTS.md) -OpenHarmony 2.0 Canary. [Learn more](en/release-notes/OpenHarmony-2-0-canary.md) + - OpenHarmony v2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md) + + - OpenHarmony 2.0 Canary. [Learn more](en/release-notes/OpenHarmony-2-0-Canary.md) ### Historical Stable Versions diff --git a/docker/CHANGELOG.md b/docker/CHANGELOG.md index f09cd81c10aef593f40a0934cdc2c5aea715fbd8..9d86d5e86b9b80169494662a960e3f61d37cd825 100644 --- a/docker/CHANGELOG.md +++ b/docker/CHANGELOG.md @@ -1,3 +1,11 @@ +### 0.0.6 (2022/02/10) + +1、更新hb。 + +2、增加安装ruby。 + + + ### 0.0.5 (2021/06/21) 1、更新llvm版本从10.0.1-53907更新到10.0.1-62608,支撑ipcamera_hispark_taurus_linux编译。 diff --git a/docker/CHANGELOG_en.md b/docker/CHANGELOG_en.md index 03fcdf51fa898f88dc522dfaef873105348e62b9..a6adf956e2727dace6583fd2760e481aa470e4df 100644 --- a/docker/CHANGELOG_en.md +++ b/docker/CHANGELOG_en.md @@ -1,3 +1,11 @@ +### 0.0.5 (2021/06/21) + +1\. Updated hb. + +2\. Added the installation of ruby. + + + ### 0.0.5 (2021/06/21) 1\. Updated LLVM from 10.0.1-53907 to 10.0.1-62608. Introduced support for ipcamera\_hispark\_taurus\_linux. diff --git a/docker/Dockerfile b/docker/Dockerfile index 3c9d9c5116dbff8cde10c1c8fe099aee03cfe149..20fffa28a04fee731fcb3dee5feb90e0b26a2439 100755 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -43,16 +43,17 @@ RUN apt-get update -y \ && apt-get install gcc-arm-linux-gnueabi -y \ && apt-get install build-essential \ && apt-get install locales \ + && apt-get install ruby -y \ && locale-gen "en_US.UTF-8" \ && 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 \ - && pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple setuptools \ - && pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple kconfiglib \ - && pip3 install --trusted-host mirrors.aliyun.com -i http://mirrors.aliyun.com/pypi/simple pycryptodome \ - && pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple ecdsa \ - && python3 -m pip install --user ohos-build \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple setuptools \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple kconfiglib \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple pycryptodome \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple ecdsa \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple ohos-build \ && mkdir -p /home/tools \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/clang/10.0.1-62608/linux/llvm.tar.gz \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/hc-gen/0.65/linux/hc-gen-0.65-linux.tar \ diff --git a/docker/README.md b/docker/README.md index 44d9fe07e7bdd915691306115b8e7b8a0e84ba51..f19f4f1b592baf4a4505095507a8c9851b823a43 100755 --- a/docker/README.md +++ b/docker/README.md @@ -8,21 +8,19 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通 | Docker镜像仓库 | 标签 | 说明 | | :----------------------------------------------------------- | :------ | :----------------------------------------------------------- | -| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.5` | 已经预安装HarmonyOSOpenHarmony版本的编译环境,支持轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB)的版本构建。 | +| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.6` | 已经预安装OpenHarmony版本的编译环境,支持轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB)的版本构建。 | ### 使用方式及步骤 - 开发者在配置好开发环境后,可以通过以下步骤来使用我们提供的Docker环境,支持Ubuntu/Windows平台,下文将以Ubuntu系统为例进行使用介绍。 - -#### 方式一:从**HuaweiCloud SWR**上直接获取Docker镜像进行构建: + 开发者在配置好开发环境后,可以通过以下步骤来使用我们提供的Docker环境。详情请参见[Docker编译环境](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/gettools-acquire.md)。 1. 获取Docker镜像 ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 2. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境 ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 3. 通过如下命令启动不同平台的编译 ``` @@ -31,25 +29,3 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通 在显示的页面中通过键盘上下键选择需要编译的平台,通过回车确定选择。 hb build -f #执行编译。 ``` - - #### 方式二:通过Dockerfile 构建本地Docker镜像进行构建 -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像 - ``` - git clone https://gitee.com/openharmony/docs.git - ``` -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令 - ``` - cd docs/docker - ./build.sh - ``` -4. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境 - ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker:0.0.5 - ``` -5. 通过如下命令启动不同平台的编译 - ``` - hb set #设置工作目录。 - . #输入源码所在目录,点(.)表示当前目录。 - 在显示的页面中通过键盘上下键选择需要编译的平台,通过回车确定选择。 - hb build -f #执行编译。 - ``` diff --git a/docker/README_en.md b/docker/README_en.md index 4c11f5eac495fbb74e56f606660d66ac7123b553..708213426c4690b2c14b7eb395f04376b5254b06 100644 --- a/docker/README_en.md +++ b/docker/README_en.md @@ -8,21 +8,19 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua | Docker Image Repository | Tag | Description | | :----------------------------------------------------------- | :------ | :----------------------------------------------------------- | -| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.5` | The HarmonyOSOpenHarmony build environment has been pre-installed. This repository applies to Mini-System Devices (reference memory ≥ 128 KB) and Small-System Devices (reference memory ≥ 1 MB). | +| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.6` | The OpenHarmony build environment has been pre-installed. This repository applies to Mini-System Devices (reference memory ≥ 128 KB) and Small-System Devices (reference memory ≥ 1 MB). | ### Usage - After configuring the development environments, perform the steps below to access the Docker environment. The following steps use Ubuntu as an example (Windows is also supported). - -#### **Method 1: Obtaining the Docker image from HuaweiCloud SWR**: + After configuring the development environments, perform the steps below to access the Docker environment. 1. Obtain the Docker image. ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 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:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 3. Run the following script to start building for different platforms. ``` @@ -31,25 +29,3 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua Press the Up or Down key to select the platform to build on, then press Enter. hb build -f # Start building. ``` - - #### **Method 2: Using the Dockerfile to Build a Local Docker Image** -1. Obtain the Dockerfile script for a local Docker image. - ``` - git clone https://gitee.com/openharmony/docs.git - ``` -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: - ``` - cd docs/docker - ./build.sh - ``` -4. 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:0.0.5 - ``` -5. Run the following script to start building for different platforms. - ``` - hb set # Set the working directory. - . # Enter the directory where the source code is stored. If the code is stored in the current directory, enter a period (.). - Press the Up or Down key to select the platform to build on, then press Enter. - hb build -f # Start building. - ``` diff --git a/docker/build.sh b/docker/build.sh index e1f08d1ee475ebdda7a361522233d99aca979dd5..b67f8cf68aab99806f7c2907231393206b2dbd79 100755 --- a/docker/build.sh +++ b/docker/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:0.0.5 . +docker build -t openharmony-docker:0.0.6 . diff --git a/docker/standard/Readme-en.md b/docker/standard/Readme-en.md index b74720651bb24cd48774b6eaaf2884e21f414006..fcc5cf4339bbe2b0310f35a0e070fae848d6decf 100755 --- a/docker/standard/Readme-en.md +++ b/docker/standard/Readme-en.md @@ -6,8 +6,6 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua ### Setting Up the Docker Environment for Standard-System Devices (reference memory ≥ 128 MB) -##### **Method 1: Obtaining the Docker image from HuaweiCloud SWR**: - 1. Obtain the Docker image. ``` docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 @@ -17,22 +15,6 @@ docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-dock 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** - -1. Obtain the Dockerfile script for a local Docker image. -``` -git clone https://gitee.com/openharmony/docs.git -``` -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: -``` -cd docs/docker/standard -./build.sh -``` -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.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) diff --git a/docker/standard/Readme.md b/docker/standard/Readme.md index 2bdb472014805d6ee68af247b3dcffd152fad671..7f239102756b60e154265c3d7e767db2694469a6 100755 --- a/docker/standard/Readme.md +++ b/docker/standard/Readme.md @@ -2,12 +2,10 @@ 本文为标准系统类设备Docker使用指导,[点此查看](https://gitee.com/openharmony/docs/blob/master/docker/README.md)小型和轻量系统类设备使用指导。 -OpenHarmony的Docker镜像托管在HuaweiCloud SWR上。开发者可以通过该镜像在很大程度上简化编译前的环境配置。开发者在配置好开发环境后,通过以下步骤来使用Docker环境。本Docker支持Ubuntu/Windows平台,下文将以Ubuntu系统为例进行使用介绍。 +OpenHarmony的Docker镜像托管在HuaweiCloud SWR上。开发者可以通过该镜像在很大程度上简化编译前的环境配置。开发者在配置好开发环境后,通过以下步骤来使用Docker环境。 ### 搭建Docker环境-标准系统类设备(参考内存≥128MB) -##### 方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建: - 1. 获取Docker镜像。 ``` docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 @@ -17,22 +15,6 @@ docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-dock docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` -##### 方式二:通过Dockerfile 构建本地Docker镜像进行构建 - -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像。 -``` -git clone https://gitee.com/openharmony/docs.git -``` -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令。 -``` -cd docs/docker/standard -./build.sh -``` -3. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 -``` -docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 -``` - ### 编译源码-标准系统类设备(参考内存≥128MB) 通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。 diff --git a/en/application-dev/background-task-management/background-task-dev-guide.md b/en/application-dev/background-task-management/background-task-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..aeab15fa9cc2ab9831147299d0c6b2ed803e88ca --- /dev/null +++ b/en/application-dev/background-task-management/background-task-dev-guide.md @@ -0,0 +1,79 @@ +# Background Task Management Development + +## When to Use + +If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type. + + +## Available APIs + +``` +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +``` + +**Table 1** Main APIs of backgroundTaskManager + +| API| Description| +| -------- | -------- | +| function requestSuspendDelay(reason: string, callback: Callback<void>): **DelaySuspendInfo**; | Requests delayed suspension after the application switches to the background.
The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| +| function getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void;
function getRemainingDelayTime(requestId: number): Promise<number>; | Obtains the remaining duration before the application is suspended. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)
Two asynchronous methods are provided: callback and promise.| +| function cancelSuspendDelay(requestId: number): void; | Cancels the suspension delay. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)| + +**Table 2** Parameters in DelaySuspendInfo + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| requestId | number | Yes| ID of the suspension delay request.| +| actualDelayTime | number | Yes| Actual suspension delay duration of the application, in milliseconds.| + + +## How to Develop + +1. Request a suspension delay. + ``` + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + let myReason = 'test requestSuspendDelay'; + let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); + }); + var id = delayInfo.requestId;console.info("requestId is: " + id); + ``` + +2. Obtain the remaining duration before the application is suspended. + ``` + backgroundTaskManager.getRemainingDelayTime(id).then( res => { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); + }).catch( err => { + console.log('promise => Operation failed. Cause: ' + err.data); + }); + ``` + +3. Cancel the suspension delay. + ``` + backgroundTaskManager.cancelSuspendDelay(id); + ``` + + +## Development Examples + +``` +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +let myReason = 'test requestSuspendDelay'; +// Request a suspension delay. +let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); +}); +// Print the suspension delay information. +var id = delayInfo.requestId; +var time = delayInfo.actualDelayTime; +console.info("The requestId is: " + id); +console.info("The actualDelayTime is: " + time); +// Obtain the remaining duration before the application is suspended. +backgroundTaskManager.getRemainingDelayTime(id).then( res => { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); +}).catch( err => { + console.log('promise => Operation failed. Cause: ' + err.data); +}); +// Cancel the suspension delay. +backgroundTaskManager.cancelSuspendDelay(id); +``` diff --git a/en/application-dev/background-task-management/background-task-overview.md b/en/application-dev/background-task-management/background-task-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..3483ae70d0e05a4613f7efa031494401f867a88a --- /dev/null +++ b/en/application-dev/background-task-management/background-task-overview.md @@ -0,0 +1,35 @@ +# Background Task Management Overview + +On an OS that allows for user interaction, resources gravitate to service processes that interact with users. In other words, apart from processes that support system running, service processes that can be perceived by users have the highest priority. Therefore, background task management is applicable to service processes that cannot be perceived by users. + + +## Background Task Types + +Background tasks described in this document refer to the services that need to be continued when the respective applications or service modules are running in the background (not visible to the users). For more targeted management of background applications and service modules, OpenHarmony classifies applications and service modules into the following types: + +1. No background task: An application or service module does not need further processing when switched to the background. + +2. Transient task: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension. + +3. Continuous task: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, upload and download, device connection, and VoIP. + + +## Transient Tasks + +As mentioned above, applications and service modules with transient tasks have their suspension delayed so that their running is not affected by background lifecycle management within the specified time frame. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> Applications and service modules can request transient tasks only for temporary tasks. The time quota is 3 minutes per time and 10 minutes per day. The system allocates the time frame based on the application scenario and system status. + + +### Restrictions on Using Transient Tasks + +Adhere to the following constraints and rules when using transient tasks: + +- **When to request**: An application can request a transient task only when it is running in the foreground or before it is suspended in the background. Otherwise, the application may be suspended, resulting in request failure. By default, an application has 6–12 seconds of running time (subject to the application scenario) before it is suspended in the background. + +- **Timeout**: The system notifies the application of the suspension delay timeout by using a callback. The application must then cancel the delayed suspension or apply for delayed suspension again. Otherwise, the application will be forcibly suspended. + +- **When to cancel**: The requesting application shall cancel the request when the transient task is complete. If the request is forcibly canceled by the system, the time frame allowed for the application to run in the background will be affected. + +- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-caution.gif b/en/application-dev/background-task-management/public_sys-resources/icon-caution.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-caution.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-danger.gif b/en/application-dev/background-task-management/public_sys-resources/icon-danger.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-danger.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-note.gif b/en/application-dev/background-task-management/public_sys-resources/icon-note.gif new file mode 100644 index 0000000000000000000000000000000000000000..6314297e45c1de184204098efd4814d6dc8b1cda Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-note.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-notice.gif b/en/application-dev/background-task-management/public_sys-resources/icon-notice.gif new file mode 100644 index 0000000000000000000000000000000000000000..86024f61b691400bea99e5b1f506d9d9aef36e27 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-notice.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-tip.gif b/en/application-dev/background-task-management/public_sys-resources/icon-tip.gif new file mode 100644 index 0000000000000000000000000000000000000000..93aa72053b510e456b149f36a0972703ea9999b7 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-tip.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-warning.gif b/en/application-dev/background-task-management/public_sys-resources/icon-warning.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-warning.gif differ diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index 573baf7669768528a5aa9bc434eca886f4283db8..2fccef4e22c1f1779b7dee4cb5ccf583bfb86675 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -2,127 +2,178 @@ ## When to Use -You use audio playback APIs to convert audio data into audible analog signals, play the audio signals using output devices, and manage playback tasks. +You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks. **Figure 1** Playback status -![](figures/playback-status.png "playback-status") - - -## Available APIs - -**Table 1** APIs for audio playback - -| API| Description| -| -------- | -------- | -| media.createAudioPlayer() | Creates an **AudioPlayer** instance.| -| AudioPlayer | Provides audio playback features. For details, see the table below.| - -**Table 2** AudioPlayer methods - -| Method| Description| -| -------- | -------- | -| release() | Releases audio resources.| -| play() | Starts audio playback.| -| pause() | Pauses playback.| -| stop() | Stops playback.| -| reset()7+ | Resets the audio source to be played.| -| setVolume(vol: number) | Sets playback volume.| -| seek(timeMs: number) | Changes the playback position.| -| src:string | Defines the URI of an audio file to play.| -| state:AudioState | Defines the playback state.| -| currentTime:number | Defines the current playback position.| -| duration:number | Defines the playback duration. The value **-1** is returned if the data source does not support playback position change, for example, in the real-time streaming media scenario.| -| loop:boolean | Defines whether to loop audio playback.| -| on('play', function callback) | Subscribes to the playback start event.| -| on('pause', function callback) | Subscribes to the playback pause event.| -| on('stop', function callback) | Subscribes to the playback stop event.| -| on('reset', function callback) | Subscribes to the playback reset event.| -| on('finish',function callback) | Subscribes to the playback end event.| -| on('error', function callback) | Subscribes to the playback error event.| -| on('dataload', function callback) | Subscribes to the data loading event.| -| on('volumeChange', function callback) | Subscribes to the volume change event.| -| on('timeUpdate', function callback) | Subscribes to the progress change event.| - - -1. Create an audio player. - ``` - import media from '@ohos.multimedia.media'; - var player = media.createAudioPlayer(); - ``` - -2. Set the subscription events. - ``` - player.on('play', (err, action) => { - if (err) { - console.error('Error returned in the play() callback.'); - return; - } - console.info('Current player duration: '+ player.duration); - console.info('Current player time: ' + player.currentTime); - console.info('Current player status: '+player.state); - console.info('Pause MP3'); - player.pause(); - }); - player.on('pause', (err, action) => { - if (err) { - console.error('Error returned in the pause() callback.'); + +![en-us_image_20220117](figures/en-us_image_20220117.jpg) + +## How to Develop + +For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md). + +### Full-Process Scenario + +The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting resources, and releasing resources. + +For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_Attributes). + +```js +function SetCallBack(audioPlayer) { + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + // The playback page is ready. You can click the Play button to start the playback. + }); + audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + // The Play button is changed to the pausable state. + }); + audioPlayer.on('pause', () => { // Set the 'pause' event callback. + console.info('audio pause success'); + // The Play button is changed to the playable state. + }); + audioPlayer.on('stop', () => { // Set the 'stop' event callback. + console.info('audio stop success'); + // The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state. + }); + audioPlayer.on('reset', () => { // Set the 'reset' event callback. + console.info('audio reset success'); + // You can reconfigure the src attribute to play another audio file. + }); + audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. + if (typeof(seekDoneTime) == 'undefined') { + console.info('audio seek fail'); return; - } - console.info('Current player status: ' + player.state); - console.info('Current player time: ' + player.currentTime); - player.seek(30000); // Seek for 30 seconds. - }); - player.on('stop', (err, action) => { - if (err) { - console.error('Error returned in the stop() callback.'); - return; - } - console.info('stop callback invoked. State:' + player.state); - player.reset(); - }); - player.on('dataLoad', (err, action) => { - if (err) { - console.error('Error returned in the dataLoad() callback.'); - return; - } - console.info('dataLoad callback invoked. Current time: ' + player.currentTime); - console.info('Duration of the source:' + player.duration); - player.play(); - }); - player.on('reset', (err, action) => { - if (err) { - console.error('Error returned in the reset() callback.'); - return; - } - console.info('reset callback invoked.'); - player.release(); - }); - player.on('finish', (err, action) => { - if (err) { - console.error('Error returned in the finish() callback.'); - return; } - console.info('finish callback invoked.'); - }); - player.on('timeUpdate', (seekTime, action) => { - console.info('Seek time: ' + seekTime); - console.info('Current player time: ' + player.currentTime); - var newTime = player.currentTime; - if(newTime == 30000) { - console.info('Seek succeeded. New time: ' + newTime); - } else { - console.error('Seek failed: ', + newTime); + console.info('audio seek success, and seek time is ' + seekDoneTime); + // The playback progress bar is updated to the seek position. + }); + audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + console.info('audio volumeChange success'); + // Display the updated volume. + }); + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + console.info('audio play finish'); + }); + audioPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); + console.info(`audio error called, errCode is ${error.code}`); + console.info(`audio error called, errMessage is ${error.message}`); + }); +} + +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} + +// 1. Create an audioPlayer instance. +let audioPlayer = media.createAudioPlayer(); +SetCallBack(audioPlayer); // Set the event callbacks. +// 2. Set the URI of the audio file. +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +// 3. Play the audio. +audioPlayer.play(); // The play() method can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered. +// 4. Seek to the playback position. +audioPlayer.seek(30000); // Trigger the 'timeUpdate' event callback, and seek to 30000 ms for playback. +// 5. Set the volume. +audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. +// 6. Pause the playback. +audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. +// 7. Obtain the track information. +audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. + if (typeof (arrlist) != 'undefined') { + for (let i = 0; i < arrlist.length; i++) { + printfDescription(arrlist[i]); } - player.stop(); - }); - player.on('error', (err) => { - console.error('Player error: ${err.message}'); - }); - ``` - -3. Start playback. - ``` - var audioSourceMp3 = 'file://test.mp3'; - player.src = audioSourceMp3; - player.loop = true; - ``` + } else { + console.log(`audio getTrackDescription fail, error:${error.message}`); + } +}); +// 8. Stop playback. +audioPlayer.stop(); // Trigger the 'stop' event callback. +// 9. Reset the playback resources. +audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. +// 10. Release the resource. +audioPlayer.release(); // Release the AudioPlayer resource. +audioPlayer = undefined; +``` + +### Normal Playback Scenario + +```js +function SetCallBack(audioPlayer) { + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. + }); + audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + }); + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + console.info('audio play finish'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; + }); +} + +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. +/* Set the URI of the audio file selected by the user. */ +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +``` + +### Switching to the Next Song + +```js +function SetCallBack(audioPlayer) { + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. + }); + audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + }); + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + console.info('audio play finish'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; + }); +} + +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. +/* Set the URI of the audio file selected by the user. */ +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +/* Send the instruction to switch to the next song after a period of time. */ +audioPlayer.reset(); +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/next.mp3'; +``` + +### Looping a Song + +```js +function SetCallBack(audioPlayer) { + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. + }); + audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + }); + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + console.info('audio play finish'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; + }); +} + +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. +/* Set the URI of the audio file selected by the user. */ +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +audioPlayer.loop = true; // Set the loop playback attribute. +``` diff --git a/en/application-dev/media/figures/en-us_image_20220117.jpg b/en/application-dev/media/figures/en-us_image_20220117.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3442add1bf969cc8ea89d201cf2e6e6c42321b99 Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_20220117.jpg differ diff --git a/en/application-dev/quick-start/import-sample-to-create-project.md b/en/application-dev/quick-start/import-sample-to-create-project.md index 9287c0694679ec14bfdbda15278caf6f1531e3bf..b05970a735b5a22a45f5717436f9261e721e91dc 100644 --- a/en/application-dev/quick-start/import-sample-to-create-project.md +++ b/en/application-dev/quick-start/import-sample-to-create-project.md @@ -6,11 +6,11 @@ After the OpenHarmony SDK is configured, you can get started to develop your app by **importing a sample project**. 1. On the DevEco Studio welcome page, select **Configure** or click the ![](figures/en-us_image_0000001118018452.png) icon, and choose **Settings** \> **Version Control** \> **Git**. Then click **Test** to check whether the Git tool has been installed. - - If the tool has been installed, import a sample by referring to [2](#li5947194711181). + - If the tool has been installed, import a sample by following the instructions in Step 2. ![](figures/en-us_image_0000001118018088.png) - - If the tool hasn't been installed, click **Download and Install**. DevEco Studio will automatically download and install it. Then import a sample by referring to [2](#li5947194711181). + - If the tool hasn't been installed, click **Download and Install**. DevEco Studio will automatically download and install it. Then import a sample by following the instructions in Step 2. ![](figures/en-us_image_0000001164498191.png) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index ea1585a4aca4f2addf6631e801f0f4267a50cf05..85bf1c75e1ae29a122a70fd5d0ef47f411f9b2ca 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -15,7 +15,7 @@ - [Internationalization \(i18n\) ](js-apis-i18n.md) - Media - [Audio Management](js-apis-audio.md) - - [Media Playback and Recording](js-apis-media.md) + - [Media](js-apis-media.md) - Security - [User Authentication](js-apis-useriam-userauth.md) - Data Management diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md new file mode 100644 index 0000000000000000000000000000000000000000..5d85731dc2ee337581c5fa38d7d52d60170675d4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -0,0 +1,217 @@ +# AbilityContext + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +Implements the ability context. This module is inherited from **Context**. + + +## Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| abilityInfo | AbilityInfo | Yes| No| Ability information.| +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| + + +## startAbility + +startAbility(want: Want, callback: AsyncCallback<void>): void + +Starts an ability. This method uses a callback to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +- Example + ``` + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" + }; + this.context.startAbility(want, (error) => { + console.log("error.code = " + error.code) + }) + ``` + + +## startAbility + +startAbility(want: Want): Promise<void>; + +Starts an ability. This method uses a promise to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +- Example + ``` + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" + }; + this.context.startAbility(want) + .then((data) => { + console.log('Operation successful.') + }).catch((error) => { + console.log('Operation failed.'); + }) + ``` + + +## startAbilityForResult + +startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; + +Starts an ability. This method uses a callback to return the execution result when the ability is terminated. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| + | callback | Callback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| + + +- Example + ``` + this.context.startAbilityForResult( + {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, + (error, result) => { + console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) + console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) + } + ); + ``` + + +## startAbilityForResult + +startAbilityForResult(want: Want): Promise<AbilityResult>; + +Starts an ability. This method uses a promise to return the execution result when the ability is terminated. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| + +- Example + ``` + this.context.startAbilityForResult({bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}).then((result) => { + console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) + }, (error) => { + console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) + }) + ``` + + +## terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void; + +Terminates this ability. This method uses a callback to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringfy(err); + } + ``` + + +## terminateSelf + +terminateSelf(): Promise<void>; + +Terminates this ability. This method uses a promise to return the result. + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.terminateSelf(want).then((data) => { + console.log('success:' + JSON.stringfy(data)); + )).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); + }); + ``` + + +## terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; + +Terminates this ability. This method uses a callback to return the information to the caller of **startAbilityForResult**. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| + | callback | Callback<void> | No| Callback used to return the information.| + +- Example + ``` + this.context.terminateSelfWithResult( + { + want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, + resultCode: 100 + }, (error) => { + console.log("terminateSelfWithResult is called = " + error.code) + } + ); + ``` + + +## terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult): Promise<void>; + +Terminates this ability. This method uses a promise to return information to the caller of **startAbilityForResult**. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +- Example + ``` + this.context.terminateSelfWithResult( + { + want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, + resultCode: 100 + }).then((result) => { + console.log("terminateSelfWithResult") + } + ) + ``` diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index de50ce278c4c0e8bae9541ddec417efceb2e0c94..eb6fbc82775e1631bd852319de66b4318a1c28de 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -337,13 +337,6 @@ Enumerates the audio channels. | :----- | :------------ | :--------------- | | CHANNEL_1 | 0x1 << 0 | Channel count 1. | | CHANNEL_2 | 0x1 << 1 | Channel count 2. | -| CHANNEL_3 | 0x1 << 2 | Channel count 3. | -| CHANNEL_4 | 0x1 << 3 | Channel count 4. | -| CHANNEL_5 | 0x1 << 4 | Channel count 5. | -| CHANNEL_6 | 0x1 << 5 | Channel count 6. | -| CHANNEL_7 | 0x1 << 6 | Channel count 7. | -| CHANNEL_8 | 0x1 << 7 | Channel count 8. | - ## AudioSamplingRate8+ Enumerates the audio sampling rates. diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md new file mode 100644 index 0000000000000000000000000000000000000000..e9962bab099f10ea3a8e662d6615ba31c1c6f574 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -0,0 +1,123 @@ +# Background Task Management + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +``` + + +## Required Permissions + +None + + +## backgroundTaskManager.requestSuspendDelay + +requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo + +Requests delayed suspension after the application switches to the background. + +The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level. + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | reason | string | Yes| Reason for delayed transition to the suspended state.| + | callback | Callback<void> | Yes| Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.| + +- **Return value** + | Type| Description| + | -------- | -------- | + | [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.| + +- **Example** + ``` + let myReason = 'test requestSuspendDelay'; + let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); + }) + ``` + + +## backgroundTaskManager.getRemainingDelayTime + +getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void + +Obtains the remaining duration before the application is suspended. This method uses an asynchronous callback to return the result. + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | requestId | number | Yes| ID of the suspension delay request.| + | callback | AsyncCallback<number> | Yes| Callback used to return the remaining duration before the application is suspended, in milliseconds.| + +- **Example** + ``` + let id = 1; + backgroundTaskManager.getRemainingDelayTime(id, (err, res) => { + if(err.data === 0) { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); + } else { + console.log('promise => Operation failed. Cause: ' + err.data); + } + }) + ``` + + +## backgroundTaskManager.getRemainingDelayTime + +getRemainingDelayTime(requestId: number): Promise<number> + +Obtains the remaining duration before the application is suspended. This method uses a promise to return the result. + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | requestId | number | Yes| ID of the suspension delay request.| + +- **Return value** + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.| + +- **Example** + ``` + let id = 1; + backgroundTaskManager.getRemainingDelayTime(id).then( res => { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); + }).catch( err => { + console.log('promise => Operation failed. Cause: ' + err.data); + }) + ``` + + +## backgroundTaskManager.cancelSuspendDelay + +cancelSuspendDelay(requestId: number): void + +Cancels the suspension delay. + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | requestId | number | Yes| ID of the suspension delay request.| + +- **Example** + ``` + backgroundTaskManager.cancelSuspendDelay(id); + ``` + + +#### DelaySuspendInfo + +Provides the information about the suspension delay. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| requestId | number | Yes| ID of the suspension delay request.| +| actualDelayTime | number | Yes| Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| diff --git a/en/application-dev/reference/apis/js-apis-extension-context.md b/en/application-dev/reference/apis/js-apis-extension-context.md new file mode 100644 index 0000000000000000000000000000000000000000..be430dce1a7275fd27d7c387199c0d353b8e8d02 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-extension-context.md @@ -0,0 +1,14 @@ +# ExtensionContext + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +Implements the extension context. This module is inherited from **Context**. + + +## Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index d4430fd798d4ef558605cb65e7463d2e1c646921..dff84877c9592c93bba4f1bfed5e31cd9a957119 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,42 +1,105 @@ -# Audio Playback and Recording +# Media + +The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. + +This subsystem offers various media services covering audio and video, which provide the following capabilities: + +- Audio playback ([AudioPlayer](#audioplayer)) +- Audio recording ([AudioRecorder](#audiorecorder)) + +The following capabilities will be provided in the future: video playback, video recording, data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query. ## Modules to Import -``` +```js import media from '@ohos.multimedia.media'; ``` -## Required Permissions - -None +## media.createAudioPlayer -## media.createAudioPlayer +createAudioPlayer(): [AudioPlayer](#audioplayer) -Creates an **AudioPlayer** instance. +Creates an **AudioPlayer** instance in synchronous mode. **Return values** -| Type | Description | +| Type| Description| | --------------------------- | ------------------------------------------------------------ | -| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. | +| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. After the instance is created, you can start, pause, or stop audio playback.| + +**Example** + +```js +var audioPlayer = media.createAudioPlayer(); +``` + +## media.createAudioPlayerAsync8+ + +createAudioPlayerAsync(callback: AsyncCallback\<[AudioPlayer](#audioplayer)>): void + +Creates an **AudioPlayer** instance in asynchronous mode. This method uses a callback to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ------------------------------------------ | ---- | ------------------------------ | +| callback | AsyncCallback<[AudioPlayer](#audioplayer)> | Yes| Callback used to return the **AudioPlayer** instance created.| **Example** +```js +media.createAudioPlayerAsync((error, audio) => { + if (typeof(audio) != 'undefined') { + audioPlayer = audio; + console.info('audio createAudioPlayerAsync success'); + } else { + console.info(`audio createAudioPlayerAsync fail, error:${error.message}`); + } +}); ``` -var audioplayer = media.createAudioPlayer(); + +## media.createAudioPlayerAsync8+ + +createAudioPlayerAsync: Promise<[AudioPlayer](#audioplayer)> + +Creates an **AudioPlayer** instance in asynchronous mode. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ------------------------------------ | ----------------------------------- | +| Promise<[AudioPlayer](#audioplayer)> | Promise used to return the **AudioPlayer** instance created.| + +**Example** + +```js +function failureCallback(error) { + console.info(`audio failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`audio catchCallback, error:${error.message}`); +} + +await media.createAudioPlayerAsync.then((audio) => { + if (typeof(audio) != 'undefined') { + audioPlayer = audio; + console.info('audio createAudioPlayerAsync success'); + } else { + console.info('audio createAudioPlayerAsync fail'); + } +}, failureCallback).catch(catchCallback); ``` ## media.createAudioRecorder - createAudioRecorder(): AudioRecorder -Creates an **AudioRecorder** instance to control audio recording. +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. | +| Type| Description| +| ------------------------------- | ----------------------------------------- | +| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.| **Example** @@ -44,255 +107,486 @@ Creates an **AudioRecorder** instance to control audio recording. var audiorecorder = media.createAudioRecorder(); ``` +## MediaErrorCode8+ + +Enumerates the media error codes. + +| Name| Value| Description| +| -------------------------- | ---- | -------------------------------------- | +| MSERR_OK | 0 | The operation is successful.| +| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.| +| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform this operation.| +| MSERR_INVALID_VAL | 3 | Invalid input parameter.| +| MSERR_IO | 4 | An I/O error occurs.| +| MSERR_TIMEOUT | 5 | The operation times out.| +| MSERR_UNKNOWN | 6 | An unknown error occurs.| +| MSERR_SERVICE_DIED | 7 | Invalid server.| +| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state.| +| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version.| + +## MediaType8+ + +Enumerates the media types. + +| Name| Value| Description| +| ------------------- | ---- | ------------------ | +| MEDIA_TYPE_AUD | 0 | Media.| +| MEDIA_TYPE_VID | 1 | Video.| +| MEDIA_TYPE_SUBTITLE | 2 | Subtitle. (under development)| + +## CodecMimeType8+ + +Enumerates the codec MIME types. + +| Name| Value| Description| +| ------------ | ----------------- | ------------------------ | +| AUDIO_MPEG | "audio/mpeg" | Audio in MPEG format.| +| AUDIO_AAC | "audio/mp4a-latm" | Audio in MP4A-LATM format.| +| AUDIO_VORBIS | "audio/vorbis" | Audio in Vorbis format.| +| AUDIO_FLAC | "audio/flac" | Audio in FLAC format.| + +## MediaDescriptionKey8+ + +Enumerates the media description keys. + +| Name| Value| Description| +| ------------------------ | --------------- | ------------------------------------------------------------ | +| MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number.| +| MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).| +| MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string.| +| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms.| +| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s.| +| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel.| +| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel.| +| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.| +| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number.| +| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz.| + +## BufferingInfoType8+ + +Enumerates the buffering event types. + +| Name| Value| Description| +| ----------------- | ---- | -------------------------- | +| BUFFERING_START | 1 | Buffering starts.| +| BUFFERING_END | 2 | Buffering ends.| +| BUFFERING_PERCENT | 3 | Buffering progress, in percent.| +| CACHED_DURATION | 4 | Cache duration, in milliseconds.| + ## AudioPlayer -Manages and plays audio. Before calling a method of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. +Manages and plays audio. Before calling a method of the **AudioPlayer** class, you must call [createAudioPlayer()](#media.createaudioplayer) or [createAudioPlayerAsync()](#media.createaudioplayerasync8) to create an [AudioPlayer](#audioplayer) instance. + +For details about the audio playback demo, see [Audio Playback Development](.../media/audio-playback.md). -### Attributes +### 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. | +| Name| Type| Readable| Writable| Description| +| ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | +| src | string | Yes| Yes| Audio media URI. The mainstream audio formats (MP4, AAC, MP3, and OGG) are supported.
**Examples of supported URIs**:
1. Local absolute path: file:///data/data/ohos.xxx.xxx/files/test.mp4
![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. HTTP network playback path (under development)
3. HLS network playback path (under development)
4. FD playback (under development)
**Precautions**:
Media files can be played only after the read permission is granted.| +| loop | boolean | Yes| Yes| Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite.| +| currentTime | number | Yes| No| Current audio playback position.| +| duration | number | Yes| No| Audio duration.| +| state | [AudioState](#audiostate) | Yes| No| Audio playback state.| -### play +### play -play\(\): void +play(): void -Starts audio playback. +Starts to play audio resources. This method can be called only after the **dataLoad** event is triggered. **Example** -``` -audioplayer.src = 'file:///data/media/sounds.mp4'; -audioplayer.on('play', () => { - console.log('Playback starts.'); +```js +audioPlayer.on('play', () => { // Set the 'play' event callback. + console.log('audio play success'); }); -audioplayer.play(); +audioPlayer.play(); ``` -### pause +### pause -pause\(\): void +pause(): void Pauses audio playback. **Example** -``` -audioplayer.src = 'file:///data/media/sounds.mp4'; -audioplayer.on('pause', () => { - console.log('Playback paused.'); +```js +audioPlayer.on('pause', () => { // Set the 'pause' event callback. + console.log('audio pause success'); }); -audioplayer.pause(); +audioPlayer.pause(); ``` +### stop -### stop - -stop\(\): void +stop(): void Stops audio playback. **Example** -``` -audioplayer.src = 'file:///data/media/sounds.mp4'; -audioplayer.on('stop',() => { - console.log('Playback stopped.'); +```js +audioPlayer.on('stop', () => { // Set the 'stop' event callback. + console.log('audio stop success'); }); -audioplayer.stop(); +audioPlayer.stop(); ``` +### reset7+ + +reset(): void -### seek +Switches the audio resource to be played. -seek\(timeMs: number\): void +**Example** + +```js +audioPlayer.on('reset', () => { // Set the 'reset' event callback. + console.log('audio reset success'); +}); +audioPlayer.reset(); +``` + +### seek + +seek(timeMs: number): void Seeks to the specified playback position. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | ----------------------------- | -| timeMs | number | Yes | Playback position to seek to. | +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ------------------------------ | +| timeMs | number | Yes| Position to seek to, in milliseconds.| **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.'); - } +```js +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. + if (typeof (seekDoneTime) == 'undefined') { + console.info('audio seek fail'); + return; + } + console.log('audio seek success. seekDoneTime: ' + seekDoneTime); }); -audioplayer.seek(30000); +audioPlayer.seek(30000); // Seek to 30000 ms. ``` -### setVolume +### setVolume -setVolume\(vol: number\): void +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%). | +| 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.'); +```js +audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + console.log('audio volumeChange success'); }); -audioplayer.setVolume(1); +audioPlayer.setVolume(1); // Set the volume to 100%. ``` -### reset7+ +### release -reset\(\): void +release(): void -Switches the audio resource to be played. +Releases this **AudioPlayer** instance. **Example** -``` -audioplay.reset(); +```js +audioPlayer.release(); +audioPlayer = undefined; ``` -### release +### getTrackDescription8+ + +getTrackDescription(callback: AsyncCallback>): void -release\(\): void +Obtains the audio track information. This method uses a callback to return the result. -Releases audio resources. +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ------------------------------------------------------------ | ---- | -------------------------- | +| callback | AsyncCallback> | Yes| Callback used to return the audio track information obtained.| **Example** +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} + +audioPlayer.getTrackDescription((error, arrlist) => { + if (typeof (arrlist) != 'undefined') { + for (let i = 0; i < arrlist.length; i++) { + printfDescription(arrlist[i]); + } + } else { + console.log(`audio getTrackDescription fail, error:${error.message}`); + } +}); ``` -audioplay.release(); + +### getTrackDescription8+ + +getTrackDescription(): Promise> + +Obtains the audio track information. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ------------------------------------------------------ | ------------------------------- | +| Promise> | Promise used to return the audio track information obtained.| + +**Example** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} +function failureCallback(error) { + console.info(`audio failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`audio catchCallback, error:${error.message}`); +} + +await audioPlayer.getTrackDescription.then((arrlist) => { + if (typeof (arrlist) != 'undefined') { + arrayDescription = arrlist; + } else { + console.log('audio getTrackDescription fail'); + } +}, failureCallback).catch(catchCallback); +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} ``` -### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') +### on('bufferingUpdate')8+ -Listens for audio playback events. +on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void -on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void) +Subscribes to the audio buffering update event. **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. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to, which is 'bufferingUpdate' in this example.| +| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | Yes| Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** +```js +audioPlayer.on('bufferingUpdate', (infoType, value) => { + console.log('audio bufferingInfo type: ' + infoType); + console.log('audio bufferingInfo value: ' + value); +}); ``` -audioplayer.src = 'file://xxx/sounds.mp4'; -audioplayer.on('play', () => { - console.log('Playback starts.'); + + ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') + +on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void + +Subscribes to the audio playback events. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ---------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to. The following events are supported: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'
- The 'play' event is triggered when the [play()](#audioplayer_play) method is called and audio playback starts.
- The 'pause' event is triggered when the [pause()](#audioplayer_pause) method is called and audio playback is paused.
- The 'stop' event is triggered when the [stop()](#audioplayer_stop) method is called and audio playback stops.
- The 'reset' event is triggered when the [reset()](#audioplayer_reset) method is called and audio playback is reset.
- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- The 'finish' event is triggered when the audio playback is finished.
- The 'volumeChange' event is triggered when the [setVolume()](#audioplayer_setvolume) method is called and the playback volume is changed.| +| callback | () => void | Yes| Callback invoked when the event is triggered.| + +**Example** + +```js +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Start the playback and trigger the 'play' event callback. +}); +audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + audioPlayer.seek(30000); // Call the seek() method and trigger the 'timeUpdate' event callback. }); -audioplayer.play(); +audioPlayer.on('pause', () => { // Set the 'pause' event callback. + console.info('audio pause success'); + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. +}); +audioPlayer.on('reset', () => { // Set the 'reset' event callback. + console.info('audio reset success'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; +}); +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. + if (typeof(seekDoneTime) == "undefined") { + console.info('audio seek fail'); + return; + } + console.info('audio seek success, and seek time is ' + seekDoneTime); + audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. +}); +audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + console.info('audio volumeChange success'); + audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. +}); +audioPlayer.on('finish', () => { // Set the 'finish' event callback. + console.info('audio play finish'); + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. +}); +audioPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); + console.info(`audio error called, errCode is ${error.code}`); + console.info(`audio error called, errMessage is ${error.message}`); +}); +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; // Set the src attribute and trigger the 'dataLoad' event callback. ``` ### on('timeUpdate') on(type: 'timeUpdate', callback: Callback\): void -Listens for audio playback timestamp update events. +Subscribes to the 'timeUpdate' event. **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. | +| Name| Type| Mandatory| Description| +| -------- | ----------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to, which is 'timeUpdate' in this method.
The 'timeUpdate' event is triggered when the [seek()](#audioplayer_seek) method is called.| +| callback | Callback\ | Yes| Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful.| **Example** -``` -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.'); - } +```js +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. + if (typeof (seekDoneTime) == 'undefined') { + console.info('audio seek fail'); + return; + } + console.log('audio seek success. seekDoneTime: ' + seekDoneTime); }); -audioplayer.seek(30000); +audioPlayer.seek(30000); // Seek to 30000 ms. ``` ### on('error') on(type: 'error', callback: ErrorCallback): void -Listens for playback error events. +Subscribes to the audio playback error event. **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. | +| Name| Type| Mandatory| Description| +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio playback.| +| callback | ErrorCallback | Yes| Callback invoked when the event is triggered.| **Example** -``` -audioplayer.src = 'file:///data/sounds.mp4'; -audioplayer.on('error', (err) => { - console.info('error callback info: ' + err); +```js +audioPlayer.on('error', (error) => { // Set the error event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errCode is ${error.code}`); // Print the error code. + console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); -audioplayer.setVolume(30000); +audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. ``` - ## AudioState -Describes the audio playback state. +Describes the audio playback state. You can obtain the state through the **state** attribute. + +| Name| Type| Description| +| ------------------ | ------ | -------------- | +| idle | string | Audio playback is idle.| +| playing | string | Audio playback is in progress.| +| paused | string | Audio playback is paused.| +| stopped | string | Audio playback is stopped.| +| error8+ | string | Audio playback is in the error state.| -| Name | Description | -| ------- | -------------------------- | -| idle | Audio playback is idle. | -| playing | The audio is being played. | -| paused | Audio playback is paused. | -| stopped | Audio playback is stopped. | +## MediaDescription8+ + +### [key : string] : any + +Defines media information in key-value mode. + +| Name| Type| Description| +| ----- | ------ | ------------------------------------------------------------ | +| key | string | Key of the media information. For details about the keys, see [MediaDescriptionKey](#mediadescriptionkey8).| +| value | any | Value of the key. For details about the values, see [MediaDescriptionKey](#mediadescriptionkey8).| + +**Example** + +```js +function printfItemDescription(obj, key) { + let property = obj[key]; + console.info('audio key is ' + key); + console.info('audio value is ' + property); +} + +audioPlayer.getTrackDescription((error, arrlist) => { + if (typeof (arrlist) != 'undefined') { + for (let i = 0; i < arrlist.length; i++) { + printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. + } + } else { + console.log(`audio getTrackDescription fail, error:${error.message}`); + } +}); +``` ## AudioRecorder -Provides methods to record audio. Before calling an **AudioRecorder** method, you must use [createAudioRecorder\(\)](#mediacreateaudiorecorder) to create an **AudioRecorder** instance. +Implements audio recording. Before calling a method of the **AudioRecorder** class, you must call [createAudioRecorder()](#createaudiorecorder-audiorecorder) to create an **AudioRecorder** instance. ### prepare prepare(config: AudioRecorderConfig): void +Prepares for recording. + **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 | +| 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) - ``` +``` +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 @@ -321,6 +615,8 @@ audiorecorder.stop(); release(): void +Releases this **AudioRecorder** instance. + **Example** ``` @@ -333,7 +629,7 @@ 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. +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** @@ -345,14 +641,14 @@ audiorecorder.reset(); on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void -Listens for audio recording events. +Subscribes to the 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. | +| Name| Type| Mandatory| Description| +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when audio recording preparation is complete.
- The 'start' event is triggered when audio recording starts.
- The 'stop' event is triggered when audio recording is stopped.
- The 'release' event is triggered when the resources related to audio recording are released.
- The 'reset' event is triggered when audio recording is reset.| +| callback | function | Yes| Callback invoked when the event is triggered.| **Example** @@ -367,41 +663,44 @@ audiorecorder.on('prepare', () => { on(type: 'error', callback: ErrorCallback): void -Listens for audio recording error events. +Subscribes to the audio recording error event. **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. | +| Name| Type| Mandatory| Description| +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio recording.| +| callback | ErrorCallback | Yes| Callback invoked when the event is triggered.| + ## 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) | +| Name| Type| Mandatory| Description| +| ------------------ | --------------------------------------- | ---- | ------------------------------------------------------------ | +| audioEncoder | [AudioEncoder](#audioencoder) | No| Audio encoding format. The default value is **AAC_LC**.| +| audioEncodeBitRate | number | No| Audio encoding bit rate. 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 URI types are supported:
1. Absolute file path: file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. FD path: file://1 (fd number)| + ## AudioEncoder -Enumerates audio encoding formats. +Enumerates the audio encoding formats. + +| Name| Default Value| Description| +| ------ | ------ | ------------------------------------------------------------ | +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| -| Name | Default Value | Description | -| ------ | ------------- | ---------------------------------------------- | -| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC). | ## AudioOutputFormat -Enumerates audio output formats. +Enumerates the 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 +| Name| Default Value| Description| +| -------- | ------ | ------------------------------------------------------------ | +| MPEG_4 | 2 | MPEG-4.| +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md new file mode 100644 index 0000000000000000000000000000000000000000..fa46ef6df13d0e7bd7b4c8dd788fbe4184417488 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -0,0 +1,193 @@ +# ServiceExtensionContext + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +Implements the context that provides the capabilities and APIs of **ServiceExtension**. This class is inherited from **ExtensionContext**. + + +## startAbility + + +startAbility(want: Want, callback: AsyncCallback<void>): void; + + +Starts an ability. This method uses a callback to return the result. + + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, such as the ability name and bundle name.| + | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the method is successfully called.| + +- Example + ``` + let want = { + "bundleName": "com.example.myapp", + "abilityName": "com.example.myapp.MyAbility" + }; + this.context.startAbility(want, (err) => { + console.log('startAbility result:' + JSON.stringfy(err); + } + ``` + + +## startAbility + +startAbility(want: Want): Promise<void>; + +Starts an ability. This method uses a promise to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, such as the ability name and bundle name.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the method is successfully called.| + +- Example + ``` + let want = { + "bundleName": "com.example.myapp", + "abilityName": "com.example.myapp.MyAbility" + }; + this.context.startAbility(want).then((data) => { + console.log('success:' + JSON.stringfy(data)); + )).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); + }); + ``` + + +## terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void; + +Terminates this ability. This method uses a callback to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringfy(err); + } + ``` + + +## terminateSelf + +terminateSelf(): Promise<void>; + +Terminates this ability. This method uses a promise to return the result. + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.terminateSelf(want).then((data) => { + console.log('success:' + JSON.stringfy(data)); + )).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); + }); + ``` + + +## connectAbility + +connectAbility(want: Want, options: ConnectOptions): number; + +Connects this ability to a Service ability. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to connect to, such as the ability name and bundle name.| + | options | [ConnectOptions](#connectoptions) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| + +- Return value + | Type| Description| + | -------- | -------- | + | number | A number, based on which the connection will be interrupted.| + +- Example + ``` + let want = { + "bundleName": "com.example.myapp", + "abilityName": "com.example.myapp.MyAbility" + }; + let options = { + onConnect: function(elementName, proxy) {} + onDisConnect: function(elementName) {} + onFailed: function(code) {} + } + let connection = this.context.connectAbility(want,options); + ``` + + +## disconnectAbility + +disconnectAbility(connection: number, callback:AsyncCallback<void>): void; + +Disconnects this ability from the Service ability. This method uses a callback to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | connection | number | Yes| Number returned after **connectAbility** is called.| + | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.disconnectAbility(connection, (err) => { // connection is the return value of connectAbility. + console.log('terminateSelf result:' + JSON.stringfy(err); + } + ``` + + +## disconnectAbility + +disconnectAbility(connection: number): Promise<void>; + +Disconnects this ability from the Service ability. This method uses a promise to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | connection | number | Yes| Number returned after **connectAbility** is called.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.disconnectAbility(connection).then((data) => { // connection is the return value of connectAbility. + console.log('success:' + JSON.stringfy(data)); + )).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); + }); + ``` + + +## ConnectOptions + +Defines the **ConnectOptions** data structure. + +| Name| Description| +| -------- | -------- | +| onConnect(elementName:ElementName, remote:IRemoteObject) | Called when this ability is connected to a Service ability.| +| onDisconnect(elementName:ElementName) | Called when the peer service is abnormal or killed.| +| onFailed(code: number) | Called when the connection fails.| diff --git a/en/application-dev/reference/apis/js-apis-service-extension.md b/en/application-dev/reference/apis/js-apis-service-extension.md new file mode 100644 index 0000000000000000000000000000000000000000..22f46948c07041a90488fef30df310ddb2f1294f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-service-extension.md @@ -0,0 +1,133 @@ +# ServiceExtension + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +Provides APIs related to **ServiceExtension**. + + +## Modules to Import + +``` +import ServiceExtension from '@ohos.application.ServiceExtension'; +``` + + +## Required Permissions + +None + + +## Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service extension context, which is inherited from **ExtensionContext**.| + + +## onCreate + +onCreate(want: Want): void; + +Called when an extension is created to initialize the service logic. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| + +- Example + ``` + onCreate(want) { + console.log('onCreate, want:' + want.abilityName); + } + ``` + + +## onDestroy + +onDestroy(): void; + +Called when this extension is destroyed to clear resources. + +- Example + ``` + onDestroy() { + console.log('onDestroy'); + destory(); + } + ``` + + +## onRequest + +onRequest(want: Want, startId: number): void; + +Called after **onCreate** is invoked when an ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| + | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| + +- Example + ``` + onRequest(want: Want, startId: number) { + console.log('onRequest, want:' + want.abilityName); + } + ``` + + +## onConnect + +onConnect(want: Want): rpc.RemoteObject; + +Called after **onCreate** is invoked when an ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| + +- Return value + | Type| Description| + | -------- | -------- | + | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| + +- Example + ``` + import rpc from '@ohos.rpc' + class StubTest extends rpc.RemoteObject{ + constructor(des) { + super(des); + } + onRemoteRequest(code, data, reply, option) { + } + } + ... + onConnect(want) { + console.log('onConnect , want:' + want.abilityName); + return new StubTest("test"); + } + ``` + + +## onDisconnect + +onDisconnect(want: Want): void; + +Called when the ability is disconnected. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| + +- Example + ``` + onDisconnect(want) { + console.log('onDisconnect, want:' + want.abilityName); + } + ``` diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-caution.gif b/en/application-dev/reference/apis/public_sys-resources/icon-caution.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-caution.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-danger.gif b/en/application-dev/reference/apis/public_sys-resources/icon-danger.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-danger.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-note.gif b/en/application-dev/reference/apis/public_sys-resources/icon-note.gif new file mode 100644 index 0000000000000000000000000000000000000000..6314297e45c1de184204098efd4814d6dc8b1cda Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-note.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-notice.gif b/en/application-dev/reference/apis/public_sys-resources/icon-notice.gif new file mode 100644 index 0000000000000000000000000000000000000000..86024f61b691400bea99e5b1f506d9d9aef36e27 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-notice.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-tip.gif b/en/application-dev/reference/apis/public_sys-resources/icon-tip.gif new file mode 100644 index 0000000000000000000000000000000000000000..93aa72053b510e456b149f36a0972703ea9999b7 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-tip.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-warning.gif b/en/application-dev/reference/apis/public_sys-resources/icon-warning.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-warning.gif differ diff --git a/en/contribute/OpenHarmony-64bits-coding-guide.md b/en/contribute/OpenHarmony-64bits-coding-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..32d5a20a9e3fc7cbf11149e7324b32ba3e08ecee --- /dev/null +++ b/en/contribute/OpenHarmony-64bits-coding-guide.md @@ -0,0 +1,590 @@ +# 32- and 64-Bit Portability Coding Guide + +## About This Document + +### Purpose + +OpenHarmony aims to build an open, distributed OS framework for smart IoT devices in the full-scenario, full-connectivity, and full-intelligence era. It has the following technical features: hardware collaboration for resource sharing, one-time development for multi-device deployment, and a unified OS for flexible deployment. +OpenHarmony supports the following system types: + +1. Mini system: a device oriented to devices that have MCU processors such as ARM Cortex-M and 32-bit RISC-V. These devices have limited hardware resources. The minimum device memory is 128 KiB. +2. Small system: a device oriented to devices that have application processors such as 64-bit ARM Cortex-A. The minimum device memory is 1 MiB. +3. Standard system: a device oriented to devices that have application processors such as 64-bit ARM Cortex-A. The minimum device memory is 128 MiB. + +OpenHarmony code can run on 32- and 64-bit devices. For easier code portability, clear coding specifications are necessary. This document stipulates the specifications on code porting and 64-bit coding, helping you improve code standardization and portability. + +### Application Scope + +C and C++ code for the user space and kernel space, without distinguishing the programming language standards. + +### Differences Between 32-Bit OS and 64-Bit OS + +#### Data Type Differences + +Most 32-bit OSs use ILP32, which defines int, long, and pointer as 32 bits. Most 64-bit OSs use LP64, which defines long, long long, and pointer as 64 bits. The Windows OS uses LLP64, which defines long long and pointer as 64 bits. The table below lists the length of each primitive data type. + +| **Type**| **ILP32** | **LP64** | **LLP64** | **LP32** | **ILP64** | +| --------- | --------- | -------- | --------- | -------- | --------- | +| char | 1 | 1 | 1 | 1 | 1 | +| short | 2 | 2 | 2 | 2 | 2 | +| int | 4 | 4 | 4 | 2 | 8 | +| long | **4** | **8** | **4** | 4 | 8 | +| long long | 8 | 8 | 8 | 8 | 8 | +| float | 4 | 4 | 4 | 4 | 4 | +| double | 8 | 8 | 8 | 8 | 8 | +| size_t | **4** | **8** | **8** | 4 | 8 | +| pointer | **4** | **8** | **8** | 4 | 8 | + +The table below lists the length of `sizeof` and `print` in ILP32 and LP64 to show the differences between constants and types. + +| Type | ILP32 sizeof | ILP32 print | LP64 sizeof | LP64 print | Remarks| +| ------------------ | ------------ | ----------- | ----------- | ---------- | ------ | +| bool | 1 | %u | 1 | %u | C++ | +| char | 1 | %d or %c| 1 | %d or %c| | +| unsigned char | 1 | %u | 1 | %u | | +| short | 2 | %d | 2 | %d | | +| unsigned short | 2 | %u | 2 | %u | | +| int | 4 | %d | 4 | %d | | +| unsigned int | 4 | %u | 4 | %u | | +| long | 4 | %ld | **8** | %ld | Differences exist.| +| unsigned long | 4 | %lu | **8** | %lu | Differences exist.| +| long int | 4 | %ld | **8** | %ld | Differences exist.| +| unsigned long int | 4 | %lu | **8** | %lu | Differences exist.| +| long long | 8 | %lld | 8 | %lld | | +| unsigned long long | 8 | %llu | 8 | %llu | | +| type * | 4 | %p | **8** | %p | Differences exist.| +| pid_t | 4 | %d | 4 | %d | | +| socklen_t | 4 | %u | 4 | %u | | +| off_t | 4 | %zd | **8** | %zd | Differences exist.| +| time_t | 4 | %zd | 8 | %zd | Differences exist.| +| pthread_t | 4 | %zu | **8** | %zu | Differences exist.| +| size_t | 4 | %zu | 8 | %zu | Differences exist.| +| ssize_t | 4 | %zd | **8** | %zd | Differences exist.| + +#### Differences in Data Structure Alignment + +##### Alignment of the data structure that contains a pointer + +```c +typedef struct tagFoo { + void *p; + uint32_t i; +} Foo; +``` + +On a 32-bit OS, the pointer length is 4, **Foo** is 4-byte aligned, and **sizeof(Foo)** is 8. On a 64-bit OS, the pointer length is 8, **Foo** is 8-byte aligned, and **sizeof(Foo)** is 16. + +##### Alignment of the data structure that contains a 64-bit integer + +```c +typedef struct tagFoo { + uint64_t p; + uint32_t i; +} Foo; +``` + +Although uint64\_t has a fixed length, **sizeof(Foo)** is different due to alignment. On a 32-bit OS, **Foo** is 4-byte aligned, and **sizeof(Foo)** is 12. On a 64-bit OS, **Foo** is 8-byte aligned, and **sizeof(Foo)** is 16. The preceding statement is also true when uint64\_t is replaced by double. + +### Conventions + +**Rule**: Conventions that must be complied with during programming. + +**Rec**: Conventions that should be complied with during programming. + +## Coding Guide + +### General Principles + +#### [Rule] Follow this coding guide to write code that is applicable to both 32- and 64-bit OSs. + +[Description] OpenHarmony will run in both 32- and 64-bit environments for a long time. To ensure code consistency, you must consider code portability during coding. + +### Data Type Definition and Formatting + +#### [Rule] Use the defined data types to define variables, and avoid custom basic data types without special meanings or requirements. + +[Description] Data types with variable lengths may cause incompatibility issues on 32- and 64-bit OSs. Unified and clear data types are required. OpenHarmony defines the following primitive data types: + +| Type| ILP32 | LP64 | Print| Use Case| +| ---------------- | ----- | ----- | ------- | ------------------------------------------------------------ | +| void | - | - | - | Used only for placeholder and general pointer definition.| +| char | 1 | 1 | %c | Used for strings and arrays.| +| int8_t | 1 | 1 | %d | Used for 1-byte integers.| +| uint8_t | 1 | 1 | %u | Used for 1-byte integers.| +| int16_t | 2 | 2 | %d | Used to replace short.| +| uint16_t | 2 | 2 | %u | Used to replace unsigned short.| +| int32_t | 4 | 4 | %d | Used to replace int.| +| uint32_t | 4 | 4 | %u | Used to replace unsigned int.| +| int64_t | 8 | 8 | %PRId64 | Used to replace long long and macros.| +| uint64_t | 8 | 8 | %PRIu64 | Used to replace unsigned long long and macros.| +| float | 4 | 4 | %f | Used for single-precision floating point numbers.| +| double | 8 | 8 | %lf | Used for double-precision floating point numbers.| +| bool | 1 | 1 | %d | Used for Boolean.| +| uintptr_t | **4** | **8** | %zu | Used for pointer storage. Different lengths are defined for 32- and 64-bit OSs.| +| type * | **4** | **8** | %p | Variable-length type. It is equivalent to uintptr_t, which is recommended for type conversion.| +| nullptr_t | **4** | **8** | %p | Used for pointer initialization.| +| pid_t | 4 | 4 | %d | Built-in for the Linux kernel. It has a fixed length.| +| socklen_t | 4 | 4 | %u | Built-in for the Linux kernel. It has a fixed length.| +| off_t/time_t | **4** | **8** | %zd | Signed, variable-length type.| +| size_t/pthread_t | **4** | **8** | %zu | Unsigned, variable-length type. It is used only for compatibility of calling library functions (for example, size_t is used in an underlying API).| + +The preceding types are defined in the **stddef.h** (C) and **cstdint** (C++) standard libraries. When `#define` is used to redefine related types, the source must be one of these types. + +Do not use non-standard types unless otherwise specified. Do not define common basic types unless they have special meanings. For primitive data types used in third-party interfaces and API calling, refer to their respective rules. + +[Example] Do not customize primitive data types unless necessary. + +```c +// Do not use the following code to redefine a data type. +typedef unsigned int UINT32;// This definition is forbidden. + +// The preceding definition can be replaced by uint32_t. However, you can define a type that has a specific meaning. +typedef uint32_t DB_TABLE_ID; // This definition can be retained. +``` + +[Example] Do not use the following two types, because their lengths are different from the common sense. + +| Type| ILP32 | LP64 | PRINT | Use Case| +| -------- | ------ | ----- | ----- | ---------------------- | +| float_t | **12** | **4** | - | Improper length. Do not use it.| +| double_t | **12** | **8** | - | Improper length. Do not use it.| + +#### [Rec] Do not use custom variable-length variables. A clear description is required if they are used to adapt to platforms or third-party interfaces. + +[Description] The native types such as long, int, short, and size_t have different lengths in the 32- and 64-bit environments. This may cause code risks. If these types are used for external storage or communication, system incompatibility may occur. Therefore, do not use them unless otherwise specified. + +[Exception] Due to platform, third-party interface, or library function reasons, they can be used with a clear description. + +[Example] + +```c +long var; +// This data type is 4-byte long on a 32-bit OS and 8-byte long on a 64-bit OS. You are advised to use uint32_t or uint64_t instead. +``` + +#### [Rule] Do not use uchar to define variables. + +[Description] It is not standard to use uchar or unsigned char to define strings. Instead, use char for strings or uint8_t for unsigned integers. + +For non-ANSI character sequences involving 8-bit encoding, char is recommended. In C++, wchar can be used. + +#### [Rule] Define an integer variable that is used to store a pointer as uintptr_t. + +[Description] The uintptr_t type is used to store data of the pointer length. The length can be automatically adjusted in the 32- and 64-bits environments. + +[Example] + +```c +uintptr_t sessionPtr; + +// When the pointer is stored as a variable, both the forced type conversion and left value should be defined as uintptr_t to adapt to the length changes in different scenarios. +sessionPtr = (uintptr_t) GetMemAddress(); +``` + +#### [Rec] When the type defined by the input parameter or return value of a function does not match the variable type, exercise caution to ensure that the result is correct after conversion following the value assignment and type conversion rules. + +[Description] If type inconsistency is inevitable, convert the type with caution to ensure that the final result meets the application requirements. + +[Example] + +```c +long function (long l); +int main () { + int i = -2; + unsigned int k = 1U; + long n = function(i + k); +} +``` + +Note: The preceding code will fail to be executed on a 64-bit OS because the expression (i + k) is an unsigned 32-bit expression. When it is converted to the long type, the symbols are not extended. The result of the input parameter is incorrect. The solution is to forcibly convert one of the operands to a 64-bit type. + +#### [Rule] Use 64-bit compatible macros, such as %PRId64, %PRIu64, and %PRIx64, to print 64-bit integers. Incompatible macros, such as %d, %ld, %zd, %x, and %lx, are not allowed. + +[Description] If the data to be formatted is of the 64-bit type (defined as uint64_t), format the output as follows: + +```c +#include +#include +#include + +int main() +{ + uint64_t a = 0x1234567fffffff; + printf("a = %"PRIx64"\n", a); + return 0; +} +``` + +The preceding code can output 64-bit numbers in both 32- and 64-bit environments. If other formatting methods are used, compatibility issues may occur, as listed in the following table. + +| Formatting Method| ILP32 Build| ILP32 Result| LP64 Build| LP64 Result| Conclusion| +| ---------- | -------------- | --------- | -------------- | -------- | ---------- | +| %lx | Type mismatch alarm| Incorrect| No alarm| Correct| Incompatible| +| %zx | Type mismatch alarm| Incorrect| No alarm| Correct| Incompatible| +| %llx | No alarm| Correct| Type mismatch alarm| Correct| Incompatible| +| %p | Type mismatch alarm| Incorrect| Type mismatch alarm| Correct| Incompatible| +| %PRIx64 | No alarm| Correct| No alarm| Correct| Compatible| + +[Example]The following is an example of the type mismatch alarm information: + +```bash +# Build on a 32-bit OS +format '%lx' expects argument of type 'long unsigned int', but argument 2 has type 'uint64_t {aka long long unsigned int}' +format '%zx' expects argument of type 'size_t', but argument 2 has type 'uint64_t {aka long long unsigned int}' +format '%p' expects argument of type 'void *', but argument 2 has type 'uint64_t {aka long long unsigned int}' + +# Build on a 64-bit OS +format '%llx' expects argument of type 'long long unsigned int', but argument 2 has type 'uint64_t {aka long unsigned int}' +format '%p' expects argument of type 'void *', but argument 2 has type 'uint64_t {aka long unsigned int}' +``` + +#### [Rule] When printing type-variable data, consider the data length and reserve sufficient space during alignment. + +[Description] On a 32-bit OS, the maximum length of the pointer and size_t is 8 bits (hexadecimal) or 10 bits (decimal). On a 64-bit OS, their maximum length is 20 bits. Therefore, you need to consider the length range when printing the data. + +#### [Rule] Do not use L/UL as the suffix of constants. You can add the suffix U to indicate the unsigned int type and the suffix LL/ULL to indicate the 64-bit length. + +[Description] By default, constants without suffixes are of the int type. When L/UL is used as the suffix, the length may change on 32- and 64-bit OSs. Therefore, use LL/ULL as the suffix to ensure that the length is fixed at 64 bits in both the 32- and 64-bit environments. + +| Constant| ILP32 | LP64 | Scenario| +| -------------- | --------- | ----- | ------------------------------------------------------------ | +| 1 | 4 | 4 | The default type is int32_t, and the length is fixed.| +| 1U | 4 | 4 | The default type is uint32_t, and the length is fixed.| +| 1L | **4** | **8** | The suffix is L. The length is not fixed. Do not use this constant.| +| 1UL | **4** | **8** | The suffix is UL. The length is not fixed. Do not use this constant.| +| 1LL | 8 | 8 | The default type is int64_t. The value is a long integer, and the length is fixed at 64 bits.| +| 1ULL | 8 | 8 | The type is uint64_t, and the value is an unsigned long integer.| +| 0x7FFFFFFF | 4 | 4 | The value is an unsigned number. It can be used within the value range of int32\_t. The default type is int32\_t. | +| 0x7FFFFFFFL | **4** | **8** | The length is not fixed. Do not use this constant.| +| 0x7FFFFFFFLL | 8 | 8 | The length is fixed.| +| 0x80000000 | 4 | 4 | It can be used within the value range of uint32\_t. The type is uint32\_t.| +| 0x80000000L | **4** | **8** | The suffix is L. It can be used within the value range of uint32\_t. This constant is meaningless. Do not use it.| +| 0x80000000LL | 8 | 8 | The suffix is LL. It can be used within the value range of uint32\_t. The length is fixed.| +| 0x8000000000 | **NA or 8**| **8** | No prefix. It can be used when the value range of uint32\_t is exceeded. The compiler uses LL by default or considers the value invalid. On a 64-bit OS, the type is fixed at uint64\_t.| +| 0x8000000000L | **NA or 8**| **8** | The suffix is L. It can be used when the value range of uint32_t is exceeded. This constant is meaningless. Do not use it.| +| 0x8000000000LL | 8 | 8 | The suffix is LL. The type is uint64_t.| + +As shown in the preceding table, a constant with the L or UL suffix has different lengths in the 32- and 64-bit environments. This hinders code portability. Therefore, do not use the L or UL suffix. + +[Example] + +```c +// UL in the following definition is meaningless. It causes an error on a 32-bit OS and is unnecessary on a 64-bit OS. +#define YYY_START_ADDRESS(XXX_START_ADDR + 0x80000000UL) +``` + +#### [Rule] Use macro constants defined in the standard header file. + +[Description] The standard header files **stdint.h** (C) and **cstdint.h** (C++) contain macro constants with the maximum and minimum values. Reference these macro constants, rather than customizing new ones. + +[Example] + +```c +#include +#include + +int main() +{ + std::printf("%zu\n", sizeof(std::int64_t)); + std::printf("%s\n", PRId64); + std::printf("%+" PRId64 "\n", INT64_MIN); + std::printf("%+" PRId64 "\n", INT64_MAX); + + std::int64_t n = 7; + std::printf("%+" PRId64 "\n", n); +} +``` + +#### [Rule] Use unified definitions instead of all Fs to indicate invalid values of constants. + +[Description] The same numeric constant value may be understood differently on 32- and 64-bit OSs, since the 32-bit OS has the signed and unsigned types. Especially, if the most significant bit is 1, this bit is considered as a negative number on a 32-bit OS based on the signed type and a positive number on a 64-bit OS. Use the definitions in **typedef.h** to indicate invalid values. + +```c +// Use the definitions in typedef.h. +#define INVALID_INT8((int8_t)(-1)) +#define INVALID_UINT8((uint8_t)(-1)) +#define INVALID_INT16((int16_t)(-1)) +#define INVALID_UINT16((uint16_t)(-1)) +#define INVALID_INT32((int32_t)(-1)) +#define INVALID_UINT32((uint32_t)(-1)) +#define INVALID_INT64((int64_t)(-1)) +#define INVALID_UINT64((uint64_t)(-1)) +``` + +[Example] + +```c +// On a 32-bit OS, n is a negative number. +long n = 0xFFFFFFFF; +// On a 64-bit OS, n is a positive number. The actual value is 0x00000000FFFFFFFF. +long n = 0xFFFFFFFF; +``` + +#### [Rec] Use uint32_t to define temporary variables whose size does not exceed 32 bits. + +[Description] You do not need to pay special attention to the type of a variable. Use the default uint32_t type to minimize forced type conversions caused by type inconsistency. + +### Structure Alignment and Padding + +#### [Rule] Do not hardcode a constant to specify the variable length and structure length. Use built-in types such as **sizeof** to obtain the variable length and structure length. + +[Description] **sizeof** automatically calculates the variable length and structure length, which might be incorrect if hardcoded. In addition, the running performance will not be adversely affected since the variable length is calculated during build. + +On a 64-bit OS, 8-byte alignment is used by default. Using **sizeof()** to obtain the structure length can avoid length calculation errors caused by structure alignment. + +Pay attention to the length differences on 32- and 64-bit OSs to avoid length calculation errors. Calculate and apply for space based on the maximum length. + +[Example] **sizeof** is not used to calculate the structure length, causing insufficient memory space. + +```c +int32_t *p; +p = (int32_t *)malloc(4 * ELEMENTS_NUMBER); +// This code assumes that the pointer length is 4 bytes. However, in LP64, the pointer length is 8 bytes. + +// The correct method is to use sizeof(). +int32_t *p; +p = (int32_t *)malloc(sizeof(p) * ELEMENTS_NUMBER); +``` + +#### [Rec] In special cases, force the compiler to use a specific alignment mode on the 64-bit OS. + +[Description] If necessary, you can use the specified alignment mode to ensure code compatibility. If the pseudo-instruction **#pragma pack (n)** is used, the compiler aligns data by n bytes. If the pseudo-instruction **#pragma pack ()** is used, the compiler cancels the custom byte alignment mode. + +[Example] + +```c +#pragma pack(push) # Save the current alignment mode. +#pragma pack(1) # Set the alignment mode to 1-byte alignment. +struct test +{ + ...... +}; +#pragma pack(pop) # Restore the previous alignment mode. +``` + +#### [Rule] Uniform the message structures related to multi-device communication. For compatibility purposes, 1-byte alignment is preferred. Do not use 8-byte alignment or 64-bit data types to avoid errors during communication with a 32-bit OS. + +Note: Inter-board communication messages involve inter-board operations. The communication fails unless all software is upgraded synchronously. For the sake of compatibility, use 1-byte alignment for the existing protocols and structures and convert them into the network byte order. For new communication protocols, use 4-byte alignment for higher communication efficiency and processing performance. + +#### [Rule] Avoid structure padding for external APIs and use at least 4-byte alignment. + +[Description] If structure definitions are included in an API header file provided externally, do not pad the structures. It is recommended that natural alignment be used to avoid data holes. Use at least 4-byte alignment. + +#### [Rec] Use member names to access structure members. Do not use the offset mode. + +[Description] The offsets of data structure members are different in the 32- and 64-bit environments. Therefore, the size of each member cannot be used as the offset. A 32-bit OS does not have structures automatically padded. However, on a 64-bit OS, automatic padding may occur. + +[Example] + +```c +Struct A +{ + uint32_t a; + uint32_t *p; + uint32_t b; +}; +``` + +The offset of member b is equal to sizeof(a) + sizeof(p) on a 32-bit OS. This is not true on a 64-bit OS. The correct method is to locate the index based on the variable name. + +```c +xxx.b = 123; +``` + +If the structure definition is special, for example, if the structure is only the message header and there are other fields, then you can redefine the structure so that it does not include padding fields. + +[Example] + +```c +typedef struct { + uint32_t self; /* Structure used for alignment. */ + uint32_t brother; /* Structure used for alignment. */ + uint8_t processedFlag; /* Flag indicating whether the current node has been processed. */ + uint8_t reserve[3]; /* Reserved for 4-byte alignment. */ +} TreeNodeInfo; + +typedef struct { + TreeNodeInfo nodeInfo; /* Tree information data structure of each node */ + void *userInfo; /* User information data structure of each node */ +} TreeNode; +``` + +The **TreeNode** structure has two member structures. In the following code, the address of the first member is the initial address of the second member minus the value of sizeof (the first member). (**inUserInfo** points to the **userInfo** field in the structure.) + +```c +inTreeNodeInfo = (TreeNodeInfo *)((void *)(((char *)inUserInfo) - sizeof(TreeNodeInfo))); +``` + +The structure adopts natural alignment. Note that the length of the substructure **TreeNodeInfo** is 12 bytes on both 32- and 64-bit OSs. On a 32-bit OS, there is no padding between member structures of the **TreeNode** structure, and the structure length is 16 bytes. On a 64-bit OS, **sizeof(TreeNodeInfo)** is 12 and **sizeof(TreeNode)** is 24, which means that there is a 4-byte padding field after the substructure **TreeNodeInfo**. Therefore, when the preceding method is used to obtain the address of the previous field on a 64-bit OS, the 4-byte padding field is not calculated, causing a member access error. + +#### [Rec] When defining a structure, implement 8-byte natural alignment to save storage space and avoid padding on the premise that readability is ensured. + +[Description] If a structure can be naturally aligned, no padding is required, which effectively reduces the invalid space of the structure. You are advised to define 64-bit data types such as size_t and pointer at both ends of the structure without affecting readability. + +[Example] + +```c +// The length of the following structure is 24 bytes in natural alignment mode. +struct Foo +{ + int32_t a; + uint64_t l; + int32_t x; +} + +// After proper adjustment, the size can be reduced to 16 bytes. +struct Foo +{ + uint64_t l; + int32_t a; + int32_t x; +} +``` + +### Data Type Conversion and Calculation + +#### [Rule] Avoid implicit type conversion between different data types. If necessary, use explicit type conversion to avoid result inconsistency between the 32- and 64-bit environments. + +[Description] Exercise caution when performing operations between operands with different lengths and precisions. Pay attention to the following about implicit type conversion: + +1. When the value of a 64-bit variable is assigned to a 32-bit variable, the values of the least significant 32 bits are directly assigned, and the values of the most significant 32 bits are ignored. Then the least significant 32 bits are treated as signed or unsigned based on the left value variable type. + +2. When the value of a 32-bit variable is assigned to a 64-bit variable, sign extension is performed based on whether the 32-bit variable is signed or unsigned, and then the 64-bit variable is treated as signed or unsigned based on the variable type. + +3. For operations of signed and unsigned numbers, if the result type is not specified, the result is treated as unsigned by default. + +The preceding conversion process may cause unexpected results. Therefore, exercise caution to avoid implicit type conversion as much as possible. + +[Example] Example of the correct conversion result + +```c +int32_t t1 = -2; +int64_t t2 = 1; +int32_t t3 = t1 + t2; +printf("t3 = %d\n", t3); + +// Printed: t3 = -1 +``` + +t1 is a 32-bit number, and t2 is a 64-bit number. Before the calculation, t1 is extended to 64 bits. After the calculation, the result is a 64-bit int64_t type. The hexadecimal value stored in the memory is 0xffffffffffffffff. During the value assignment, the value is truncated into 0xffffffff. Then, the value is treated as signed, which is -1. Although the result is correct, data truncation occurs. This may not be the author's intention. + +[Example] Conversion from signed to unsigned + +```c +int64_t t1 = -1; +uint32_t t2 = t1; +printf("t2=%u", t2); + +// Printed: t2=4294967295 +``` + +t1 is a 64-bit int64_t type, which is 0xffffffffffffffff in binary mode. When this value is assigned to a 32-bit int type, the most significant 32 bits are ignored and the least significant 32 bits are displayed. The binary value is 0xffffffff, which is 4294967295 in unsigned mode. + +[Example] Conversion from 32-bit to unsigned 64-bit + +```c +int32_t t1 = -1; +uint64_t t2 = t1; +printf("t2 = %lu\n", t2); + +// Printed: t2 = 18446744073709551615 +``` + +t1 is a signed negative 32-bit number, which must be extended with signs. The most significant bits of the negative number are all fs, and the value after extension is 0xffffffffffffffff. t2 is an unsigned 64-bit number, the value of which is a large positive number. + +#### [Rule] When a pointer is used as the base address and the offset is calculated by byte, the pointer must be forcibly converted to a single-byte pointer such as uintptr_t or uint8_t *. + +[Description] If the pointer is converted to an integer of the uint32_t type, the pointer may be truncated. This will not occur if the pointer is converted to uintptr_t. The pointer can also be converted to a single-byte pointer such as uint8_t * and char *. In this case, the offset is considered as bytes. A one-byte offset will be carried out for the void * type. To clarify the type, you are advised to use the type that is more specific. + +[Example] + +```c +// Incorrect +void *pPkt = (void *)((uint32_t)MSG_GET_DATA_ADDR(msgAddr) + OFFSET); + +// Correct +void *pPkt = (void *)((uintptr_t)MSG_GET_DATA_ADDR(msgAddr) + OFFSET);// C +void *pPkt = reinterpret_cast(reinterpret_cast(MSG_GET_DATA_ADDR(msgAddr)) + OFFSET); // C++ +``` + +#### [Rule] Mutual assignment is forbidden between pointers and uint32_t, including function parameter passing. + +[Description] If the variable to be defined is a length-variable pointer, use void *. If the variable to be defined is a pointer or an integer, use uintptr_t. + +[Example] Conversion between pointers and integers + +```c +int32_t i, *p, *q; +p = &i; +q = (int32_t *) (int32_t)&i; + +// In ARM Cortex-A32, p = q; in A64-LP64, p != q +``` + +To avoid this type conflict, use uintptr_t to indicate the pointer type. + +#### [Rule] Mutual assignment is forbidden between size_t and int32_t/uint32_t, including function parameter passing. + +[Description] The variable-length type cannot be forcibly converted to the 32-bit type. + +[Example] + +```c +int32_t length = (int32_t)strlen(str); // Incorrect +``` + +strlen returns size_t (unsigned long in LP64). When the value is assigned to int32_t, truncation is inevitable. Generally, truncation occurs only when the length of **str** is greater than 2 GB. This is rare in programs. + +#### [Rule] When a large array or large `for` loop index is used on a 64-bit OS, the index type must be consistent with the subscript boundary. + +[Description] If a large array or large loop is used on a 64-bit OS, the index range may exceed 32 bits. In this case, the variable-length type or 64-bit type must be used to define the array subscript or loop variable to prevent full traversal failures caused by an incorrect variable range. + +[Example] + +```c +int64_t count = BIG_NUMBER; +for (unsigned int index = 0; index != count; index++) + ... +``` + +On a 64-bit OS, int64_t is a 64-bit type, and count is a large number. unsigned int is a 32-bit type. As a result, the loop never ends. Therefore, the index type should be changed to int64_t. + +### Bit Field and Byte Order + +#### [Rule] When defining variables based on bit fields, fully consider the basic types and alignment of bit fields to avoid calculation errors in different bit widths. + +[Description] Consider both the width of a bit field and alignment. The structure length is different in different environments. Use the name rather than direct calculation result for the value of a bit field. + +#### [Rule] On a 64-bit OS, consider the length difference caused by the shift operation and the problem that the value generated after shift is implicitly extended to 64 bits. + +[Description] During the shift operation, check whether overflow and rewind occur. Change the data type to 32-bit to avoid result inconsistency. + +[Example] + +```c +int64_t t = 1 << a; // Consider the size of a. +``` + +The maximum value of a is 32 on a 32-bit OS and 64 on a 64-bit OS. If a is a 32-bit variable, the extension to 64 bits must also be considered. + +### Third-Party Libraries and Differentiated Features + +#### [Rule] The third-party class libraries used by a 64-bit OS must support 64-bit. + +[Description] Some library functions and third-party open-source code may not fully support 64-bit. You must evaluate all involved code to ensure that it can run in the 64-bit environment. Some library functions are implemented using different APIs in the 32- and 64-bit environments. Ensure that correct APIs are used. + +[Example] In the 32-bit environment, **mmap** can be used. If the size of the memory to map exceeds 2 GB, **mmap64** is required. In the 64-bit environment, **mmap** is used. + +#### [Rule] Functionalities involving bottom-layer assembly must be debugged separately on the 32- and 64-bit OSs. + +[Description] The number and bit width of registers are different in the 32- and 64-bit environments. The debugging functionalities related to assembly must be adjusted. You must also pay attention to the code validity in the 32-bit and 64-bit environments. + +[Example] For the push-to-stack functionality of the call stack, you must write and debug the assembly code in the 32- and 64-bit environment separately. + +#### [Rule] The patch functionality must support both 32- and 64-bit instructions. + +[Description] The patch mechanism and functionalities must be adopted to the command length changes. + +#### [Rule] All tools used on a 64-bit OS must support 64-bit. + +[Description] If type inconsistency is inevitable, convert the type with caution to ensure that the final result meets the application requirements. diff --git a/en/contribute/OpenHarmony-Java-secure-coding-guide.md b/en/contribute/OpenHarmony-Java-secure-coding-guide.md index 79a5726cc1192f3faf495e7fcfa3e6f75781df39..f61c28892897c2f5a66ac2762755c78ed6433af5 100644 --- a/en/contribute/OpenHarmony-Java-secure-coding-guide.md +++ b/en/contribute/OpenHarmony-Java-secure-coding-guide.md @@ -1,4 +1,4 @@ -# OpenHarmony Java Secure Coding Guide +# Java Secure Coding Guide This document provides secure coding suggestions for Java-based development. @@ -1786,7 +1786,7 @@ public void xsltTrans(String src, String dst, String xslt) { } ``` -A security policy can be added to **TransformerFactory**. Java has a built-in blocklist for XSLT. Here some [insecure methods are disabled by setting **http://javax.xml.XMLConstants/feature/secure-processing** to **true**.](http://javax.xml.xmlconstants/feature/secure-processing属性设置为true开启防护,可以禁用一些不安全的方法。) +A security policy can be added to **TransformerFactory**. Java has a built-in blocklist for XSLT. Here some insecure methods are disabled by setting **http://javax.xml.XMLConstants/feature/secure-processing** to **true**. ## Try best to simplify the regular expression (regex) to prevent regular expression denial of service (ReDoS) attacks diff --git a/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md b/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md index 621953b338c8ca14c1e71d1a670788a544ab22aa..e5bcc1db9120dc9bc29ba91bd6b9e5d7a8f4ec08 100644 --- a/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md +++ b/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md @@ -1,4 +1,4 @@ -# OpenHarmony C&C++ Secure Coding Guide +# C&C++ Secure Coding Guide This document provides some secure coding suggestions based on the C\&C++ language to guide development. diff --git a/en/contribute/OpenHarmony-hdf-coding-guide.md b/en/contribute/OpenHarmony-hdf-coding-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b28b7591c6467b04927d06d53d276e1f69f3b00f --- /dev/null +++ b/en/contribute/OpenHarmony-hdf-coding-guide.md @@ -0,0 +1,635 @@ +# HDF Driver Coding Guide + +## About This Document + +### Purpose + +OpenHarmony aims to build an open, distributed OS framework for smart IoT devices in the full-scenario, full-connectivity, and full-intelligence era. It has the following technical features: hardware collaboration for resource sharing, one-time development for multi-device deployment, and a unified OS for flexible deployment. + +The Hardware Driver Foundation (HDF) provides the following driver framework capabilities: driver loading, driver service management, and driver message mechanism. This unified driver architecture system is designed to provide a more precise and efficient development environment, where you can perform one-time driver development for multi-system deployment. + +As such, certain coding specifications are required for the OpenHarmony driver implemented based on the HDF. This document stipulates the specifications on the driver code, helping you improve code standardization and portability. + +## Coding Guide + +### General Principles + +#### [Rule] Use the capabilities provided by the HDF to implement drivers. + +[Description] The HDF supports driver loading, driver service management, and driver message mechanism. It provides the Operating System Abstraction Layer (OSAL) and Platform Abstraction Layer (PAL) to support cross-system and cross-platform driver deployment. It also provides capabilities such as driver model abstraction, common tools, and peripheral component framework. You should develop drivers based on these capabilities to ensure that the drivers can be deployed on various devices powered by OpenHarmony. + +#### [Rule] Follow this coding guide to develop drivers that can run in both the kernel space and user space. + +[Description] Kernel-mode drivers are different from user-mode drivers in essence. They apply to different use cases. You must follow this guide during service design and development and use the HDF OSAL and PAL to shield the differences, so as to ensure that the drivers can run in both the kernel space and user space. + +#### [Rec] Include the drivers/framework/include directory instead of a subdirectory in the build script. + +[Description] The **drivers/framework/include** directory is the root directory of the header file exposed by the HDF externally. This directory contains multiple subdirectories to represent different modules such as the core framework, OSAL, and PAL. When using a header file, you are advised to include the **drivers/framework/include** directory in the build script. This avoids repeated inclusion when the script is referenced in the code. + +[Example] + +```gn +config("xxxx_private_config") { + include_dirs = [ + "//drivers/framework/include", + "//drivers/framework/include/core", # Not recommended. + ] +} +``` + +```c +#include +#include // Not recommended. +``` + +### HDF Core Framework + +#### [Rule] Implement the Bind, Init, and Release methods based on the responsibility definitions in the HdfDriverEntry object. + +[Description] The **HdfDriverEntry** object is the entry of an HDF driver. The **Bind**, **Init**, and **Release** methods have their own responsibilities. You must implement the corresponding functions based on the responsibilities. + +```c +struct HdfDriverEntry g_sampleDriverEntry = { + .moduleVersion = 1, + .moduleName = "sample_driver", + .Bind = SampleDriverBind, // Responsibility: Bind the service interface provided by the driver to the HDF. + .Init = SampleDriverInit, // Responsibility: Initialize the driver service. + .Release = SampleDriverRelease, // Responsibility: Release driver resources. It is invoked when an exception occurs. +}; + +HDF_INIT(g_sampleDriverEntry); +``` + +#### [Rule] The first member in the driver service structure must be of the IDeviceIoService type. + +[Description] The first member of the service interface defined by the driver must be of the **IDeviceIoService** type. + +[Example] + +```c +struct ISampleDriverService { + struct IDeviceIoService ioService; // The first member must be of the IDeviceIoService type. + int32_t (*FunctionA)(void); // The first service interface of the driver. + int32_t (*FunctionB)(uint32_t inputCode); // The second service interface of the driver. More service interfaces can be added here. +}; +``` + +[Example] + +```c +struct ISampleDriverService { + struct IDeviceIoService ioService; // The first member must be of the IDeviceIoService type. + void *instance; // A service instance can be encapsulated here to provide service interfaces. +}; +``` + +#### [Rule] All driver service interfaces must be bound using the Bind method of the HdfDriverEntry object. All service interfaces must be defined. They cannot be defined as null. + +[Description] The service interfaces defined by the driver are exposed externally. If a service interface is not defined or is defined as null, exceptions may occur during external invocation. + +[Example] + +```c +int32_t SampleDriverBind(struct HdfDeviceObject *deviceObject) +{ + static struct ISampleDriverService sampleDriver = { + .FunctionA = SampleDriverServiceA, + .FunctionB = NULL, // The service interface cannot be defined as null. + }; + // Bind ioService to the device object created by the HDF. + deviceObject->service = &sampleDriver.ioService; + return HDF_SUCCESS; +} +``` + +#### [Rec] Call the HdfDeviceSetClass interface in the Init method of the HdfDriverEntry object to define the driver type. + +[Description] Based on the driver type, you can classify the drivers of the current device and query the driver capabilities of the current device. For better driver management, you are advised to call **HdfDeviceSetClass** to set the driver type. + +[Example] + +```c +int32_t SampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + // Set the driver type to DISPLAY. + if (!HdfDeviceSetClass(deviceObject, DEVICE_CLASS_DISPLAY)) { + HDF_LOGE("HdfDeviceSetClass failed"); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} +``` + +### HCS + +HDF Configuration Source (HCS) describes the configuration source code of the HDF in the form of key-value pairs. It decouples configuration code from driver code, making it easy for you to manage the driver configuration. + +The driver configuration consists of the driver device description defined by the HDF and the private configuration of a driver. + +**Driver Device Description** + +The driver loading information required by the HDF comes from the driver device description. Therefore, you must add the driver device description to the **device_info.hcs** file defined by the HDF. + +#### [Rule] Before configuring a driver, determine the hardware to which the driver belongs and the deployment mode, and plan the directories and files to be configured. + +[Description] In the **vendor** directory of the OpenHarmony source code, plan the directories based on the chip vendor, development board, and configuration. The HDF driver configuration is stored in the **hdf\_config** directory. According to the hardware specifications, the **hdf\_config** directory stores kernel-mode configuration information or both kernel- and user-mode configuration information. You should determine the directory where the driver is to be configured based on the driver hardware and deployment mode. + +[Example] + +```bash +$openharmony_src_root/vendor/hisilicon/hispark_taurus/hdf_config # Directory for storing the kernel-mode configuration file. There are no user-mode configuration files. + +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf # Directory for storing the kernel-mode configuration file. +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/uhdf # Directory for storing the user-mode configuration file. +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf/device_info/device_info.hcs # Device description file of the kernel-mode driver. +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf/lcd/lcd_config.hcs # Private configuration file of the kernel-mode driver. +``` + +#### [Rule] Use existing configuration information and inherit existing configuration templates during driver configuration. + +[Description] The **host**, **device**, and **deviceNode** templates have been configured in the **device_info.hcs** file. When configuring a driver, make full use of the existing configuration information and inherit HCS features to minimize your configuration workload. + +[Example] + +``` +root { + device_info { + match_attr = "hdf_manager"; + template host { // host template + hostName = ""; + priority = 100; // Host startup priority. The value ranges from 0 to 200. A larger value indicates a lower priority. The default value 100 is recommended. If the priorities are the same, the host loading sequence cannot be ensured. + template device { // device template + template deviceNode { // deviceNode template + policy = 0; // Policy for publishing drive services. + priority = 100; // Driver startup priority. The value ranges from 0 to 200. A larger value indicates a lower priority. The default value 100 is recommended. If the priorities are the same, the device loading sequence cannot be ensured. + preload = 0; // The driver is loaded as required. + permission = 0664; // Permission for the driver to create a device node. + moduleName = ""; + serviceName = ""; + deviceMatchAttr = ""; + } + } + } + // To use the default values in the template, the node fields can be not included. + sample_host :: host { // sample_host inherits the host template. + hostName = "host0"; // Host name. The host node is a container used to store a type of drivers. + device_sample :: device { // device_sample inherits the device template. + device0 :: deviceNode { // device0 inherits the deviceNode template. + policy = 1; // Overwrite the policy in the template. + moduleName = "sample_driver"; // Driver name. The value of this field must be the same as that of moduleName in the HdfDriverEntry structure. + serviceName = "sample_service"; // Service name of the driver, which must be unique. + deviceMatchAttr = "sample_config"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. + } + } + } + } +} +``` + +#### [Rule] Use the defined types during driver model design and classification. Do not configure hosts and devices repeatedly. + +[Description] The HDF places the same type of devices in the same host. You can develop and deploy the driver functionalities of the host by layer, so that one driver has multiple nodes. The following figure shows the HDF driver model. + +![HDFDriverModel.png]( ../device-dev/driver/figures/HDFDriverModel.png) + +Place devices of the same type in the same host. When adding a device, check whether the host of the same type already exists. If such a host already exists, configure the device in the host. Do not configure the same host again. A device belongs to only one driver. Therefore, do not configure the same device in different hosts. + +#### [Rule] Set publication policies for driver services based on service rules. + +[Description] The driver service is the object of capabilities provided by the driver to external systems and is managed by the HDF in a unified manner. The HDF uses the **policy** field in the configuration file to define policies for drivers to publish services externally. The values and meanings of this field are as follows: + +```c +typedef enum { + /* The driver does not provide services.*/ + SERVICE_POLICY_NONE = 0, + /* The driver provides services for kernel-space applications. */ + SERVICE_POLICY_PUBLIC = 1, + /* The driver provides services for both kernel- and user-space applications. */ + SERVICE_POLICY_CAPACITY = 2, + /** Driver services are not published externally but can be subscribed to. */ + SERVICE_POLICY_FRIENDLY = 3, + /* Driver services are not published externally and cannot be subscribed to. */ + SERVICE_POLICY_PRIVATE = 4, + /** Invalid policy. */ + SERVICE_POLICY_INVALID +} ServicePolicy; +``` + +You must set the policies based on service rules. Do not set unnecessary policies, for example, setting user-mode publication policies for kernel-mode drivers. + +[Example] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + policy = 1; // The driver provides services for kernel-space applications. + ... + } + } + } + } +} +``` + +#### [Rule] The permission to create device nodes for a driver must match the publication policy of the driver. + +[Description] In the **device_info.hcs** file, the **permission** field specifies the permission used by the driver to create a device node. This field is a 4-digit octal number and uses the Unix file permissions, for example, 0644. This field takes effect only when the driver provides services for user-space applications (policy = 2). + +You must ensure that the publication policy of the driver service matches the device node permission. Otherwise, access to the driver service may fail or the permission of the device node may be inappropriate. + +[Example] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + policy = 2; // The driver provides services for both kernel- and user-space applications. + permission = 0640; // Recommended value + ... + } + } + } + } +} +``` + +[Counterexample] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + policy = 2; // The driver provides services for both kernel- and user-space applications. + permission = 0777; // Excessive permission. + ... + } + } + } + } +} +``` + +[Counterexample] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + policy = 1; // The driver provides services for kernel-space applications but does not create a device node. + permission = 0640; // Redundancy configuration + ... + } + } + } + } +} +``` + +#### [Rule] Configure whether to load a driver as required based on service requirements. + +[Description] In the **device_info.hcs**, **preload** specifies the driver loading mode. The values and meanings of this field are as follows: + +```c +typedef enum { + /* The driver is loaded by default during the system boot process. */ + DEVICE_PRELOAD_ENABLE = 0, + /* The driver is loaded after a quick start is complete if the system supports quick start. If the system does not support quick start, this value has the same meaning as DEVICE\_PRELOAD\_ENABLE. */ + DEVICE_PRELOAD_ENABLE_STEP2, + /* The driver is not loaded during the system boot process. When a user-mode process requests the driver service, the HDF attempts to dynamically load the driver if the driver service does not exist. */ + DEVICE_PRELOAD_DISABLE, + /** Invalid value. */ + DEVICE_PRELOAD_INVALID +} DevicePreload; +``` + +Set the **preload** field based on the service requirements. + +[Example] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + preload = 2; // The driver is loaded as required. + ... + } + } + } + } +} +``` + +#### [Rec] When the preload field is set to 0, configure the loading priority based on the service requirements. + +[Description] In the **device_info.hcs** file, the **priority** field indicates the host and driver loading priority. The value of this field is an integer ranging from 0 to 200. For drivers in different hosts, a smaller priority value of the host indicates a higher driver loading priority. For drivers in the same host, a smaller priority value of the driver indicates a higher driver loading priority. The default value of the **priority** field is 100. If this field is not set or set to the same value for different drivers, the driver loading sequence cannot be ensured. You should configure the **priority** field based on the service requirements to ensure the driver loading sequence. + +[Example] + +``` +root { + device_info { + sample_host0 { + priority = 100; + sample_device { + device0 { + preload = 0; // The driver is loaded by default. + priority = 100; // The HDF ensures that the driver is loaded before device1. + ... + } + device1 { + preload = 0; // The driver is loaded by default. + priority = 200; // The HDF ensures that the driver is loaded after device0. + ... + } + } + } + sample_host1 { + priority = 100; // The HDF does not ensure the loading sequence because this host has the same priority as sample_host0. + ... + } + } +} +``` + +**Private Configuration Information of the Driver** + +If a driver has private configurations, you can add a driver configuration file to fill in default configurations of the driver. When loading the driver, the HDF obtains the configuration information, saves it in the **property** field of **HdfDeviceObject**, and passes it to the driver through **Bind** and **Init**. + +#### [Rule] Store the private configuration files of the drivers in different directories according to the component type or module. + +[Description] You must properly plan the directory for storing private configuration files of drivers. Do not store them in the root directory. + +[Example] + +```bash +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf/sample/sample_config.hcs # Correct. The private configuration file is stored in the sample directory. + +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf/sample_config.hcs # Incorrect. The private configuration file is placed in the root directory. +``` + +#### [Rule] Add the private configuration file of a driver to the hdf.hcs file in the hdf_config directory. + +[Description] The **hdf.hcs** file summarizes the configuration information. The HDF parses the file content and loads the private configuration information of the driver to the device node during the build and runtime. Include the private configuration file of the driver in the **hdf.hcs** file to trigger driver initialization. + +[Example] + +```c +#include "device_info/device_info.hcs" +#include "sample/sample_config.hcs" // The file contains the private configuration file of a driver. + +root { + module = "hisilicon,hi35xx_chip"; +} +``` + +#### [Rule] The value of the matchAttr field in the private configuration file of the driver must be the same as that of the deviceMatchAttr field in device_info.hcs. + +[Description] The HDF associates with the driver device through the **match_attr** field. A mismatch causes a failure to obtain the private configuration information. + +[Example] + +``` +root { + sample_config { + ... + match_attr = "sample_config"; // The value of this field must be the same as that of deviceMatchAttr in device_info.hcs. + } +} +``` + +#### [Rule] Use underscores (_) in field names in the private configuration file. + +[Description] According to the naming rules in the C/C++ coding guide, use underscores (_) in field names in the private configuration file of a driver. In this way, the naming rule is satisfied during the definition of the private configuration data structure in the implementation code. It also makes unified management of the code and configuration files easier. + +[Example] + +``` +root { + sample_config { + sample_version = 1; // Use an underscore (_) in the field name. + sample_bus = "I2C_0"; + match_attr = "sample_config"; + } +} +``` + +### HCS Macros + +The private configuration information of a driver is loaded to **property** of **HdfDeviceObject**. This occupies memory space, which should be avoided for mini- and small-system devices. To minimize the memory usage, the HDF provides HCS macros to parse the private configuration information. + +#### [Rule] Use HCS macros to parse the private configuration information in memory-sensitive or cross-system scenario. + +[Description] You should specify the use cases of drivers. In memory-sensitive scenarios or if a driver needs to be used in mini-, small-, and standard-system devices, use HCS macros to parse the private configuration information for higher performance and portability. + +[Example] + +```c +#include + +#define SAMPLE_CONFIG_NODE HCS_NODE(HCS_ROOT, sample_config) + +ASSERT_EQ(HCS_PROP(SAMPLE_CONFIG_NODE, sampleVersion), 1); +ASSERT_EQ(HCS_PROP(SAMPLE_CONFIG_NODE, sample_bus), "I2C_0"); +ASSERT_EQ(HCS_PROP(SAMPLE_CONFIG_NODE, match_attr), "sample_config"); +``` + +### HDF Tools + +#### [Rule] Determine the communication scenario and HdfSbuf type. + +[Description] **HdfSbuf** is a data structure used for data transfer. This structure is classified into different types based on the communication scenario. These types are defined in the **hdf_sbuf.h** header file. + +```c +enum HdfSbufType { + SBUF_RAW = 0, /* SBUF used for communication between the user space and the kernel space. */ + SBUF_IPC, /* SBUF used for inter-process communication (IPC). */ + SBUF_IPC_HW, /* Reserved for extension. */ + SBUF_TYPE_MAX, /* Maximum value of the SBUF type. */ +}; +``` + +Determine whether the data transfer is IPC in the user space or between the user space and kernel space, and then create the corresponding **HdfSbuf** structure. + +[Example] + +```c +void SampleDispatchBetweenUserAndKernel() +{ + int32_t ret; + /* Communication between the user space and kernel space. */ + struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_RAW); + ... + ret = sample->dispatcher->Dispatch(&sample->object, CMD_SAMPLE_DISPATCH, data, NULL); + ... + HdfSBufRecycle(data); +} +``` + +[Example] + +```c++ +void SampleDispatchIpc() +{ + /* IPC */ + struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_IPC); + ... + int ret = sample->dispatcher->Dispatch(sample, CMD_SAMPLE_DISPATCH, data, nullptr); + ... + HdfSBufRecycle(data); +} +``` + +#### [Rule] Define the HDF_LOG_TAG macro when using HDF logging. + +[Description] The HDF provides the **hdf_log.h** tool ,using which you can output driver run logs. The **HDF_LOG_TAG** macro specifies the log tag. You must define this macro before printing logs. + +[Example] + +```c +#include + +#define HDF_LOG_TAG sample_driver // Define the log tag. + +int32_t SampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + HDF_LOGI("sample driver is initialized"); // Use the tool to print logs. + return HDF_SUCCESS; +} +``` + +#### [Rule] Verify the return values of the HDF methods and use the error codes provided by the HDF. + +[Description] The HDF methods have specific return values. You should verify them rather than ignoring them. The return values correspond to error codes in the **hdf_base.h** header file. Use the error codes provided by the HDF when using the HDF or implementing custom methods. + +[Example] + +```c +int32_t SampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + int32_t ret; + // Check whether the device type is successfully set. + if (!HdfDeviceSetClass(deviceObject, DEVICE_CLASS_DISPLAY)) { + HDF_LOGE("HdfDeviceSetClass failed"); + return HDF_FAILURE; + } + ret = InitDiver(); + // A custom method uses an error code provided by the HDF. + if (ret != HDF_SUCCESS) { + HDF_LOGE("init drvier is failed"); + return ret; + } + return HDF_SUCCESS; +} +``` + +### OSAL + +The HDF OSAL shields the interface differences between OpenHarmony subsystems and provides unified OS interfaces, including memory management, threads, mutexes, spin locks, semaphores, timers, files, IRQ, time, atoms, firmware, and I/O operation modules. + +#### [Rule] Use OS interfaces through the OSAL for drivers used across mini-, small-, and standard-system devices. + +[Description] The OSAL shields the differences between OS interfaces. You should operate these OS interfaces based on the OSAL to ensure that drivers can run on different types of systems. + +[Example] + +```c +#include +#include + +struct DevHandle *SampleInit(void) +{ + struct DevHandle *handle = (struct DevHandle *)OsalMemCalloc(sizeof(struct DevHandle)); + if (handle == NULL) { + HDF_LOGE("OsalMemCalloc handle failed"); + return NULL; + } + return handle; +} +``` + +[Example] + +```c +#include + +void SampleSleep(uint32_t timeMs) +{ + OsalMSleep(timeMs); +} +``` + +### PAL + +The HDF PAL abstracts platform drivers and provides unified operation interfaces for modules such as the GPIO, I2C, SPI, UART, RTC, SDIO, eMMC, DSI, PWM, and watchdog. + +#### [Rule] Use platform drivers across mini, small, and standard systems through the PAL. + +[Description] The PAL masks the differences between platform driver interfaces of different system types. You should operate these interfaces based on PAL to ensure that drivers can run on different types of systems. + +[Example] + +```c +#include +#include +#include +#include + +static uint32_t g_irqCnt; + +/* Sample function of the GPIO IRQ service */ +static int32_t SampleGpioIrqHandler(uint16_t gpio, void *data) +{ + HDF_LOGE("%s: irq triggered, on gpio:%u, data=%p", __func__, gpio, data); + g_irqCnt++; /* If the IRQ function is triggered, the number of global counters is incremented by 1. */ + return GpioDisableIrq(gpio); +} + +/* GPIO sample function */ +static int32_t SampleGpioIrqEdge(void) +{ + int32_t ret; + uint16_t valRead; + uint16_t mode; + uint16_t gpio = 83; // Number of the GPIO pin to test + uint32_t timeout; + + /* Set the output direction for the pin. */ + ret = GpioSetDir(gpio, GPIO_DIR_OUT); + ... + /* Disable the IRP of this pin. */ + ret = GpioDisableIrq(gpio); + ... + /* Set the IRR function for the pin. The trigger mode is both rising edge and falling edge. */ + mode = OSAL_IRQF_TRIGGER_RISING | OSAL_IRQF_TRIGGER_FALLING; + ret = GpioSetIrq(gpio, mode, SampleGpioIrqHandler, NULL); + ... + /* Enable the IRQ for this pin. */ + ret = GpioEnableIrq(gpio); + ... + g_irqCnt = 0; /* Reset the global counter. */ + timeout = 0; /* Reset the waiting time. */ + /* Wait for the IRQ function of this pin to trigger. The timeout duration is 1000 ms. */ + while (g_irqCnt <= 0 && timeout < 1000) { + ret = GpioRead(gpio, &valRead); + ... + ret = GpioWrite(gpio, (valRead == GPIO_VAL_LOW) ? GPIO_VAL_HIGH : GPIO_VAL_LOW); + ... + OsalMDelay(200); // Wait for an interrupt to be triggered. + timeout += 200; + } + ret = GpioUnSetIrq(gpio); + ... + return (g_irqCnt > 0) ? HDF_SUCCESS : HDF_FAILURE; +} +``` diff --git a/en/contribute/code-contribution.md b/en/contribute/code-contribution.md index 923c335c3754c54d8e82246eb1686ea2a69b9520..2b00657ca8b0fdf889c71e009b4968b06788d3f3 100644 --- a/en/contribute/code-contribution.md +++ b/en/contribute/code-contribution.md @@ -8,6 +8,8 @@ - [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.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. @@ -17,6 +19,8 @@ Develop, review, and test code following the OpenHarmony coding standards. Make - [JavaScript Coding Style Guide](OpenHarmony-JavaScript-coding-style-guide.md) - [Python Coding Style Guide](https://pep8.org/) - [C&C++ Secure Coding Guide](OpenHarmony-c-cpp-secure-coding-guide.md) +- [HDF Driver Coding Guide](OpenHarmony-Java-secure-coding-guide.md) +- [32- and 64-Bit Portability Coding Guide](OpenHarmony-64bits-coding-guide.md) - [Java Secure Coding Guide](OpenHarmony-Java-secure-coding-guide.md) - [Logging Guide](OpenHarmony-Log-guide.md) @@ -28,6 +32,6 @@ For details, see [Contribution Process](contribution-process.md). - [Security Issue Handling and Release Processes](https://gitee.com/openharmony/security/blob/master/en/security-process/README.md) -- [OpenHarmony Security and Disclosure Statement](https://gitee.com/openharmony/security/blob/master/en/security-process/security-disclosure.md) +- [OpenHarmony Security Vulnerability Notice](https://gitee.com/openharmony/security/blob/master/en/security-process/security-disclosure.md) diff --git a/en/device-dev/get-code/gettools-acquire.md b/en/device-dev/get-code/gettools-acquire.md index 4b00335c966bbedd4be221e0aaab63d4212653d5..27055822bc419cf22a635389b6c3765a8a54b711 100644 --- a/en/device-dev/get-code/gettools-acquire.md +++ b/en/device-dev/get-code/gettools-acquire.md @@ -30,7 +30,7 @@ OpenHarmony provides the following two types of Docker environments for you to q

swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker

-

0.0.5

+

0.0.6

Standard system

@@ -60,6 +60,7 @@ OpenHarmony provides the following two types of Docker environments for you to q + ## Preparations Before using the Docker environment, perform the following operations: @@ -77,12 +78,10 @@ The Docker image of OpenHarmony is hosted on [HUAWEI CLOUD SWR](https://console ### Setting Up the Docker Environment for Mini-System Devices \(reference memory ≥ 128 KB\) and Small-System Devices \(reference memory ≥ 1 MB\) -**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR** - 1. Obtain the Docker image. ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 2. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: @@ -90,43 +89,13 @@ The Docker image of OpenHarmony is hosted on [HUAWEI CLOUD SWR](https://console Run the following command in Ubuntu: ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 - ``` - - Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\): - - ``` - docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 - ``` - - -**Method 2: Using the Dockerfile to Build a Local Docker Image** - -1. Obtain the Dockerfile script for a local Docker image. - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: - - ``` - cd docs/docker - ./build.sh - ``` - -3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: - - Run the following command in Ubuntu: - - ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\): ``` - docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` @@ -164,8 +133,6 @@ hb set ### Setting Up the Docker Environment for Standard-System Devices \(reference memory ≥ 128 MB\) -**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR** - 1. Obtain the Docker image. ``` @@ -179,28 +146,6 @@ hb set ``` -**Method 2: Using the Dockerfile to Build a Local Docker Image** - -1. Obtain the Dockerfile script for a local Docker image. - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: - - ``` - cd docs/docker/standard - ./build.sh - ``` - -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.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\). @@ -209,7 +154,7 @@ Run the following script to start building for standard-system devices \(referen ./build.sh --product-name {product_name} --ccache ``` -**product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300 and RK3568. +**product\_name** indicates the platform supported by the current distribution, for example, Hi3516DV300 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/quick-start/quickstart-standard-docker-environment.md b/en/device-dev/quick-start/quickstart-standard-docker-environment.md index 34d557772b9d5a80846bf587cd38348f57084abd..9374bb781fcdcd4c8a58d3070648e74756f3073c 100644 --- a/en/device-dev/quick-start/quickstart-standard-docker-environment.md +++ b/en/device-dev/quick-start/quickstart-standard-docker-environment.md @@ -61,8 +61,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. ## Obtaining the Docker Environment -**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR** - 1. Obtain the Docker image. ``` @@ -76,28 +74,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. ``` -**Method 2: Using the Dockerfile to Build a Local Docker Image** - -1. Obtain the Dockerfile script for a local Docker image. - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: - - ``` - cd docs/docker/standard - ./build.sh - ``` - -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.7 - ``` - - ## Building Source Code 1. Run the following script to start building for standard-system devices \(reference memory ≥ 128 MB\). @@ -106,7 +82,7 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. ./build.sh --product-name {product_name} --ccache ``` - **product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300, rk3568. + **product\_name** indicates the platform supported by the current distribution, for example, Hi3516DV300, 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/subsys-data-relational-database-guide.md b/en/device-dev/subsystems/subsys-data-relational-database-guide.md index 44a0b1829249264fb99aff7cf998dd6a4de43b38..d668fc922079dfa5b38633d6c7a9c65a88351942 100644 --- a/en/device-dev/subsystems/subsys-data-relational-database-guide.md +++ b/en/device-dev/subsystems/subsys-data-relational-database-guide.md @@ -68,7 +68,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th 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.
| + | 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 delete conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.
| - Updating data diff --git a/en/readme/DeviceProfile.md b/en/readme/DeviceProfile.md new file mode 100644 index 0000000000000000000000000000000000000000..29653fb13b515c0c88d00f1ca819745f1a1a4397 --- /dev/null +++ b/en/readme/DeviceProfile.md @@ -0,0 +1,189 @@ +# DeviceProfile + +## Introduction + +DeviceProfile is used to manage device hardware capabilities and system software features. A typical device profile includes the device type, device name, OS type, and OS version. By allowing quick access to local and remote device profiles, DeviceProfile lays the foundation for initiating distributed services. It provides the following features: + +- Querying, inserting, and deleting local device profile information +- Querying remote device profile information +- Synchronizing profile information across devices +- Subscribing to remote device profile changes + +Below is the architecture of the DeviceProfile subsystem. + +## Architecture + +**Figure 1** Architecture of the DeviceProfile subsystem + +![](figures/dp-architecture.png) + +## Directory Structure + +The main code directory structure of DeviceProfile is as follows: + +``` +├── interfaces +│   └── innerkits +│ └── distributeddeviceprofile // Internal APIs +├── ohos.build +├── sa_profile // SAID profile +│   ├── 6001.xml +│   └── BUILD.gn +├── services +│   └── distributeddeviceprofile +│   ├── BUILD.gn +│   ├── include +│ │ ├── contentsensor // Header file for content sensor data collection +│ │ ├── dbstorage // Header file for database operations +│ │ ├── devicemanager // Header file for device management +│ │ └── subscribemanager // Header file for subscription management +│   ├── src +│ │ ├── contentsensor // Implementation of content sensor data collection +│ │ ├── dbstorage // Implementation of database operations +│ │ ├── devicemanager // Implementation of device management +│ │ ├── subscribemanager // Implementation of subscription management +│ └── test // Test cases +└── tools + └── dp // Auxiliary test tool +``` + +## Constraints + +- The devices between which you want to set up a connection must be in the same LAN. +- Before setting up a connection between two devices, you must bind the devices. For details about the binding process, see relevant descriptions in the Security subsystem readme file. + +## Usage + +### Querying Profile Information + +* Parameters of GetDeviceProfile + +| Name| Type| Mandatory| Description| +| --------- | ---------------------------- | ---- | ----------------------------------- | +| deviceId | std::string | Yes| ID of the device whose profile is to be queried. A null value indicates the local device.| +| serviceId | std::string | Yes| Service ID (ID of the service data record).| +| profile | ServiceCharacteristicProfile | Yes| Return value.| + +* Example + +```c++ +// Declare the return value. +ServiceCharacteristicProfile profile; +// Call GetDeviceProfile. +DistributedDeviceProfileClient::GetInstance().GetDeviceProfile(deviceId, serviceId, profile); +std::string jsonData = profile.GetCharacteristicProfileJson(); +result.append("jsonData:" + jsonData + "\n"); +``` + +### Inserting Profile Information + +* Parameters of PutDeviceProfile + +| Name| Type| Mandatory| Description| +| --------- | ---------------------------- | ---- | ----------------------------------- | +| profile | ServiceCharacteristicProfile | Yes| Profile information to insert.| + +* Example + +```c++ +// Declare and fill in the data to insert. +ServiceCharacteristicProfile profile; +profile.SetServiceId(serviceId); +profile.SetServiceType(serviceType); +nlohmann::json j; +j["testVersion"] = "3.0.0"; +j["testApiLevel"] = API_LEVEL; +profile.SetCharacteristicProfileJson(j.dump()); +// Call PutDeviceProfile. +DistributedDeviceProfileClient::GetInstance().PutDeviceProfile(profile); +``` + +### Deleting Profile Information + +* Parameters of DeleteDeviceProfile + +| Name| Type| Mandatory| Description| +| --------- | ---------------------------- | ---- | ----------------------------------- | +| serviceId | std::string | Yes| ID of the service record to delete.| + +* Example + +```c++ +// Declare and fill in the data to delete. +std::string serviceId = "test"; +// DeleteDeviceProfile +DistributedDeviceProfileClient::GetInstance().DeleteDeviceProfile(serviceId); +``` + +### Synchronizing Profile Information + +* Parameters of SyncDeviceProfile + +| Name| Type| Mandatory| Description| +| --------- | ---------------------------- | ---- | ----------------------------------- | +| syncOption| SyncOption | Yes| Synchronization mode and range.| +| syncCb | IProfileEventCallback | Yes| Callback used to return the synchronization result.| + +* Example + +```c++ +// Define the synchronization mode and range. +SyncOptions syncOption; +syncOption.SetSyncMode((OHOS::DistributedKv::SyncMode)atoi(mode.c_str())); +for (const auto& deviceId : deviceIds) { + syncOption.AddDevice(deviceId); +} +// Call SyncDeviceProfile. +DistributedDeviceProfileClient::GetInstance().SyncDeviceProfile(syncOption, + std::make_shared()); +``` + +### Subscribing to Profile Events (Synchronization and Change Events) + +* Parameters of SubscribeProfileEvents + +| Name| Type| Mandatory| Description| +| -------------- | ---------------------------- | ---- | ----------------------------------- | +| subscribeInfos | SubscribeInfo | Yes| Type of the event to subscribe to.| +| eventCb | IProfileEventCallback | Yes| Callback for the subscribed event.| +| failedEvents | ProfileEvent | Yes| Failure event.| + +* Example + +```c++ +auto callback = std::make_shared(); +std::list subscribeInfos; +ExtraInfo extraInfo; +extraInfo["deviceId"] = deviceId; +extraInfo["serviceIds"] = serviceIds; + +// Subscribe to the EVENT_PROFILE_CHANGED event. +SubscribeInfo info1; +info1.profileEvent = ProfileEvent::EVENT_PROFILE_CHANGED; +info1.extraInfo = std::move(extraInfo); +subscribeInfos.emplace_back(info1); + +// Subscribe to the EVENT_SYNC_COMPLETED event. +SubscribeInfo info2; +info2.profileEvent = ProfileEvent::EVENT_SYNC_COMPLETED; +info2.extraInfo = std::move(extraInfo); +subscribeInfos.emplace_back(info2); + +std::list failedEvents; +// Call SubscribeProfileEvents. +DistributedDeviceProfileClient::GetInstance().SubscribeProfileEvents(subscribeInfos, + callback, failedEvents); +sleep(SUBSCRIBE_SLEEP_TIME); +std::list profileEvents; +profileEvents.emplace_back(ProfileEvent::EVENT_PROFILE_CHANGED); +failedEvents.clear(); +// Cancel the subscription. +DistributedDeviceProfileClient::GetInstance().UnsubscribeProfileEvents(profileEvents, + callback, failedEvents); +``` + +## Repositories Involved + +**DeviceProfile subsystem** + +[device\_profile\_core](https://gitee.com/openharmony/device_profile_core) diff --git a/en/readme/figures/dp-architecture.png b/en/readme/figures/dp-architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..6d4573646c6b950b3e571d94ee09816397dd1d73 Binary files /dev/null and b/en/readme/figures/dp-architecture.png differ diff --git a/en/readme/figures/multimedia-architecture.png b/en/readme/figures/multimedia-architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..7c5341b63aa9ff48f3edfe48ed590a4cec8a3935 Binary files /dev/null and b/en/readme/figures/multimedia-architecture.png differ diff --git a/en/readme/multimedia.md b/en/readme/multimedia.md index c26c892898ccec4d4f1a442dc2a9e5abd623f27c..5c42b3425d8e33adb51ff38bb1e0ead7ec0ca8ea 100755 --- a/en/readme/multimedia.md +++ b/en/readme/multimedia.md @@ -8,23 +8,24 @@ This subsystem offers various media services covering audio, videos, and cameras - Audio playback and recording - Video playback and recording - - Photographing and recording \(with cameras\) -## Architecture - -**Figure 1** Common architecture of the multimedia subsystem - - -![](figures/en-us_image_0000001163462711.png) +## System Architecture -**Figure 2** Architecture of the multimedia subsystem suitable for the small system +**Figure 1** Architecture of the multimedia subsystem +![](figures/multimedia-architecture.png) -![](figures/multimedia-subsystem-architecture.png) - -**Figure 3** Multimedia service flow for the small system -![](figures/multimedia-service-flow-for-the-small-system.png "multimedia-service-flow-for-the-small-system") +- **Media**: provides playback and recording APIs for applications, and invokes the Gstreamer, Histreamer, or other engines through cross-process calling or direct calling. + - For the mini system, the media component invokes Histreamer to support audio playback. + - For the small system, the media component invokes recorder_lite to support audio/video recording and invokes player_lite by default to support audio/video playback. If the system variable **debug.media_service.histreamer** is set to **1**, the component invokes Histreamer to support audio/video playback. For details, see [syspara Module](https://device.harmonyos.com/en/docs/documentation/guide/subsys-boot-syspara-0000001063362360) or [syspara_lite](https://gitee.com/openharmony/startup_syspara_lite). + - For the standard system, the media component invokes Gstreamer to support audio/video playback and recording. +- **Audio**: supports audio input and output, policy management, and audio focus management. +- **Camera**: provides camera operation APIs for preview, photographing, and video recording. +- **Image**: supports encoding and decoding of common image formats. +- **MediaLibrary**: supports local and distributed media data access management. +- **Histreamer**: a lightweight media engine that supports file/network streaming media input, audio/video decoding and playback, audio/video encoding and recording, and plugin extension. +- **Gstreamer**: an open-source GStreamer engine that supports streaming media, audio and video playback, and recording. ## Directory Structure @@ -59,6 +60,13 @@ The structure of the repository directory is as follows: │ ├── figures # Architecture and process figures of the playback and recording module for the standard system │ ├── frameworks # Playback and recording framework implementation for the standard system │ └── interfaces # Playback and recording module APIs for the standard system +├── histreamer # Histreamer engine +│ └── engine # Media engine +│ ├── player # Encapsulated player +│ ├── foundation # Basic tools +│ ├── pipeline # Pipeline framework +│ └── plugin # Plugin framework +│ └── plugins # Platform software plugins └── utils # Subsystem utility module └── lite # Utility module for the small system ├── figures # Architecture and process figures of the utility module for the small system @@ -94,9 +102,10 @@ Load the kernel and related drivers before installing the repository. For detail [multimedia\_utils\_lite](https://gitee.com/openharmony/multimedia_utils_lite) +[multimedia\_histreamer](https://gitee.com/openharmony/multimedia_histreamer) + [multimedia\_camera\_standard](https://gitee.com/openharmony/multimedia_camera_standard) [multimedia\_audio\_standard](https://gitee.com/openharmony/multimedia_audio_standard) [multimedia\_media\_standard](https://gitee.com/openharmony/multimedia_media_standard) - diff --git a/en/release-notes/OpenHarmony-2-0-canary.md b/en/release-notes/OpenHarmony-2-0-Canary.md similarity index 100% rename from en/release-notes/OpenHarmony-2-0-canary.md rename to en/release-notes/OpenHarmony-2-0-Canary.md diff --git a/en/release-notes/OpenHarmony-v3.0.1-LTS.md b/en/release-notes/OpenHarmony-v3.0.1-LTS.md new file mode 100644 index 0000000000000000000000000000000000000000..93c97e5a99e41cfd30bc037c52959b655999d205 --- /dev/null +++ b/en/release-notes/OpenHarmony-v3.0.1-LTS.md @@ -0,0 +1,167 @@ +# OpenHarmony 3.0.1 LTS + +## Version Description + +OpenHarmony 3.0.1 LTS is a maintenance version with a tag of OpenHarmony 3.0 LTS. This version has rectified certain issues detected in OpenHarmony 3.0 LTS. + + +## Version Mapping + +**Table 1** Version mapping of software and tools + +| Software/Tool| Version| Remarks| +| -------- | -------- | -------- | +| OpenHarmony | 3.0.1 LTS | NA | +| SDK | 3.0.0.0 (API Version 7 release) | NA | +| (Optional) HUAWEI DevEco Studio| 3.0 Beta1 | Recommended for developing OpenHarmony applications| +| (Optional) HUAWEI DevEco Device Tool| 2.2 Beta2 | Recommended for developing OpenHarmony smart devices| + + +## Source Code Acquisition + + +### Acquiring Source Code Using the repo Tool + +Method 1 \(recommended\): Use the **repo** tool to download the source code over SSH. \(You must have an SSH public key for access to Gitee.\) + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.1-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +Method 2: Use the **repo** tool to download the source code over HTTPS. + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.1-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### Acquiring Source Code from Mirrors + +**Table 2** Mirrors for acquiring source code + +| LTS Code| Version| Mirror| SHA-256 Checksum| +| -------- | -------- | -------- | -------- | +| Full code base (for mini, small, and standard systems)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/code-v3.0.1-LTS.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/code-v3.0.1-LTS.tar.gz.sha256) | +| Standard system solution (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/standard.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/standard.tar.gz.sha256) | +| Hi3861 solution (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_pegasus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_pegasus.tar.gz.sha256) | +| Hi3518 solution (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_aries.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_aries.tar.gz.sha256) | +| Hi3516 solution-LiteOS (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_taurus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_taurus.tar.gz.sha256) | +| Hi3516 solution-Linux (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_taurus_linux.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_taurus_linux.tar.gz.sha256) | + + + +## What's New + +This version has the following updates to OpenHarmony 3.0 LTS. + + +### Feature Updates + +This version does not involve feature updates. + + +### API Updates + +This version does not involve API updates. + + +### Chip and Development Board Adaptation + +For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard.md). + + +## Resolved Issues + +**Table 3** Issues resolved for the mini and small systems + +| Issue No.| Description| +| -------- | -------- | +| [I4BJFU](https://gitee.com/openharmony/kernel_liteos_a/issues/I4BJFU) | An error occurs when the dyload_posix module removes a file.| +| [I42N33](https://gitee.com/openharmony/third_party_mksh/issues/I42N33) | During the integration test, the Ctrl+C operation does not function after the **cat** command is run. A device restart is required.| +| [I4C8BO](https://gitee.com/openharmony/docs/issues/I4C8BO?from=project-issue) | The basic functions of the media subsystem (on a mini- or small-system device) are abnormal when Hi3516D V300 or Hi3518E V300 is burnt and configured by following the instructions in the official website.| +| [I4BWKC](https://gitee.com/openharmony/drivers_framework/issues/I4BWKC) | The camera driver on the Hi3516D V300 board does not function properly in the pressure test.| +| [I4BW0G](https://gitee.com/openharmony/drivers_framework/issues/I4BW0G) | The **ResetDriver** interface of the Hi3516D V300 board fails to be called.| +| [I4C7ZK](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4C7ZK) | For Hi3516D V300, the resident memory of the small system exceeds the baseline.| +| [I434P1](https://gitee.com/openharmony/multimedia_camera_lite/issues/I434P1) | For Hi3518E V300, the resident memory exceeds the baseline.| +| [I48IM7](https://gitee.com/openharmony/hiviewdfx_hilog/issues/I48IM7) | During the HiLog pressure test, the hilogd restarts unexpectedly, and the hilog commands cannot be used.| +| [I4EGMD](https://gitee.com/openharmony/aafwk_aafwk_lite/issues/I4EGMD) | The serialization and deserialization methods of **Want** are defective.| +| [I4CED3](https://gitee.com/openharmony/account_os_account/issues/I4CED3) | The JS API returns both "err" and "data" in one message.| +| [I4BXZ1](https://gitee.com/openharmony/app_samples/issues/I4BXZ1) | The **\** component does not respond to clicks.| +| [I4CMMH](https://gitee.com/openharmony/ace_ace_engine/issues/I4CMMH) | The display effect of the **\** component is abnormal.| +| [I4CE7D](https://gitee.com/openharmony/miscservices_inputmethod/issues/I4CE7D) | The response time of the edit box is inappropriate.| +| [I4HI4C](https://gitee.com/openharmony/ai_engine/issues/I4HI4C) | There is a failed item of the TDD test on a small-system device. This failure is caused by the inappropriate test case comparison time range.| +| [I4EUOW](https://gitee.com/openharmony/ai_engine/issues/I4EUOW) | The number of case execution threads is inappropriate.| +| [I4HTFS](https://gitee.com/openharmony/appexecfwk_appexecfwk_lite/issues/I4HTFS) | BMS adaptation for the mini system is not supported.| +| [I4C3BE](https://gitee.com/openharmony/communication_dsoftbus/issues/I4C3BE) | During passive Bluetooth Low Energy (BLE) discovery, the Bluetooth advertisement is frequently updated and, when the Bluetooth resources are used up, automatically disabled.| +| [I4I7QL](https://gitee.com/openharmony/developtools_packing_tool/issues/I4I7QL) | Packing fails when an ability has two widgets.| +| [I4BW0G](https://gitee.com/openharmony/drivers_framework/issues/I4BW0G) | There is a possibility that the Wi-Fi **ResetDriver** interface fails to be called.| +| [I4GBB6](https://gitee.com/openharmony/device_qemu/issues/I4GBB6) | The RISC-V QEMU emulator fails to run.| +| [I4CE7E](https://gitee.com/openharmony/kernel_liteos_a/issues/I4CE7E) | **drivers/mtd/multi_partition/** in the LiteOS-A kernel is implemented by using the driver functions in **device/hisilicon**.| +| [I4JBEH](https://gitee.com/openharmony/drivers_framework/issues/I4JBEH) | Memory leakage occurs when the DMA transmission interface of HDF is repeatedly used.| +| [I4IGQ0](https://gitee.com/openharmony/drivers_framework/issues/I4IGQ0) | Resources are released after component detection fails.| +| [I4JPCG](https://gitee.com/openharmony/drivers_framework/issues/I4JPCG) | The PWM backlight cannot be set to 0.| +| [I4ERM4](https://gitee.com/openharmony/drivers_peripheral/issues/I4ERM4) | A test case fails to be displayed.| +| [I4CMUY](https://gitee.com/openharmony/drivers_adapter_khdf_linux/issues/I4CMUY) | The hdf\_peripheral\_wlan\_test\_performance.bin test suite fails to run.| +| [I4FIP2](https://gitee.com/openharmony/kernel_liteos_a/issues/I4FIP2) | The **ioctl** function of the LiteOS_A kernel does not support the **SIOCGIFBRDADDR** option.| +| [I4GVF7](https://gitee.com/openharmony/kernel_liteos_a/issues/I4GVF7) | The permissions on the files and folders generated by the blackbox are inappropriate.| +| [I4EV8U](https://gitee.com/openharmony/kernel_liteos_a/issues/I4EV8U) | Three test cases, including IO_TEST_PPOLL_001, fail in the liteos\_a\_io\_unittest.bin\#IoTest module.| +| [I4EV3X](https://gitee.com/openharmony/kernel_liteos_a/issues/I4EV3X) | Seven test cases, including ItTestSys018, fail in the liteos\_a\_sys\_unittest.bin\#SysTest module.| +| [I4EVG0](https://gitee.com/openharmony/kernel_liteos_a/issues/I4EVG0) | The test case ItTestMisc009 fails in the liteos\_a\_misc\_unittest.bin\#MiscTest module.| +| [I4JYAX](https://gitee.com/openharmony/kernel_liteos_a/issues/I4JYAX) | The jffs2 adaptation layer incorrectly releases the lock.| +| [I4FIQW](https://gitee.com/openharmony/kernel_liteos_m/issues/I4FIQW) | The **ioctl** function of the LiteOS_M kernel does not support the **SIOCGIFBRDADDR** option.| +| [I4ELVA](https://gitee.com/openharmony/kernel_liteos_m/issues/I4ELVA) | The **read** interface at the VFS layer of the file system incorrectly determines whether **g_fs** is null.| +| [I4C6P2](https://gitee.com/openharmony/kernel_liteos_m/issues/I4C6P2) | The **LOS_QueueInfoGet** function incorrectly counts the tasks waiting to be read and written.| +| [I4C5RW](https://gitee.com/openharmony/kernel_liteos_m/issues/I4C5RW) | The error indicating that the **OS_TASK_STACK_PROTECT_SIZE** macro is not defined occurs when the MPU is enabled to protect the task stack.| +| [I4G4VK](https://gitee.com/openharmony/kernel_liteos_m/issues/I4G4VK) | Some macros are inappropriate. If they (for example, **inet_addr**) are changed to functions, the lwIP header file is not required for external calling.| +| [I4FVGV](https://gitee.com/openharmony/kernel_liteos_m/issues/I4FVGV) | The default lwIP configuration of the LiteOS_M kernel is inappropriate.| +| [I4CE7D](https://gitee.com/openharmony/miscservices_inputmethod/issues/I4CE7D) | There is no necessary to start the input method after a 3-second delay.| +| [I4CFOO](https://gitee.com/openharmony/multimedia_media_lite/issues/I4CFOO) | After an application running on the Linux system records videos for multiple times, the size of the last recording file is 0 when the system is restarted without exiting the application.| +| [I4CLGW](https://gitee.com/openharmony/kernel_liteos_a/issues/I4CLGW) | The page cache is inappropriate.| +| [I4HKQ2](https://gitee.com/openharmony/vendor_hisilicon/issues/I4HKQ2) | The mechanism for the LiteOS running on a mini-system board to obtain the UDID is inappropriate.| +| [I4FVJN](https://gitee.com/openharmony/startup_syspara_lite/issues/I4FVJN) | Mini system compilation fails because the dependency to mbedTLS is not added.| +| [I4CE7E](https://gitee.com/openharmony/kernel_liteos_a/issues/I4CE7E) | **drivers/mtd/multi_partition/** in the LiteOS-A kernel is implemented by using the driver functions in **device/hisilicon**.| + +**Table 4** Issues resolved for the standard system + +| Issue No.| Description| +| -------- | -------- | +| [I4BX4J](https://gitee.com/openharmony/hiviewdfx_hicollie/issues/I4BX4J?from=project-issue) | The Hi3516D V300 board fails to call the **hicollie** interface.| +| [I4BX1X](https://gitee.com/openharmony/hiviewdfx_hitrace/issues/I4BX1X?from=project-issue) | The Hi3516D V300 board fails to call the **hitrace** interface.| +| [I4BVUL](https://gitee.com/openharmony/communication_wifi/issues/I4BVUL?from=project-issue) | When access points (APs) are changed, the success rate for networking between standard-system devices and mobile phones is 91%, lower than the expected value (98%).| +| [I4BW6E](https://gitee.com/openharmony/security_deviceauth/issues/I4BW6E) | During the test for networking between standard-system devices and mobile phones, when the mobile phone disables and enables the network access repeatedly for around 30 times, the networking fails.| +| [I4BVVW](https://gitee.com/openharmony/communication_dsoftbus/issues/I4BVVW) | During the test for networking between standard-system devices and mobile phones, when the Wi-Fi switch is turned on and off repeatedly, the networking success rate is 97%, lower than the expected value.| +| [I48YPH](https://gitee.com/openharmony/security_deviceauth/issues/I48YPH?from=project-issue) | During the test for discovery and networking performance, 3 out of 110 networking attempts fails.| +| [I4492M](https://gitee.com/openharmony/communication_dsoftbus/issues/I4492M) | The offline device detection takes about 30s longer than the specifications.| +| [I44W7U](https://gitee.com/openharmony/graphic_standard/issues/I44W7U?from=project-issue) | The child window does not support zooming. As a result, the progress bar is hidden during video playback.| +| [I480Z1](https://gitee.com/openharmony/communication_dsoftbus/issues/I480Z1?from=project-issue) | Softbus_server crashes when executing **socketfuzz**.| +| [I4BGLS](https://gitee.com/openharmony/security_deviceauth/issues/I4BGLS?from=project-issue) | The key imported by using `import_signed_auth_info_hilink` is used for identifying the HiChain connection. After the key is imported, it is encrypted and stored in the file and is not cleared from the heap after being returned.| +| [I4A10Q](https://gitee.com/openharmony/startup_appspawn/issues/I4A10Q?from=project-issue) | The performance of Hi3516 3.0.0.6 static KPIs deteriorates severely.| +| [I4BXYT](https://gitee.com/openharmony/developtools_hdc_standard/issues/I4BXYT) | After device restart, developers must run the **hdc_std kill** command to discover the device again.| +| [I4KUTY](https://gitee.com/openharmony/ace_engine_lite/issues/I4KUTY) | There are invalid return values.| +| [I4DMFV](https://gitee.com/openharmony/ark_js_runtime/issues/I4DMFV) | The conversion from UTF-16 to UTF-8 is inappropriate.| +| [I4HGVM](https://gitee.com/openharmony/communication_dsoftbus/issues/I4HGVM) | The dependency on mbedTLS is missing for the standard system.| +| [I4DLV2](https://gitee.com/openharmony/drivers_framework/issues/I4DLV2) | An invalid memory access error occurs due to the HidInfo\* type.| +| [I4CIJJ](https://gitee.com/openharmony/third_party_flutter/issues/I4CIJJ) | ACE does not support GPU rendering.| +| [I4G31Z](https://gitee.com/openharmony/third_party_freetype/issues/I4G31Z) | An update for the font engine version from 2.10.1 to 2.10.4 is unavailable.| +| [I4H06M](https://gitee.com/openharmony/third_party_harfbuzz/issues/I4H06M) | An update for the OpenType text shaping engine from 2.6.1 to 2.8.1 is unavailable.| +| [I4FS7V](https://gitee.com/openharmony/third_party_lwip/issues/I4FS7V) | The **LWIP\_NETCONN\_FULLDUPLEX** macro is not used to control the initialization of **conn->mbox\_threads\_waiting**.| +| [I43KL7](https://gitee.com/openharmony/graphic_standard/issues/I43KL7) | The synthesizer does not support GPU synthesis.| + + +## Known Issues + +**Table 5** Known issues + +| Issue No.| Description| Impact| To Be Resolved On| +| -------- | -------- | -------- | -------- | +| [I4NMXQ](https://gitee.com/openharmony/xts_acts/issues/I4NMXQ?from=project-issue) | The XTS test suites storagefileioperformancejstest and storagefilestabilityjstest cannot be automatically executed on a standard-system device.| This issue is caused by the XTS test suite framework. The test suites can only be manually executed. This issue does not affect functions.| 2022/01/30 | +| [I4NU92](https://gitee.com/openharmony/communication_wifi/issues/I4NU92) | Mini-system Hi3516_Linux: The ActsLwipTest.bin test suite has a failed test item.| The automatic test case fails to invoke the kernel to read time_out. This issue does not affect the communication function.| 2022/01/15 | +| [I4NTKG](https://gitee.com/openharmony/xts_acts/issues/I4NTKG) | Two failed items are displayed when the XTS test suite WeekPluralNumberTest is executed.| This is a test case issue and does not affect functions.| 2022/01/15 | +| [I4OWWM](https://gitee.com/openharmony/xts_acts/issues/I4OWWM) | The JSON file corresponding to the WeekPluralNumbertest module is incorrectly configured. During case execution, the error message "required device does not exist" is displayed.| The JSON file configuration is incorrect. This issue does not affect functions.| 2022/01/15 | +| [I4MSVV](https://gitee.com/openharmony/xts_acts/issues/I4MSVV?from=project-issue) | During the XTS test on the standard system, there are three failed items of the HiCollieCppTest cases in the ActsHiCollieCppTest module.| The test suite name is changed. As a result, the test case with the text verification function fails. This issue does not affect functions.| 2022/01/15 | +| [I4MSWM](https://gitee.com/openharmony/xts_acts/issues/I4MSWM?from=project-issue) | During the XTS test on the standard system, there is one failed item for faultloggertest in the ActsFaultLoggerTest module.| The test suite name is changed. As a result, the test case with the text verification function fails. This issue does not affect functions.| 2022/01/15 | +| [I4NODO](https://gitee.com/openharmony/device_manager/issues/I4NODO) | During the test for the Hi3516 board running on a standard-system device, the E2E test of the distributed service hopping fails.| The DM component fails to repeatedly create a group. This issue affects the services that use hopping in the same way as that described in the issue details. Other services are not affected.| 2022/01/30 | diff --git a/en/release-notes/Readme.md b/en/release-notes/Readme.md index bc2cf67f424665d1346bfd1e4955ed8f56bbb2ee..1182087f12c19aff9aa3772fe559feed1ba534ef 100644 --- a/en/release-notes/Readme.md +++ b/en/release-notes/Readme.md @@ -1,11 +1,12 @@ # OpenHarmony Release Notes ## OpenHarmony 3.x Releases - [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md) +- [OpenHarmony v3.0.1 LTS (2022-01-12)](OpenHarmony-v3.0.1-LTS.md) - [OpenHarmony v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md) ## OpenHarmony 2.x Releases - [OpenHarmony v2.2 beta2 (2021-08-04)](OpenHarmony-v2.2-beta2.md) -- [OpenHarmony 2.0 Canary (2021-06-02)](OpenHarmony-2-0-canary.md) +- [OpenHarmony 2.0 Canary (2021-06-02)](OpenHarmony-2-0-Canary.md) ## OpenHarmony 1.x Releases - [OpenHarmony v1.1.3 LTS (2021-09-30)](OpenHarmony-v1-1-3-LTS.md) - [OpenHarmony v1.1.2 LTS (2021-08-04)](OpenHarmony-v1.1.2-LTS.md) diff --git a/zh-cn/application-dev/background-task-management/background-task-dev-guide.md b/zh-cn/application-dev/background-task-management/background-task-dev-guide.md index 590eeaeb10e8fb8eef38659490aeaeb0f8badc0b..c23b3f917dfa750846432232963eac050d88f963 100644 --- a/zh-cn/application-dev/background-task-management/background-task-dev-guide.md +++ b/zh-cn/application-dev/background-task-management/background-task-dev-guide.md @@ -34,7 +34,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; let myReason = 'test requestSuspendDelay'; let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspend delay will time out."); + console.info("Request suspension delay will time out."); }); var id = delayInfo.requestId;console.info("requestId is: " + id); ``` @@ -61,7 +61,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; let myReason = 'test requestSuspendDelay'; // 申请延迟挂起 let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspend delay will time out."); + console.info("Request suspension delay will time out."); }); // 打印延迟挂起信息 var id = delayInfo.requestId; diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_20220117.jpg b/zh-cn/application-dev/media/figures/zh-ch_image_20220117.jpg index bc56b9d8395873193bbad2b3faf7340c6728af60..8fba3a7beeb4efc7599dde3f32b228135ed92fce 100644 Binary files a/zh-cn/application-dev/media/figures/zh-ch_image_20220117.jpg and b/zh-cn/application-dev/media/figures/zh-ch_image_20220117.jpg differ diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 5834381fe4f5cddb0c648316714160f6513aad55..c26de29843cc9bbcddf0ab54e931b488a87eb260 100644 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -20,6 +20,7 @@ - [媒体服务](js-apis-media.md) - 安全 - [用户认证](js-apis-useriam-userauth.md) + - [访问控制](js-apis-security-accessToken.md) - 数据管理 - [轻量级存储](js-apis-data-storage.md) - [分布式数据管理](js-apis-distributed-data.md) @@ -31,6 +32,7 @@ - [文件管理](js-apis-fileio.md) - [Statfs](js-apis-statfs.md) - [目录环境](js-apis-environment.md) + - [公共文件访问与管理](js-apis-filemanager.md) - 账号管理 - [分布式帐号管理](js-apis-distributed-account.md) - [应用帐号管理](js-apis-appAccount.md) @@ -75,4 +77,18 @@ - [xml解析与生成](js-apis-xml.md) - [xml转换JavaScript](js-apis-convertxml.md) - [启动一个worker](js-apis-worker.md) + - [线性容器ArrayList](js-apis-arraylist.md) + - [线性容器Deque](js-apis-deque.md) + - [线性容器List](js-apis-list.md) + - [线性容器LinkedList](js-apis-linkedlist.md) + - [线性容器Queue](js-apis-queue.md) + - [线性容器Stack](js-apis-stack.md) + - [线性容器Vector](js-apis-vector.md) + - [非线性容器HashSet](js-apis-hashset.md) + - [非线性容器HashMap](js-apis-hashmap.md) + - [非线性容器PlainArray](js-apis-plainarray.md) + - [非线性容器TreeMap](js-apis-treemap.md) + - [非线性容器TreeSet](js-apis-treeset.md) + - [非线性容器LightWeightMap](js-apis-lightweightmap.md) + - [非线性容器LightWeightSet](js-apis-lightweightset.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md new file mode 100644 index 0000000000000000000000000000000000000000..cecb7b7b0cb306fec81610b475839fe756024ec7 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md @@ -0,0 +1,518 @@ +# 线性容器ArrayList + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +``` +import {ArrayList} from '@ohos.util.ArrayList' +``` + +## 权限 + +无 + +## ArrayList + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | ArrayList的元素个数 | + + +### constructor + +constructor(); + +ArrayList的构造函数。 + +- 示例: + ``` + let arrayList = new ArrayList(); + ``` + + +### add + +add(element: T): boolean; + +在ArrayList尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add("a"); + arrayList.add(1); + let b = [1, 2, 3]; + arrayList.add(b); + let c = {name: "lala", age: "13"}; + arrayList.add(false); + ``` + +### insert + +insert(element: T, index: number): void; + +在长度范围内任意位置插入指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 被插入的元素 | + | index | number | 是 | 被插入的位置索引 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.insert("A", 0); + arrayList.insert(0, 1); + arrayList.insert(true, 2); + ``` + +### has + +has(element: T): boolean; + +判断此ArrayList中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + arrayList.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + +### getIndexOf + +getIndexOf(element: T): number; + +返回指定元素第一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(2); + arrayList.add(1); + arrayList.add(2); + arrayList.add(4); + arrayList.getIndexOf(2); + ``` +### getLastIndexOf + +getLastIndexOf(element: T): number; + +返回指定元素最后一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素最后一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(2); + arrayList.add(1); + arrayList.add(2); + arrayList.add(4); + arrayList.getLastIndexOf(2); + ``` +### removeByIndex + +removeByIndex(index: number): T; + +根据元素的下标值查找元素,返回元素后将其删除。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定元素的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(2); + arrayList.add(4); + arrayList.removeByIndex(2); + ``` + +### remove + +remove(element: T): boolean; + +删除查找到的第一个指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.remove(2); + ``` + +### removeByRange + +removeByRange(fromIndex: number, toIndex: number): void; + +从一段范围内删除元素,包括起始值但不包括终止值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.removeByRange(2, 4); + arrayList.removeByRange(4, 3); + arrayList.removeByRange(2, 6); + ``` +### replaceAllElements +replaceAllElements(callbackfn: (value: T, index?: number, arraylist?: ArrayList<T>) => T, +thisArg?: Object): void; + +用户操作ArrayList中的元素,用操作后的元素替换原元素并返回操作后的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | arraylist | ArrayList<T> | 否 | 当前调用replaceAllElements方法的实例对象 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.replaceAllElements((value, index) => { + return value = 2 * value; + }); + arrayList.replaceAllElements((value, index) => { + return value = value - 2; + }); + ``` +### forEach +forEach(callbackfn: (value: T, index?: number, arraylist?: ArrayList<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历ArrayList实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数。 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素。 | + | index | number | 否 | 当前遍历到的下标值。 | + | arraylist | ArrayList<T> | 否 | 当前调用forEach方法的实例对象。 | + + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.forEach((value, index) => { + console.log(value, index); + }); + ``` +### sort +sort(comparator?: (firstValue: T, secondValue: T) => number): void; + +对ArrayList中的元素进行一个排序操作 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 否 | 回调函数 | + +- comparator的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | firstValue | T | 是 | 前一项元素 | + | secondValue | T | 是 | 后一项元素 | + + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.sort(a, (b => a - b)); + arrayList.sort(a, (b => b - a)); + arrayList.sort(); + ``` +### subArrayList +subArrayList(fromIndex: number, toIndex: number): ArrayList<T>; + +根据下标截取ArrayList中的一段元素,并返回这一段ArrayList实例, 包括起始值但不包括终止值 +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | ArrayList<T> | 返回ArrayList对象实例 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.subArrayList(2, 4); + arrayList.subArrayList(4, 3); + arrayList.subArrayList(2, 6); + ``` + +### clear +clear(): void; + +清除ArrayList中的所有元素,并把length置为0。 + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.clear(); + ``` +### clone +clone(): ArrayList<T> ; + +克隆一个与ArrayList一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | ArrayList<T> | 返回ArrayList对象实例 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.clone(); + ``` +### getCapacity +getCapacity(): number; + +获取当前实例的容量大小。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回arraylist的容量大小 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.getCapacity(); + ``` +### convertToArray +convertToArray(): Array<T>; + +把当前ArrayList实例转换成数组,并返回转换后的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回数组类型 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.convertToArray(); + ``` +### isEmpty +isEmpty(): boolean; + +判断该ArrayList是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.isEmpty(); + ``` +### increaseCapacityTo +increaseCapacityTo(newCapacity: number): void; + +如果传入的新容量大于或等于ArrayList中的元素个数,将容量变更为新容量。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | newCapacity | number | 是 | 新容量 | + + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.increaseCapacityTo(2); + arrayList.increaseCapacityTo(8); + ``` +### trimToCurrentLength +trimToCurrentLength(): void; + +把容量限制为当前的length大小。 + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.trimToCurrentLength(2); + ``` +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + + // 使用方法一: + for (let item of arrayList) { + console.log(item); + } + + // 使用方法二: + let iter = arrayList[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 636afc455eb984765269155842edec14c2cfbda5..4369e06d5710ff9b4fcefec08576015c83ebba7b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -7,11 +7,6 @@ import audio from '@ohos.multimedia.audio'; ``` -## 权限 - -无 - - ## getAudioManager getAudioManager(): AudioManager @@ -115,6 +110,7 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err)=>{ if (err) { console.error('Failed to set the volume. ${err.message}'); @@ -146,6 +142,7 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(()=> console.log('Promise returned to indicate a successful volume setting.'); ) @@ -167,6 +164,7 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): v **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the volume. ${err.message}'); @@ -197,6 +195,7 @@ getVolume(volumeType: AudioVolumeType): Promise<number> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => console.log('Promise returned to indicate that the volume is obtained.' + value); ) @@ -218,6 +217,7 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the minimum volume. ${err.message}'); @@ -248,6 +248,7 @@ getMinVolume(volumeType: AudioVolumeType): Promise<number> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => console.log('Promised returned to indicate that the minimum volume is obtained.' + value); ) @@ -269,6 +270,7 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the maximum volume. ${err.message}'); @@ -299,6 +301,7 @@ getMaxVolume(volumeType: AudioVolumeType): Promise<number> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data)=> console.log('Promised returned to indicate that the maximum volume is obtained.'); ) @@ -321,6 +324,7 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { console.error('Failed to mute the stream. ${err.message}'); @@ -353,6 +357,7 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> ``` +var audioManager = audio.getAudioManager(); audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => console.log('Promise returned to indicate that the stream is muted.'); ) @@ -375,6 +380,7 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): voi **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the mute status. ${err.message}'); @@ -406,6 +412,7 @@ isMute(volumeType: AudioVolumeType): Promise<boolean> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => console.log('Promise returned to indicate that the mute status of the stream is obtained.' + value); ) @@ -427,6 +434,7 @@ isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): v **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the active status of the stream. ${err.message}'); @@ -457,6 +465,7 @@ isActive(volumeType: AudioVolumeType): Promise<boolean> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => console.log('Promise returned to indicate that the active status of the stream is obtained.' + value); ) @@ -478,6 +487,7 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { console.error('Failed to set the ringer mode.​ ${err.message}'); @@ -508,6 +518,7 @@ setRingerMode(mode: AudioRingMode): Promise<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => console.log('Promise returned to indicate a successful setting of the ringer mode.'); ) @@ -529,6 +540,7 @@ getRingerMode(callback: AsyncCallback<AudioRingMode>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getRingerMode((err, value) => { if (err) { console.error('Failed to obtain the ringer mode.​ ${err.message}'); @@ -554,6 +566,7 @@ getRingerMode(): Promise<AudioRingMode> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getRingerMode().then((value) => console.log('Promise returned to indicate that the ringer mode is obtained.' + value); ) @@ -576,6 +589,7 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => { if (err) { console.error('Failed to set the audio parameter. ${err.message}'); @@ -607,6 +621,7 @@ setAudioParameter(key: string, value: string): Promise<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setAudioParameter('PBits per sample', '8 bit').then(() => console.log('Promise returned to indicate a successful setting of the audio parameter.'); ) @@ -628,6 +643,7 @@ getAudioParameter(key: string, callback: AsyncCallback<string>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getAudioParameter('PBits per sample', (err, value) => { if (err) { console.error('Failed to obtain the value of the audio parameter. ${err.message}'); @@ -658,6 +674,7 @@ getAudioParameter(key: string): Promise<string> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getAudioParameter('PBits per sample').then((value) => console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value); ) @@ -678,6 +695,7 @@ getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescrip **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{ if (err) { console.error('Failed to obtain the device list. ${err.message}'); @@ -708,6 +726,7 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{ **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data)=> console.log('Promise returned to indicate that the device list is obtained.'); ) @@ -730,6 +749,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean, callback: AsyncCallback **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true, (err)=> { if (err) { console.error('Failed to set the active status of the device. ${err.message}'); @@ -762,6 +782,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean): Promise<void> ``` +var audioManager = audio.getAudioManager(); audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true).then(()=> console.log('Promise returned to indicate that the device is set to the active status.'); ) @@ -783,6 +804,7 @@ isDeviceActive(deviceType: DeviceType, callback: AsyncCallback<boolean>): **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isDeviceActive(audio.DeviceType.SPEAKER, (err, value) => { if (err) { console.error('Failed to obtain the active status of the device. ${err.message}'); @@ -814,6 +836,7 @@ isDeviceActive(deviceType: DeviceType): Promise<boolean> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isDeviceActive(audio.DeviceType.SPEAKER).then((value) => console.log('Promise returned to indicate that the active status of the device is obtained.' + value); ) @@ -835,6 +858,7 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setMicrophoneMute(true, (err) => { if (err) { console.error('Failed to mute the microphone. ${err.message}'); @@ -865,6 +889,7 @@ setMicrophoneMute(mute: boolean): Promise<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setMicrophoneMute(true).then(() => console.log('Promise returned to indicate that the microphone is muted.'); ) @@ -885,6 +910,7 @@ isMicrophoneMute(callback: AsyncCallback<boolean>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isMicrophoneMute((err, value) => { if (err) { console.error('Failed to obtain the mute status of the microphone. ${err.message}'); @@ -910,6 +936,7 @@ isMicrophoneMute(): Promise<boolean> ``` +var audioManager = audio.getAudioManager(); audioManager.isMicrophoneMute().then((value) => console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value); ) diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 6054f6d62100b455a5abc2092bae1ac30dd957a5..774b6c05d8efe64a01395bdf5e7018778e1e3750 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -39,7 +39,7 @@ requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspen ``` let myReason = 'test requestSuspendDelay'; let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspend delay will time out."); + console.info("Request suspension delay will time out."); }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-battery-info.md b/zh-cn/application-dev/reference/apis/js-apis-battery-info.md index 57a8070f4f4d702331a2c2fbb1868f0f44e30fdd..c9a4b11914a4240013c0475d85a6aaa5acab39b3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-battery-info.md +++ b/zh-cn/application-dev/reference/apis/js-apis-battery-info.md @@ -10,6 +10,9 @@ import batteryInfo from '@ohos.batteryInfo'; ``` +## 系统能力 + +SystemCapability.PowerManager.BatteryManager ## 属性 diff --git a/zh-cn/application-dev/reference/apis/js-apis-brightness.md b/zh-cn/application-dev/reference/apis/js-apis-brightness.md index 1825ff78c9b0b02223f4aecd41ddafe9575fde44..9692cb136f5ac05ef9fe2152f8ce73297994a074 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-brightness.md +++ b/zh-cn/application-dev/reference/apis/js-apis-brightness.md @@ -10,6 +10,9 @@ import brightness from '@ohos.brightness'; ``` +## 系统能力 + +SystemCapability.PowerManager.DisplayPowerManager ## brightness.setValue diff --git a/zh-cn/application-dev/reference/apis/js-apis-convertxml.md b/zh-cn/application-dev/reference/apis/js-apis-convertxml.md index 6b5edb199d7c4f174d49dadf620a640afff7bf60..1520b77763fb5d845d153beb3b12acd0a9d2c276 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-convertxml.md +++ b/zh-cn/application-dev/reference/apis/js-apis-convertxml.md @@ -7,14 +7,9 @@ ## 导入模块 ``` -import convertxml from '@ohos.convertxml' +import convertxml from '@ohos.convertxml'; ``` - -## 权限 - -无 - ## ConvertXML @@ -48,7 +43,7 @@ convert(xml: string, options?: ConvertOptions) : Object ' Work' + ' Play' + ''; - var conv= new convertxml.ConvertXML(); + var conv = new convertxml.ConvertXML(); var result1 = conv.convert(xml, {trim: false, ignoreDeclaration: false}); console.log(result1) ``` @@ -63,7 +58,7 @@ convert(xml: string, options?: ConvertOptions) : Object | ignoreInstruction | boolean | 否 | 是否忽略xml的写入处理指令,默认false。 | | ignoreAttributes | boolean | 否 | 是否跨多行打印属性并缩进属性,默认false。 | | ignoreComment | boolean | 否 | 是否忽略元素的注释信息,默认false。 | -| ignoreCdata | boolean | 否 | 是否忽略元素的CData信息,默认false。 | +| ignoreCDATA | boolean | 否 | 是否忽略元素的CDATA信息,默认false。 | | ignoreDoctype | boolean | 否 | 是否忽略元素的Doctype信息,默认false。 | | ignoreText | boolean | 否 | 是否忽略元素的文本信息,默认false。 | | declarationKey | string | 否 | 用于输出对象中declaration的属性键的名称,默认_declaration。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-deque.md b/zh-cn/application-dev/reference/apis/js-apis-deque.md new file mode 100644 index 0000000000000000000000000000000000000000..8a845a02e8a12d2f5b103c11c9ef21982ef84a65 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-deque.md @@ -0,0 +1,251 @@ +# 线性容器Deque + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {Deque} from '@ohos.util.Deque' +``` + +## 权限 + +无 + +## Deque + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | Deque的元素个数 | + +### constructor + +constructor(); + +Deque的构造函数。 + +- 示例: + ``` + let queue = new Queue(); + ``` + +### insertFront + +insertFront(element: T): void; + +在deque头部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 示例: + ``` + let deque = new Deque; + deque.insertFront("a"); + deque.insertFront(1); + let b = [1, 2, 3]; + deque.insertFront(b); + let c = {name : "lala", age : "13"}; + deque.insertFront(false); + ``` +### insertEnd + +insertEnd(element: T): void; + +在deque尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 示例: + ``` + let deque = new Deque; + deque.insertEnd("a"); + deque.insertEnd(1); + let b = [1, 2, 3]; + deque.insertEnd(b); + let c = {name : "lala", age : "13"}; + deque.insertEnd(false); + ``` +### has + +has(element: T): boolean; + +判断此Deque中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let deque = new Deque(); + deque.has("Ahfbrgrbgnutfodgorrogorg"); + deque.insertFront("Ahfbrgrbgnutfodgorrogorg"); + deque.has("Ahfbrgrbgnutfodgorrogorg"); + ``` +### popFirst + +popFirst(): T; + +删除并返回双端队列的首元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertFront(4); + deque.insertEnd(5); + deque.insertFront(2); + deque.insertFront(4); + deque.popFirst(); + ``` +### popLast + +popLast(): T; + +删除并返回双端队列的尾元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertEnd(4); + deque.insertFront(5); + deque.insertFront(2); + deque.insertFront(4); + deque.popLast(); + ``` + +### forEach +forEach(callbackfn: (value: T, index?: number, deque?: Deque<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历Deque实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | deque | Deque<T> | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertEnd(4); + deque.insertFront(5); + deque.insertEnd(4); + deque.forEach((value, index) => { + console.log(value, index); + }); + ``` + +### getFirst + +getFirst(): T; +获取Deque实例中的头元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let deque = new Deque(); + deque.insertEnd(2); + deque.insertEnd(4); + deque.insertFront(5); + deque.insertFront(4); + deque.getFirst(); + ``` +### getLast + +getLast(): T; +获取Deque实例中的尾元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertFront(4); + deque.insertFront(5); + deque.insertFront(4); + deque.getLast(); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器。 | + + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertFront(4); + deque.insertFront(5); + deque.insertFront(4); + + // 使用方法一: + for (let item of deque) { + console.log(item); + } + + // 使用方法二: + let iter = deque[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-environment.md b/zh-cn/application-dev/reference/apis/js-apis-environment.md index 2d38edd1d107c7713d9ef9e6815710e403650ecc..c4077db9a74a56395243a1a98eb8f059d1e010d5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-environment.md +++ b/zh-cn/application-dev/reference/apis/js-apis-environment.md @@ -1,18 +1,17 @@ # 目录环境能力 - +> ![icon-note.gif](D:/docs/zh-cn/application-dev/reference/apis/public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 -``` +```js import environment from '@ohos.environment'; ``` +## 系统能力 - -## 权限列表 - -无 +SystemCapability.FileManagement.File.Environment ## environment.getStorageDataDir @@ -28,7 +27,7 @@ getStorageDataDir():Promise<string> - 示例: - ``` + ```js environment.getStorageDataDir().then(function(path){ // do something }).catch(function(error){ @@ -50,7 +49,7 @@ getStorageDataDir(callback:AsyncCallback<string>):void - 示例: - ``` + ```js environment.getStorageDataDir(function(error, path){ // do something }); @@ -70,7 +69,7 @@ getUserDataDir():Promise<string> - 示例: - ``` + ```js environment.getUserDataDir().then(function(path){ // do something }).catch(function(error){ @@ -92,7 +91,7 @@ getUserDataDir(callback:AsyncCallback<string>): void - 示例: - ``` + ```js environment.getUserDataDir(function(error, path){ // do something }); diff --git a/zh-cn/application-dev/reference/apis/js-apis-filemanager.md b/zh-cn/application-dev/reference/apis/js-apis-filemanager.md index 897f1063eadeedf1ce2acfbb392f85139d4e959a..173e64ef45ade4c21a26e7cd3346eebedf826fe6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-filemanager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-filemanager.md @@ -1,16 +1,18 @@ # 公共文件访问与管理 - +>![](../../public_sys-resources/icon-note.gif) **说明:** +>本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 -``` +```js import filemanager from 'ohos.filemanager' ``` -## 权限 +## 系统能力 -应用需要拥有SystemCapability.FileManagement.FileManagerService权限 +SystemCapability.FileManagement.FileManagerService ## filemanager.getRoot + getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> 以异步方法获取第一层相册,目录信息。使用promise形式返回结果。 @@ -18,13 +20,13 @@ getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> - 参数 | 参数名 | 类型 | 必填 | 说明 | | --- | --- | --- | -- | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | - 返回值 | 类型 | 说明 | | --- | -- | - | Promise<FileInfo[]> | 第一层目录相册信息 | + | Promise<[FileInfo](#fileinfo)[]> | 第一层目录相册信息 | - 示例 @@ -52,8 +54,8 @@ getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback<FileInfo[]>) | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----------------------------- | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | - | callback | AsyncCallback<FileInfo[]> | 是 | 异步获取文件的信息之后的回调 | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | + | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - 示例 @@ -78,10 +80,10 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num | --- | --- | --- | -- | | type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" | | path | string | 是 | 待查询目录uri | - | dev | DevInfo | 是 | 设备名, 当前仅支持设备'local' | + | dev | [DevInfo](#devinfo) | 是 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | | offset | number | 否 | 待查询文件偏移 | | count | number | 否 | 待查询文件个数 | - + - 返回值 | 类型 | 说明 | @@ -123,10 +125,10 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" | | path | string | 是 | 待查询目录uri | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | | offset | number | 否 | 待查询文件偏移 | | count | number | 否 | 待查询文件个数 | - | callback | AsyncCallback<FileInfo[]> | 是 | 异步获取文件的信息之后的回调 | + | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - 异常 | 错误名称 | 错误类型 | 错误码 | 说明 | @@ -158,7 +160,7 @@ filemanager.createFile(path : string, filename : string, options? : {dev? : DevI | --- | --- | --- | -- | | filename | string | 是 | 待创建的文件名 | | path | string | 是 | 待保存目的相册uri | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | - 返回值 @@ -199,8 +201,8 @@ createFile(path : string, filename: string, options? : {dev? : DevInfo}, callbac | -------- | ------------------------- | ---- | ----------------------------- | | filename | string | 是 | 待创建的文件名 | | path | string | 是 | 待保存目的相册uri | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | - | callback | AsyncCallback<FileInfo[]> | 是 | 异步获取文件的信息之后的回调 | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | + | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - 异常 @@ -225,6 +227,8 @@ filemanager.createFile(media_path, name, (err, uri) => { ## FileInfo 文件信息类型,通过getRoot, listFile等接口返回的类型。 +### 属性 + | 参数名 | 类型 | 可读 | 可写 | 说明 | | --- | -- | -- | -- | -- | | name | string | 是 | 否 | 文件名称 | @@ -237,6 +241,8 @@ filemanager.createFile(media_path, name, (err, uri) => { ## DevInfo 设备类型,配置接口访问的设备类型。 +### 属性 + | 参数名 | 类型 | 可读 | 可写 | 说明 | | --- | -- | -- | -- | -- | | name | string | 是 | 是 | 设备名称 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md new file mode 100644 index 0000000000000000000000000000000000000000..bb8b631ed02837a7645134a62a985e162db24b10 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md @@ -0,0 +1,380 @@ +# 非线性容器HashMap + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {HashMap} from '@ohos.util.HashMap' +``` + + +## 权限 + +无 + +## HashMap + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | HashMap的元素个数 | + + +### constructor + +constructor(); + +HashMap的构造函数。 + +- 示例: + ``` + let hashMap = new HashMap(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该HashMap是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const hashMap = new HashMap(); + hashMap.isEmpty(); + ``` + + +### hasKey + +hasKey(key: K): boolean; + +判断此HashMap中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### hasValue + +hasValue(value: V): boolean; + +判断此HashMap中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.hasValue(123); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.hasValue(123); + ``` + + +### get + +get(key: K): V; + +获取指定key所对应的value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回key映射的value值 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + hashMap.get("sdfs"); + ``` + + +### setAll + +setAll(map: HashMap): void; + +将一个HashMap中的所有元素组添加到另一个hashmap中。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | map | HashMap | 是 | 被添加元素的hashmap | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + let newHashMap = new HashMap(); + hashMap.setAll(newHashMap); + ``` + + +### set + +set(key: K, value: V): Object; + +向HashMap中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 添加成员数据的键名 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Object | 返回添加后的hashmap | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + ``` + + +### remove + +remove(key: K): V; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回删除元素的值 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + hashMap.remove("sdfs"); + ``` + + +### clear + +clear(): void; + +清除HashMap中的所有元素,并把length置为0。 + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + hashMap.clear(); + ``` + + +### keys + +keys(): IterableIterator<K>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<K> | 返回一个迭代器 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + let iter = hashMap.keys(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### values + +values(): IterableIterator<V>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<V> | 返回一个迭代器 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + let iter = hashMap.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### replace + +replace(key: K, value: V): boolean; + +对HashMap中一组数据进行更新(替换)。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定替换的元素 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功对已有数据进行替换 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("sdfs", 123); + hashMap.replace("sdfs", 357); + ``` + + +### forEach + +forEach(callbackfn: (value: V, key?: K, hashMap?: HashMap) => void, thisArg?: Object): void; + +通过回调函数来遍历HashMap实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 当前遍历到的元素键值对的值 | + | key | K | 是 | 当前遍历到的元素键值对的键 | + | hashMap | HashMap | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("sdfs", 123); + hashMap.set("dfsghsf", 357); + hashMap.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries + +entries(): IterableIterator<[K, V]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + let iter = hashMap.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<[K, V]>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + + // 使用方法一: + for (let item of hashMap) { + console.log("key: " + item[0]); + console.log("value: " + item[1]); + } + + // 使用方法二: + let iter = hashMap[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashset.md b/zh-cn/application-dev/reference/apis/js-apis-hashset.md new file mode 100644 index 0000000000000000000000000000000000000000..cf0a8fcfc2ef15b87c88ddb89e6a7019609711c5 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-hashset.md @@ -0,0 +1,256 @@ +# 非线性容器HashSet + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {HashSet} from '@ohos.util.HashSet' +``` + + +## 权限 + +无 + +## HashSet + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | HashSet的元素个数 | + + +### constructor + +constructor(); + +HashSet的构造函数。 + +- 示例: + ``` + let hashSet = new HashSet(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该HashSet是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const hashSet = new HashSet(); + hashSet.isEmpty(); + ``` + + +### has + +has(value: T): boolean; + +判断此HashSet中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### add + +add(value: T): boolean; + +向HashSet中添加数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 添加成员数据 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 返回是否有成功增加元素 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### remove + +remove(value: T): boolean; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 返回是否成功删除指定元素 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + hashSet.remove("sdfs"); + ``` + + +### clear + +clear(): void; + +清除HashSet中的所有元素,并把length置为0。 + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + hashSet.clear(); + ``` + + +### values + +values(): IterableIterator<T>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + let iter = hashSet.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### forEach + +forEach(callbackfn: (value: T, key?: T, hashSet?: HashSet<T>) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素键值对的值 | + | key | T | 否 | 当前遍历到的元素键值对的值(和value相同) | + | hashSet | HashSet<T> | 否 | 当前调用forEach方法的实例对象 | + + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("sdfs"); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries +entries(): IterableIterator<[T, T]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[T, T]> | 返回一个迭代器 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + let iter = hashSet.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + + // 使用方法一: + for (let item of hashSet) { + console.log("value: " + item); + } + + // 使用方法二: + let iter = hashSet[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md new file mode 100644 index 0000000000000000000000000000000000000000..81af9fe3a0b734117c1324415d2119f0ee0e644a --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @@ -0,0 +1,551 @@ +# 非线性容器LightWeightMap + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {LightWeightMap} from '@ohos.util.LightWeightMap' +``` + + +## 权限 + +无 + +## LightWeightMap + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | LightWeightMap的元素个数 | + + +### constructor + +constructor(); + +LightWeightMap的构造函数。 + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该LightWeightMap是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const lightWeightMap = new LightWeightMap(); + lightWeightMap.isEmpty(); + ``` + + +### hasAll + +hasAll(map: LightWeightMap): boolean; + +判断此LightWeightMap中是否含有该指定map中的所有元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | map | LightWeightMap | 是 | 比较对象 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含所有元素 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let map = new LightWeightMap(); + map.set("sdfs", 356); + let result = lightWeightMap.hasAll(map); + ``` + + +### hasKey + +hasKey(key: K): boolean; + +判断此LightWeightMap中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### hasValue + +hasValue(value: V): boolean; + +判断此LightWeightMap中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.hasValue(123); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.hasValue(123); + ``` + + +### increaseCapacityTo + +increaseCapacityTo(minimumCapacity: number): void; + +将当前LightWeightMap扩容至可以容纳指定数量元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | minimumCapacity | number | 是 | 需要容纳数量 | + + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.increaseCapacityTo(10); + ``` + + +### get + +get(key: K): V; + +获取指定key所对应的value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回key映射的value值 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.get("sdfs"); + ``` + + +### getIndexOfKey + +getIndexOfKey(key: K): number; + +查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 被查找的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.getIndexOfKey("sdfs"); + ``` + + +### getIndexOfValue + +getIndexOfValue(value: V): number; + +查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 被查找的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.getIndexOfValue(123); + ``` + + +### getKeyAt + +getKeyAt(index: number): K; + +查找指定下标的元素键值对中key值,否则返回undefined。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 所查找的下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回该下标对应的元素键值对中key值 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.getKeyAt(1); + ``` + + +### setAll + +setAll(map: LightWeightMap): void; + +将一个LightWeightMap中的所有元素组添加到另一个lightweightmap中。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | map | LightWeightMap | 是 | 被添加元素的lightweightmap | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let map = new LightWeightMap(); + lightWeightMap.setAll(map); + ``` + + +### set +set(key: K, value: V): Object; + +向LightWeightMap中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 添加成员数据的键名 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Object | 返回添加后的hashmap | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + ``` + + +### remove + +remove(key: K): V; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回删除元素的值 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.remove("sdfs"); + ``` + + +### removeAt + +removeAt(index: number): boolean; + +删除指定下标的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定想要删除元素下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 确认是否成功删除元素 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.removeAt(1); + ``` + + +### setValueAt + +setValueAt(index: number, newValue: V): boolean; + +向LightWeightMap中具体位置替换键值对中的值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定替换数据下标 | + | newValue | V | 是 | 替换键值对中的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功替换指定位置数据 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.setValueAt(1, 3546); + ``` + + +### getValueAt + +getValueAt(index: number): V; + +获取LightWeightMap中具体位置键值对中的值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定查询数据下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回指定位置中键值对的值 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.getValueAt(1); + ``` + + +### clear + +clear(): void; + +清除LightWeightMap中的所有元素,并把length置为0。 + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.clear(); + ``` + + +### keys + +keys(): IterableIterator<K>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<K> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let iter = lightWeightMap.keys(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### values + +values(): IterableIterator<V>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<V> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let iter = lightWeightMap.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### forEach + +forEach(callbackfn: (value: V, key?: K, lightWeightMap?: LightWeightMap) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 当前遍历到的元素键值对的值 | + | key | K | 是 | 当前遍历到的元素键值对的键 | + | lightWeightMap | LightWeightMap | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("sdfs", 123); + lightWeightMap.set("dfsghsf", 357); + lightWeightMap.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries + +entries(): IterableIterator<[K, V]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let iter = lightWeightMap.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<[K, V]>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + + // 使用方法一: + for (let item of lightWeightMap) { + console.log("key: " + item[0]); + console.log("value: " + item[1]); + } + + // 使用方法二: + let iter = lightWeightMap[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md new file mode 100644 index 0000000000000000000000000000000000000000..8f31ac5037df748bfe566232281d937ab089a146 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @@ -0,0 +1,463 @@ +# 非线性容器LightWeightSet + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {LightWeightSet} from '@ohos.util.LightWeightSet' +``` + + +## 权限 + +无 + +## LightWeightSet + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | LightWeightSet的元素个数 | + + +### constructor + +constructor(); + +LightWeightSet的构造函数。 + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该容器是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const lightWeightSet = new LightWeightSet(); + lightWeightSet.isEmpty(); + ``` + +### add + +add(value: T): boolean; + +向此容器中添加数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 添加的成员数据 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功添加元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### addAll + +addAll(set: LightWeightSet<T>): boolean; + +将另一个容器中的所有元素组添加到当前容器中。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | set | LightWeightSet<T> | 是 | 提供添加元素的lightweightmap | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let set = new LightWeightSet(); + set.add("sfage"); + lightWeightSet.addAll(set); + ``` + + +### hasAll + +hasAll(set: LightWeightSet<T>): boolean; + +判断此容器中是否含有该指定set中的所有元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | set | LightWeightSet<T> | 是 | 比较对象 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含所有元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let set = new LightWeightSet(); + set.add("sdfs"); + let result = lightWeightSet.hasAll(set); + ``` + + +### has + +has(value: T): boolean; + +判断此容器中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.has(123); + lightWeightSet.add(123); + lightWeightSet.has(123); + ``` + + +### equal + +equal(obj: Object): boolean; + +判断此容器中是否含有该指定obj同类型。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | obj | Object | 是 | 比较对象 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否构成类型相同 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let obj = {"Ahfbrgrbgnutfodgorrogorgrogofdfdf", "sdfs"}; + let result = lightWeightSet.equal(obj); + ``` + + +### ensureCapacityTo + +ensureCapacityTo(minimumCapacity: number): void; + +将当前容器扩容至可以容纳指定数量元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | minimumCapacity | number | 是 | 需要容纳数量 | + + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.ensureCapacityTo(10); + ``` + + +### getIndexOf + +getIndexOf(key: T): number; + +获取指定key所对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 在lightweightset中指定数据的下标 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.getIndexOf("sdfs"); + ``` + + +### remove + +remove(key: T): T; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除元素的值 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.remove("sdfs"); + ``` + + +### removeAt + +removeAt(index: number): boolean; + +删除指定下标的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定想要删除元素下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 确认是否成功删除元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.removeAt(1); + ``` + + +### getValueAt + +getValueAt(index: number): T; + +获取此容器中具体位置的元素 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定查询数据下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回指定位置中元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.getValueAt(1); + ``` + + +### clear + +clear(): void; + +清除容器中的所有元素,并把length置为0。 + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.clear(); + ``` + + +### toString + +toString(): String; + +获取包含容器中所有键和值的字符串。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | String | 返回一个字符串 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.toString(); + ``` + + +### toArray + +toArray(): Array<T>; + +获取包含此容器中所有对象的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回一个数组 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.toString(); + ``` + + +### values + +values(): IterableIterator<T>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let iter = lightWeightSet.values(); + let index = 0; + while(index < lightWeightSet.length) { + console.log(JSON.stringify(iter.next().value)); + index++; + } + ``` + + +### forEach + +forEach(callbackfn: (value: T, key?: T, lightWeightSet?: LightWeightSet<T>) => void, thisArg?: Object): void; + +通过回调函数来遍历LightWeightSet实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | key | T | 否 | 当前遍历到的元素(和value相同) | + | lightWeightSet | LightWeightSet<T> | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("sdfs"); + lightWeightSet.add("dfsghsf"); + lightWeightSet.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries + +entries(): IterableIterator<[T, T]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[T, T]> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let iter = lightWeightSet.entries(); + let index = 0; + while(index < lightWeightSet.length) { + console.log(JSON.stringify(iter.next().value)); + index++; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + + // 使用方法一: + for (let item of lightWeightSet) { + console.log("value: " + item); + } + + // 使用方法二: + let iter = lightWeightSet[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md new file mode 100644 index 0000000000000000000000000000000000000000..8c8cd37ffd6d1da955c8dac7134b751bb2fa2b7a --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @@ -0,0 +1,551 @@ +# 线性容器LinkedList + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {LinkedList} from '@ohos.util.LinkedList' +``` + + +## 权限 + +无 + + +## LinkedList + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | LinkedList的元素个数 | + + +### constructor + +constructor(_head?: NodeObj<T>, _tail?: NodeObj<T>); + +LinkedList的构造函数。 + +- 参数: + | 参数名 | 类型 | 可读 | 可写 | 说明 | + | -------- | -------- | -------- | -------- | -------- | + | _head | NodeObj<T> | 是 | 否 | 入参对象,节点对象,含有element,和next指向,和prev指向 | + | _tail | NodeObj<T> | 是 | 否 | 入参对象,节点对象,含有element,和next指向,和prev指向 | + +- 示例: + ``` + let linkedList = new LinkedList(); + ``` + + +### add + +add(element: T): boolean; + +在LinkedList尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add("a"); + linkedList.add(1); + let b = [1, 2, 3]; + linkedList.add(b); + let c = {name : "lala", age : "13"}; + linkedList.add(false); + ``` +### addFirst + +addFirst(element: T): void; + +在LinkedList头部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.addFirst("a"); + linkedList.addFirst(1); + let b = [1, 2, 3]; + linkedList.addFirst(b); + let c = {name : "lala", age : "13"}; + linkedList.addFirst(false); + ``` + +### insert + +insert(element: T, index: number): void; + +在长度范围内任意插入指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 被插入的元素 | + | index | number | 是 | 被插入的位置索引 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.insert("A", 0); + linkedList.insert(0, 1); + linkedList.insert(true, 2); + ``` + +### has + +has(element: T): boolean; + +判断此LinkedList中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.has("Ahfbrgrbgnutfodgorrogorg"); + linkedList.add("Ahfbrgrbgnutfodgorrogorg"); + linkedList.has("Ahfbrgrbgnutfodgorrogorg"); + ``` + +### get + +get(index: number): T; + +根据下标获取LinkedList中的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 根据下标查找到的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(1); + linkedList.add(2); + linkedList.add(4); + linkedList.get(2); + ``` +### getLastIndexOf + +getLastIndexOf(element: T): number; + +返回指定元素最后一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素最后一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(1); + linkedList.add(2); + linkedList.add(4); + linkedList.getLastIndexOf(2); + ``` + +### getIndexOf + +getIndexOf(element: T): number; + +返回指定元素第一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(1); + linkedList.add(2); + linkedList.add(4); + linkedList.getIndexOf(2); + ``` +### removeByIndex + +removeByIndex(index: number): T; + +根据元素的下标值查找元素,返回元素后将其删除。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定元素的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(4); + linkedList.removeByIndex(2); + ``` +### removeFirst + +removeFirst(): T; + +删除并返回LinkedList的第一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(4); + linkedList.removeFirst(); + ``` +### removeLast + +removeLst(): T; + +删除并返回LinkedList的最后一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(4); + linkedList.removeLast(); + ``` + +### remove + +remove(element: T): boolean; + +删除查找到的第一个指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.remove(2); + ``` +### removeFirstFound + +removeFirstFound(element: T): boolean; + +删除第一次出现的指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.removeFirstFound(4); + ``` +### removeLastFound + +removeLastFound(element: T): boolean; + +删除最后一次出现的指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.removeLastFound(4); + ``` +### clone +clone(): LinkedList<T>; + +克隆一个与LinkedList一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | LinkedList<T> | 返回LinkedList对象实例 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.clone(); + ``` +### forEach +forEach(callbackfn: (value: T, index?: number, linkedlist?: LinkedList<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历LinkedList实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | linkedlist | LinkedList<T> | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.forEach((value, index) => { + console.log(value, index); + }); + ``` +### clear +clear(): void; + +清除LinkedList中的所有元素,并把length置为0。 + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.clear(); + ``` +### set +set(index: number, element: T): T; +将此 LinkedList 中指定位置的元素替换为指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 查找的下标值 | + | element | T | 是 | 用来替换的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T类型 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.set(2, "b"); + ``` +### convertToArray +convertToArray(): Array<T>; + +把当前LinkedList实例转换成数组,并返回转换后的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回数组类型 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.convertToArray(); + ``` + +### getFirst + +getFirst(): T; +获取LinkedList实例中的第一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.getFirst(); + ``` +### getLast + +getLast(): T; +获取LinkedList实例中的最后一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.getLast(); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器。 | + + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + + // 使用方法一: + for (let item of linkedList) { + console.log(item); + } + + // 使用方法二: + let iter = linkedList[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-list.md b/zh-cn/application-dev/reference/apis/js-apis-list.md new file mode 100644 index 0000000000000000000000000000000000000000..03a5b0e01e1497c7346c2b1c01c808c78bc2c9a7 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-list.md @@ -0,0 +1,561 @@ +# 线性容器List + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {List} from '@ohos.util.List' +``` + + +## 权限 + +无 + + +## List + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | List的元素个数 | + + +### constructor + +constructor(_head?: NodeObj<T>); + +List的构造函数。 + +- 参数: + | 参数名 | 类型 | 可读 | 可写 | 说明 | + | -------- | -------- | -------- | -------- | -------- | + | _head | NodeObj<T> | 是 | 否 | 入参对象,节点对象,含有element,和next指向 | + +- 示例: + ``` + let list = new List(); + ``` + + +### add + +add(element: T): boolean; + +在List尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let list = new List; + list.add("a"); + list.add(1); + let b = [1, 2, 3]; + list.add(b); + let c = {name : "lala", age : "13"}; + list.add(false); + ``` + +### insert + +insert(element: T, index: number): void; + +在长度范围内任意位置插入指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 被插入的元素 | + | index | number | 是 | 被插入的位置索引 | + +- 示例: + ``` + let list = new List(); + list.insert("A", 0); + list.insert(0, 1); + list.insert(true, 2); + ``` + +### has + +has(element: T): boolean; + +判断此List中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let list = new List(); + list.has("Ahfbrgrbgnutfodgorrogorg"); + list.add("Ahfbrgrbgnutfodgorrogorg"); + list.has("Ahfbrgrbgnutfodgorrogorg"); + ``` + +### get + +get(index: number): T; + +根据下标获取List中的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 要查找的下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 根据下标查找到的元素 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + list.add(1); + list.add(2); + list.add(4); + list.get(2); + ``` +### getLastIndexOf + +getLastIndexOf(element: T): number; + +查找指定元素最后一次出现的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 查找指定元素最后一次出现的下标值,查找失败返回-1 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + list.add(1); + list.add(2); + list.add(4); + list.getLastIndexOf(2); + ``` + +### getIndexOf + +getIndexOf(element: T): number; + +查找指定元素第一次出现的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回第一次找到指定元素的下标,没有找到返回-1 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + list.add(1); + list.add(2); + list.add(4); + list.getIndexOf(2); + ``` + +### equal + +equal(obj: Object): boolean; + +比较指定对象与此List是否相等。如果对象与此列表相同,返回true,否则返回false。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | obj | Object | 是 | 用来比较的对象 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 返回boolean类型 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + let obj1 = new List(); + obj1.add(2); + obj1.add(4); + obj1.add(5); + list.equal(obj1); + let obj2 = {name : "lala", age : "13"}; + list.equal(obj2); + ``` +### removeByIndex + +removeByIndex(index: number): T; + +根据元素的下标值查找元素,返回元素后将其删除。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定元素的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + list.add(4); + list.removeByIndex(2); + ``` + +### remove + +remove(element: T): boolean; + +删除查找到的第一个指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.remove(2); + ``` + +### replaceAllElements +replaceAllElements(callbackfn: (value: T, index?: number, list?: List<T>) => T, +thisArg?: Object): void; + +用户操作List中的元素,用操作后的元素替换原元素并返回操作后的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | list | List<T> | 否 | 当前调用replaceAllElements方法的实例对象 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.replaceAllElements((value, index) => { + return value = 2 * value; + }); + list.replaceAllElements((value, index) => { + return value = value - 2; + }); + ``` +### forEach +forEach(callbackfn: (value: T, index?: number, list?: List<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历List实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素。 | + | index | number | 否 | 当前遍历到的下标值。 | + | list | List<T> | 否 | 当前调用forEach方法的实例对象 | + + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.forEach((value, index) => { + console.log(value, index); + }); + + ``` +### sort +sort(comparator: (firstValue: T, secondValue: T) => number): void; + +对List中的元素进行一个排序操作。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 是 | 回调函数。 | + +- comparator的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | firstValue | T | 是 | 前一项元素 | + | secondValue | T | 是 | 后一项元素 | + + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.sort(a, (b => a - b)); + list.sort(a, (b => b - a)); + ``` +### getSubList +getSubList(fromIndex: number, toIndex: number): List<T>; + +根据下标截取List中的一段元素,并返回这一段List实例,包括起始值但不包括终止值。 +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | List<T> | 返回List对象实例 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.subList(2, 4); + list.subList(4, 3); + list.subList(2, 6); + ``` + +### clear +clear(): void; + +清除List中的所有元素,并把length置为0。 + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.clear(); + ``` +### set +set(index: number, element: T): T; +将此 List 中指定位置的元素替换为指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 查找的下标值 | + | element | T | 是 | 用来替换的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T类型 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.set(2, "b"); + + ``` +### convertToArray +convertToArray(): Array<T>; + +把当前List实例转换成数组,并返回转换后的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回数组类型 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.convertToArray(); + ``` +### isEmpty +isEmpty(): boolean; + +判断该List是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.isEmpty(); + ``` +### getFirst + +getFirst(): T; +获取List实例中的第一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let list = new Vector(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.getFirst(); + ``` +### getLast + +getLast(): T; +获取List实例中的最后一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let list = new Vector(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.getLast(); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器。 | + + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + + // 使用方法一: + for (let item of list) { + console.log(item); + } + + // 使用方法二: + let iter = list[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md new file mode 100644 index 0000000000000000000000000000000000000000..0c56ffe5dac2e3e85662a92c520ab6d27be776e5 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md @@ -0,0 +1,421 @@ +# 非线性容器PlainArray + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {PlainArray} from '@ohos.util.PlainArray' +``` + + +## 权限 + +无 + +## PlainArray + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | PlainArray的元素个数 | + + +### constructor + +constructor(); + +PlainArray的构造函数。 + +- 示例: + ``` + let plainArray = new PlainArray(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该容器是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const plainArray = new PlainArray(); + plainArray.isEmpty(); + ``` + + +### has + +has(key: number): boolean; + +判断此容器中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 查询的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.has(1); + plainArray.add(1, "sddfhf"); + plainArray.has(1); + ``` + + +### get + +get(key: number): T; + +获取指定key所对应的value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回key映射的value值 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.get(1); + ``` + + +### getIndexOfKey + +getIndexOfKey(key: number): number; + +查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 被查找的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.getIndexOfKey("sdfs"); + ``` + + +### getIndexOfValue + +getIndexOfValue(value: T): number; + +查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 被查找的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.getIndexOfValue("sddfhf"); + ``` + + +### getKeyAt + +getKeyAt(index: number): number; + +查找指定下标的元素键值对中key值,否则返回undefined。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 所查找的下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回该下标对应的元素键值对中key值 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.getKeyAt(1); + ``` + + +### clone + +clone(): PlainArray<T>; + +克隆一个一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | PlainArray<T> | 返回新的对象实例 | + +- 示例: + ``` + let plainArray = new ArrayList(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + let newPlainArray = plainArray.clone(); + ``` + + +### add + +add(key: number, value: T): boolean; + +向容器中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 添加成员数据的键名 | + | value | T | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 确认是否成功添加 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + ``` + + +### remove + +remove(key: number): T; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除元素的值 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.remove(2); + ``` + + +### removeAt + +removeAt(index: number): boolean; + +删除指定下标的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定想要删除元素下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 确认是否成功删除元素 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.removeAt(1); + ``` + + +### removeRangeFrom + +removeRangeFrom(index: number, size: number): number; + +删除一定范围内的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 删除元素的起始下标 | + | size | number | 是 | 期望删除元素个数 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 实际删除元素个数 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.removeAt(1, 3); + ``` + + +### setValueAt + +setValueAt(index: number, newValue: T): void; + +向容器中具体位置替换键值对中的值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定替换数据下标 | + | newValue | T | 是 | 替换键值对中的值 | + + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.setValueAt(1, 3546); + ``` + + +### toString + +toString(): String; + +获取包含容器中所有键和值的字符串。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | String | 返回一个字符串 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.toString(); + ``` + + +### clear + +clear(): void; + +清除容器中的所有元素,并把length置为0。 + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.clear(); + ``` + + +### forEach + +forEach(callbackfn: (value: T, key?: number, plainArray?: PlainArray) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素键值对的值 | + | key | number | 是 | 当前遍历到的元素键值对的键 | + | plainArray | PlainArray | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<[number, T]>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[number, T]> | 返回一个迭代器 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + + // 使用方法一: + for (let item of plainArray) { + console.log("index: " + item[0]); + console.log("value: " + item[1]); + } + + // 使用方法二: + let iter = plainArray[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-power.md b/zh-cn/application-dev/reference/apis/js-apis-power.md index 8304b440be0a7fa40c3be3af046863b6cb2da3af..281e065072a9cbd418ab2755255613665be337b9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-power.md +++ b/zh-cn/application-dev/reference/apis/js-apis-power.md @@ -10,14 +10,9 @@ import power from '@ohos.power'; ``` +## 系统能力 -## 权限 - -关机权限: ohos.permission.SHUTDOWN - -重启权限: ohos.permission.REBOOT - -重启并进入recovery模式的权限:ohos.permission.REBOOT_RECOVERY +SystemCapability.PowerManager.PowerManager ## power.shutdownDevice @@ -26,6 +21,8 @@ shutdownDevice(reason: string): void 系统关机。 +需要权限:ohos.permission.SHUTDOWN + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -44,6 +41,8 @@ rebootDevice(reason: string): void 重启设备。 +需要权限:ohos.permission.REBOOT(重启权限)、ohos.permission.REBOOT_RECOVERY(重启并进入recovery模式的权限) + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-process.md b/zh-cn/application-dev/reference/apis/js-apis-process.md index 5aa3245c385bfbaa6d6f190ec708844dbc5ec51f..1c6b6523c02888233aab036de160305b5b7bcdf6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-process.md +++ b/zh-cn/application-dev/reference/apis/js-apis-process.md @@ -11,11 +11,6 @@ import process from '@ohos.process'; ``` -## 权限 - -无 - - ## 属性 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -143,12 +138,12 @@ kill函数用来发送信号给子进程,结束指定进程。 isIsolatedProcess(): boolean -检查进程是否被隔离。 +判断进程是否被隔离。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 进程是否隔离 | + | boolean | 返回判断结果,如果返回true表示进程被隔离。 | - 示例: ``` @@ -160,17 +155,17 @@ isIsolatedProcess(): boolean isAppUid(v:number): boolean -判断是否特定程序的uid。 +判断uid是否属于应用程序。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | v | number | 是 | 进程的id。 | + | v | number | 是 | 应用程序的uid。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 是否是当前app的uid | + | boolean | 返回判断结果,如果返回true表示为应用程序的uid。| - 示例: ``` @@ -182,12 +177,12 @@ isAppUid(v:number): boolean is64Bit(): boolean -判断运行环境是不是64位。 +判断运行环境是否64位。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 是不是64位环境 | + | boolean | 返回判断结果,如果返回true表示为64位环境。 | - 示例: ``` @@ -204,12 +199,12 @@ getUidForName(v:string): number - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | v | string | 是 | 进程name | + | v | string | 是 | 进程名。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 进程的uid | + | number | 返回进程uid。| - 示例: ``` @@ -221,17 +216,17 @@ getUidForName(v:string): number getThreadPriority(v:number): number -根据指定的 TID 获取线程优先级。 +根据指定的tid获取线程优先级。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | v | number | 是 | 进程的id | + | v | number | 是 | 指定的线程tid。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 进程的优先级 | + | number | 返回线程的优先级。 | - 示例: ``` @@ -249,7 +244,7 @@ getStartRealtime() :number - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 时间 | + | number | 返回经过的实时时间。| - 示例: ``` @@ -261,12 +256,12 @@ getStartRealtime() :number getAvailableCores() :number[] -获取多核设备上当前进程可用的 CPU 内核。 +获取多核设备上当前进程可用的CPU内核。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | number[] | 可用内核数 | + | number[] | 返回可用内核数。 | - 示例: ``` @@ -283,7 +278,7 @@ getPastCputime() :number - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 时间 | + | number | 返回经过的CPU时间。 | - 示例: ``` @@ -295,17 +290,17 @@ getPastCputime() :number getSystemConfig(name:number): number -用该方法发送signal到指定的进程。 +获取系统配置信息。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | number | 是 | 系统配置参数名 | + | name | number | 是 | 指定系统配置参数名。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 配置信息 | + | number | 返回系统配置信息。 | - 示例: ``` @@ -323,12 +318,12 @@ getEnvironmentVar(name:string): string - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | string | 是 | 环境名 | + | name | string | 是 | 环境变量名。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | string | 环境名对应的value | + | string | 返回环境变量名对应的value。 | - 示例: ``` @@ -367,7 +362,7 @@ runCmd(command: string, options?: { timeout : number, killSignal :number | str var result = child.wait(); child.getOutput.then(val=>{ console.log("child.getOutput = " + val); - } + }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-queue.md b/zh-cn/application-dev/reference/apis/js-apis-queue.md new file mode 100644 index 0000000000000000000000000000000000000000..cef46e3686c6497b449ec7704a053b602d68695d --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-queue.md @@ -0,0 +1,180 @@ +# 线性容器Queue + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {Queue} from '@ohos.util.Queue' +``` + + +## 权限 + +无 + + +## Queue + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | Queue的元素个数 | + + +### constructor + +constructor(); + +Queue的构造函数。 + + +- 示例: + ``` + let queue = new Queue(); + ``` + + +### add + +add(element: T): boolean; + +在队列尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let queue = new Queue(); + queue.add("a"); + queue.add(1); + let b = [1, 2, 3]; + queue.add(b); + let c = {name : "lala", age : "13"}; + queue.add(false); + ``` + +### pop + +pop(): T + +删除头元素并返回该删除元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let queue = new Queue(); + queue.add(2); + queue.add(4); + queue.add(5); + queue.add(2); + queue.add(4); + queue.pop(); + ``` + +### getFirst + +getFirst(): T; + +获取队列的头元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回尾元素 | + +- 示例: + ``` + let queue = new Queue(); + queue.add(2); + queue.add(4); + queue.add(5); + queue.add(2); + queue.getFirst(); + ``` + +### forEach +forEach(callbackfn: (value: T, index?: number, queue?: Queue<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历Queue实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数。 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | queue | Queue<T> | 否 | 当前调用forEach方法的实例对象 | + + +- 示例: + ``` + let queue = new Queue(); + queue.add(2); + queue.add(4); + queue.add(5); + queue.add(4); + queue.forEach((value, index) => { + console.log(value, index); + }); + + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + + +- 示例: + ``` + let queue = new Queue(); + queue.add(2); + queue.add(4); + queue.add(5); + queue.add(4); + + // 使用方法一: + for (let item of queue) { + console.log(item); + } + + // 使用方法二: + let iter = queue[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md index 302ec50fe59579adac4133cd9f5e41df1ce37536..5d634d453ea544c2eff9e67b164e41d6e4de6a1d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @@ -11,6 +11,11 @@ import reminderAgent from'@ohos.reminderAgent'; ``` +## 系统能力 + +SystemCapability.Notification.ReminderAgent + + ## 权限 ohos.permission.PUBLISH_AGENT_REMINDER diff --git a/zh-cn/application-dev/reference/apis/js-apis-runninglock.md b/zh-cn/application-dev/reference/apis/js-apis-runninglock.md index 887fa5eb22a99229226be3d13c70037e44d61318..c6f8ba213794bcd5398c20148c79624c45c3c698 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-runninglock.md +++ b/zh-cn/application-dev/reference/apis/js-apis-runninglock.md @@ -11,9 +11,9 @@ import runninglock from '@ohos.runningLock'; ``` -## 权限 +## 系统能力 -申请、使用锁的权限:ohos.permission.RUNNING_LOCK +SystemCapability.PowerManager.PowerManager ## RunningLockType @@ -84,6 +84,8 @@ createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback&l 创建RunningLock锁。 +需要权限:ohos.permission.RUNNING_LOCK + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -113,6 +115,8 @@ createRunningLock(name: string, type: RunningLockType): Promise<RunningLock&g 创建Runninglock锁。 +需要权限:ohos.permission.RUNNING_LOCK + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-security-accessToken.md b/zh-cn/application-dev/reference/apis/js-apis-security-accessToken.md new file mode 100644 index 0000000000000000000000000000000000000000..09e204bff8581a44fd227abd2f98c0050a930ea4 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-security-accessToken.md @@ -0,0 +1,216 @@ +# 访问控制管理 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +``` +import abilityAccessCtrl from '@ohos.abilityAccessCtrl' +``` + +## 系统能力 +SystemCapability.Security.AccessToken + +## abilityAccessCtrl.createAtManager + +createAtManager(): AtManager + +访问控制管理:获取访问控制模块对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | [AtManager](#atManager) | 获取访问控制模块的实例。 | + +- 示例: + ``` + var AtManager = abilityAccessCtrl.createAtManager(); + ``` + +## AtManager + +管理访问控制模块的实例。 + +### verifyAccessToken + +verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> + +校验应用是否授予权限,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------- | ---- | ------------------------------------------ | + | tokenID | number | 是 | 要校验的目标应用的身份标识。 | + | permissionName | string | 是 | 需要校验的权限名称。 | + +- 返回值: + + | 类型 | 说明 | + | :------------ | :---------------------------------- | + | Promise<GrantStatus> | Promise实例,用于获取异步返回的授权状态结果。 | + +- 示例: + + ``` + const AtManager = abilityAccessCtrl.createAtManager(); + let tokenID = 0; + let promise = AtManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); + promise.then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); + }); + ``` + +### grantUserGrantedPermission + +grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> + +授予应用user grant权限,使用Promise方式异步返回结果。 + +需要权限:ohos.permission.GRANT_SENSITIVE_PERMISSIONS。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | --------- | ------------------- | ---- | ------------------------------------------------------------ | + | tokenID | number | 是 | 目标应用的身份标识。 | + | permissionName | string | 是 | 被授予的权限名称。 | + | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | + +- 返回值: + + | 类型 | 说明 | + | :------------ | :---------------------------------- | + | Promise<number> | Promise实例,用于获取异步返回的授权操作结果。 | +- 示例: + + ``` + const AtManager = abilityAccessCtrl.createAtManager(); + let tokenID = 0; + let promise = AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); + promise.then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); + }); + ``` + + + +### grantUserGrantedPermission + +grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<number>): void + +授予应用user grant权限,使用callback回调异步返回结果。 + +需要权限:ohos.permission.GRANT_SENSITIVE_PERMISSIONS。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | --------- | ------------------- | ---- | ------------------------------------------------------------ | + | tokenID | number | 是 | 目标应用的身份标识。 | + | permissionName | string | 是 | 被授予的权限名称。 | + | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | + | callback | AsyncCallback<number> | 是 | 检查授予应用user grant权限的操作结果同步的回调。 | + +- 示例: + + ``` + const AtManager = abilityAccessCtrl.createAtManager(); + let tokenID = 0; + let permissionFlag = 1; + AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS",permissionFlag, data => { + console.log(`callback: data->${JSON.stringify(data)}`); + }); + ``` + +### revokeUserGrantedPermission + +revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> + +撤销应用user grant权限,使用Promise方式异步返回结果。 + +需要权限:ohos.permission.REVOKE_SENSITIVE_PERMISSIONS。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | --------- | ------------------- | ---- | ------------------------------------------------------------ | + | tokenID | number | 是 | 目标应用的身份标识。 | + | permissionName | string | 是 | 被撤销的权限名称。 | + | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | + +- 返回值: + + | 类型 | 说明 | + | :------------ | :---------------------------------- | + | Promise<number> | Promise实例,用于获取异步返回的授权操作结果。 | + +- 示例: + + ``` + const AtManager = abilityAccessCtrl.createAtManager(); + let tokenID = 0; + let permissionFlag = 1; + let promise = AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag); + promise.then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); + }); + ``` + +### revokeUserGrantedPermission + +revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<number>): void + +撤销应用user grant权限,使用callback回调异步返回结果。 + +需要权限:ohos.permission.REVOKE_SENSITIVE_PERMISSIONS。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | --------- | ------------------- | ---- | ------------------------------------------------------------ | + | tokenID | number | 是 | 目标应用的身份标识。 | + | permissionName | string | 是 | 被撤销的权限名称。 | + | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | + | callback | AsyncCallback<number> | 是 | 检查撤销应用user grant权限的操作结果同步的回调。 | + +- 示例: + + ``` + const AtManager = abilityAccessCtrl.createAtManager(); + let tokenID = 0; + AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS",permissionFlag, data => { + console.log(`callback: data->${JSON.stringify(data)}`); + }); + ``` + +### getPermissionFlags + +getPermissionFlags(tokenID: number, permissionName: string): Promise<number> + +获取指定应用的指定权限的flag,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | --------- | ------------------- | ---- | ------------------------------------------------------------ | + | tokenID | number | 是 | 目标应用的身份标识。 | + | permissionName | string | 是 | 查询的权限名称。 | + +- 返回值: + + | 类型 | 说明 | + | :------------ | :---------------------------------- | + | Promise<number> | Promise实例,用于获取异步返回的查询结果。 | + +- 示例: + + ``` + const AtManager = abilityAccessCtrl.createAtManager(); + let tokenID = 0; + let promise = AtManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); + promise.then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); + }); + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md index 1abb59effb99cabfbb0111aef6c201f1b2448228..838641fb4ee7d5f08e671f789e9000f31f602164 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -10,6 +10,9 @@ import sensor from '@ohos.sensor'; ``` +## 系统能力 + +SystemCapability.Sensors.Sensor ## 权限列表 @@ -22,9 +25,9 @@ import sensor from '@ohos.sensor'; 陀螺仪:ohos.permission.GYROSCOPE -## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER) -on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<AccelerometerResponse>,options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<AccelerometerResponse>,options?: Options): void 监听加速度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -39,23 +42,23 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<Acc - 示例: ``` - sensor.on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } - console.info('X-coordinate component: ' + data.x); + console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) -on(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback<LinearAccelerometerResponse>, options?: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback<LinearAccelerometerResponse>, options?: Options): void 监听线性加速度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -68,23 +71,23 @@ on(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback< - 示例: ``` - sensor.on(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(error,data){ - if (error) { + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(error,data){ + if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) -on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallback<AccelerometerUncalibratedResponse>, options?: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallback<AccelerometerUncalibratedResponse>, options?: Options): void 监听未校准加速度计传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -97,7 +100,7 @@ on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallb - 示例: ``` - sensor.on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -108,15 +111,15 @@ on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallb console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_GRAVITY) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY) -on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<GravityResponse>,options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<GravityResponse>,options?: Options): void 监听重力传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -129,23 +132,23 @@ on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<GravityRe - 示例: ``` - sensor.on(type:SensorType.SENSOR_TYPE_ID_GRAVITY,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } - console.info('X-coordinate component: ' + data.x); + console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE) -on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<GyroscopeResponse>, options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<GyroscopeResponse>, options?: Options): void 监听陀螺仪传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -158,23 +161,23 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<Gyrosco - 示例: ``` - sensor.on(type:SensorType.SENSOR_TYPE_ID_GUROSCOPE,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } - console.info('X-coordinate component: ' + data.x); + console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) -on(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback<GyroscopeUncalibratedResponse>, options?: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback<GyroscopeUncalibratedResponse>, options?: Options): void 监听未校准陀螺仪传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -187,26 +190,26 @@ on(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback& - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } - console.info('X-coordinate component: ' + data.x); + console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); + console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) -on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: AsyncCallback<SignificantMotionResponse>, options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: AsyncCallback<SignificantMotionResponse>, options?: Options): void 监听大幅动作传感器数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -219,21 +222,21 @@ on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: AsyncCallback&l - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,function(error,data){ + sensor.on(sensor.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} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) -on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: AsyncCallback<PedometerDetectResponse>, options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: AsyncCallback<PedometerDetectResponse>, options?: Options): void 监听计步检测传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -246,21 +249,21 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: AsyncCallback& - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,function(error,data){ if (error) { - console.error(""Subscription failed. Error code: " + error.code + "; message: " + error.message); + console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('Scalar data: ' + data.scalar); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_PEDOMETER) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER) -on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<PedometerResponse>, options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<PedometerResponse>, options?: Options): void 监听计步传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -273,21 +276,21 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<Pedomet - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('Steps: ' + data.steps); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) -on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback<AmbientTemperatureResponse>, options?: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback<AmbientTemperatureResponse>, options?: Options): void 监听环境温度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -300,21 +303,21 @@ on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback< - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('Temperature: ' + data.temperature); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) -on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback<MagneticFieldResponse>,options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback<MagneticFieldResponse>,options?: Options): void 监听磁场传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -327,7 +330,7 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback<Ma - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -335,15 +338,15 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback<Ma console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) -on(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCallback<MagneticFieldUncalibratedResponse>, options: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCallback<MagneticFieldUncalibratedResponse>, options: Options): void 监听未校准磁场传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -356,26 +359,26 @@ on(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCall - 示例: ``` - ensor.on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - console.info('X-coordinate bias: ' + data.biasX); + console.info('X-coordinate component: ' + data.x); + console.info('Y-coordinate component: ' + data.y); + console.info('Z-coordinate component: ' + data.z); + console.info('X-coordinate bias: ' + data.biasX); console.info('Y-coordinate bias: ' + data.biasY); console.info('Z-coordinate bias: ' + data.biasZ); - } - {interval: 10000000} //设置数据的上报频率。 + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_PROXIMITY) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY) -on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<ProximityResponse>,options?: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<ProximityResponse>,options?: Options): void 监听接近光传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -388,21 +391,21 @@ on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<Proximi - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('Distance: ' + data.distance); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_HUMIDITY) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY) -on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<HumidityResponse>,options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<HumidityResponse>,options?: Options): void 监听湿度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -415,21 +418,21 @@ on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<Humidity - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('Humidity: ' + data.humidity); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_BAROMETER) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER) -on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<BarometerResponse>,options?: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<BarometerResponse>,options?: Options): void 监听气压计传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -442,21 +445,21 @@ on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<Baromet - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_BAROMETER,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('Atmospheric pressure: ' + data.pressure); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_HALL) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL) -on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResponse>, options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResponse>, options?: Options): void 监听霍尔传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -469,21 +472,21 @@ on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResponse - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_HALL,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HALL,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('Status: ' + data.status); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) -on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback<LightResponse>, options?: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback<LightResponse>, options?: Options): void 监听环境光传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -496,21 +499,21 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback<Lig - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } - console.info(''Illumination: ' + data.intensity); - } - {interval: 10000000} + console.info(' Illumination: ' + data.intensity); + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_ORIENTATION) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION) -on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<OrientationResponse>, options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<OrientationResponse>, options?: Options): void 监听方向传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -523,7 +526,7 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<Orien - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -531,15 +534,15 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<Orien console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) -on(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback<RotationVectorResponse>,options?: Options): void +on(type:sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback<RotationVectorResponse>,options?: Options): void 监听旋转矢量传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -552,7 +555,7 @@ on(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback<Rota - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -560,15 +563,15 @@ on(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback<Rota console.info('X-coordinate component: ' + data.x); console.info('Y-coordinate component: ' + data.y); console.info('Z-coordinate component: ' + data.z); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.on(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +## sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) -on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback<WearDetectionResponse>,options?: Options): void +on(type: sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback<WearDetectionResponse>,options?: Options): void 监听佩戴检测传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 @@ -581,21 +584,21 @@ on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback<We - 示例: ``` - sensor.on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(error,data){ + sensor.on(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } console.info('Wear status: ' + data.value); - } - {interval: 10000000} + }, + {interval: 10000000} ); ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER) -once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<AccelerometerResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<AccelerometerResponse>): void 监听加速度传感器的数据变化一次。 @@ -607,7 +610,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<A - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER,function(error,data){ if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -620,9 +623,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback<A ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION) -once(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback<LinearAccelerometerResponse>): void +once(type:sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback<LinearAccelerometerResponse>): void 监听线性加速度传感器数据变化一次。 @@ -634,7 +637,7 @@ once(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback&l - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -647,9 +650,9 @@ once(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback&l ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED) -once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallback<AccelerometerUncalibratedResponse>): void +once(type:sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallback<AccelerometerUncalibratedResponse>): void 监听未校准加速度传感器的数据变化一次。 @@ -661,7 +664,7 @@ once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCal - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -677,9 +680,9 @@ once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCal ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_GRAVITY) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY) -once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<GravityResponse>): void +once(type:sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<GravityResponse>): void 监听重力传感器的数据变化一次。 @@ -691,7 +694,7 @@ once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<Gravity - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_GRAVITY, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -704,9 +707,9 @@ once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback<Gravity ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE) -once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<GyroscopeResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<GyroscopeResponse>): void 监听陀螺仪传感器的数据变化一次。 @@ -718,7 +721,7 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<Gyros - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -731,9 +734,9 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback<Gyros ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED) -once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback<GyroscopeUncalibratedResponse>): void +once(type:sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback<GyroscopeUncalibratedResponse>): void 监听未校准陀螺仪传感器的数据变化一次。 @@ -745,7 +748,7 @@ once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallbac - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -761,9 +764,9 @@ once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallbac ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION) -once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback:AsyncCallback<SignificantMotionResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback:AsyncCallback<SignificantMotionResponse>): void 监听有效运动传感器的数据变化一次。 @@ -775,7 +778,7 @@ once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback:AsyncCallback&l - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -786,9 +789,9 @@ once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback:AsyncCallback&l ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION) -once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback:AsyncCallback<PedometerDetectResponse>): void +once(type:sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback:AsyncCallback<PedometerDetectResponse>): void 监听计步检测传感器数据变化一次。 @@ -800,7 +803,7 @@ once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback:AsyncCallback&l - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -811,9 +814,9 @@ once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback:AsyncCallback&l ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_PEDOMETER) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER) -once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<PedometerResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<PedometerResponse>): void 监听计步器传感器数据变化一次。 @@ -825,7 +828,7 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<Pedom - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -836,9 +839,9 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback<Pedom ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE) -once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback<AmbientTemperatureResponse>): void +once(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback<AmbientTemperatureResponse>): void 监听环境温度传感器数据变化一次。 @@ -850,7 +853,7 @@ once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback&l - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -861,9 +864,9 @@ once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback&l ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD) -once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback<MagneticFieldResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback<MagneticFieldResponse>): void 监听磁场传感器数据变化一次。 @@ -875,7 +878,7 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback< - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -888,9 +891,9 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback< ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED) -once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCallback<MagneticFieldUncalibratedResponse>): void +once(type:sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCallback<MagneticFieldUncalibratedResponse>): void 监听未校准磁场传感器数据变化一次。 @@ -902,7 +905,7 @@ once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCa - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -918,9 +921,9 @@ once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCa ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_PROXIMITY) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY) -once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<ProximityResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<ProximityResponse>): void 监听接近光传感器数据变化一次。 @@ -932,7 +935,7 @@ once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<Proxi - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -943,9 +946,9 @@ once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback<Proxi ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_HUMIDITY) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY) -once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<HumidityResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<HumidityResponse>): void 监听湿度传感器数据变化一次。 @@ -957,7 +960,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<Humidi - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_HUMIDITY, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -968,9 +971,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback<Humidi ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_BAROMETER) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER) -once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<BarometerResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<BarometerResponse>): void 监听气压计传感器数据变化一次。 @@ -982,7 +985,7 @@ once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<Barom - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_BAROMETER, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -993,9 +996,9 @@ once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback<Barom ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_HALL) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL) -once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResponse>): void 监听霍尔传感器数据变化一次。 @@ -1007,7 +1010,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResp - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_HALL, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HALL, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -1018,9 +1021,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback<HallResp ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT) -once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback<LightResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback<LightResponse>): void 监听环境光传感器数据变化一次。 @@ -1032,20 +1035,20 @@ once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback<L - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; } - console.info(''Illumination: ' + data.intensity); + console.info(' Illumination: ' + data.intensity); } ); ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_ORIENTATION) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION) -once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<OrientationResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<OrientationResponse>): void 监听方向传感器数据变化一次。 @@ -1057,7 +1060,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<Ori - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_ORIENTATION, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -1070,9 +1073,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback<Ori ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR) -once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback<RotationVectorResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback<RotationVectorResponse>): void 监听旋转矢量传感器数据变化一次。 @@ -1084,7 +1087,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback< - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -1097,9 +1100,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback< ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_HEART_RATE) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE) -once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback<HeartRateResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback<HeartRateResponse>): void 监听心率传感器数据变化一次。 @@ -1111,7 +1114,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback<Hear - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_HEART_RATE, function(error, data) { + sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, function(error, data) { if (error) { console.error("Subscription failed. Error code: " + error.code + "; message: " + error.message); return; @@ -1122,9 +1125,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback<Hear ``` -## sensor.once(SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) +## sensor.once(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION) -once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback<WearDetectionResponse>): void +once(type: sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback<WearDetectionResponse>): void 监听佩戴检测传感器数据变化一次。 @@ -1136,7 +1139,7 @@ once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback< - 示例: ``` - sensor.once(type:SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, function(error, data) { + sensor.once(sensor.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; @@ -1161,7 +1164,7 @@ off(type: SensorType, callback?: AsyncCallback<void>): void - 示例: ``` - sensor.off(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error) { + sensor.off(sensor.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; diff --git a/zh-cn/application-dev/reference/apis/js-apis-stack.md b/zh-cn/application-dev/reference/apis/js-apis-stack.md new file mode 100644 index 0000000000000000000000000000000000000000..a9250af729524f7f1c2277e1dbb91b27ac081e83 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-stack.md @@ -0,0 +1,222 @@ +# 线性容器Stack + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {Stack} from '@ohos.util.Stack' +``` + + +## 权限 + +无 + + +## Stack + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | Stack的元素个数 | + + +### constructor + +constructor(); + +Stack的构造函数。 + + +- 示例: + ``` + let stack = new Stack(); + ``` + + +### push + +push(item: T): T; + +在栈顶插入元素,并返回该元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | item | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回被添加进去的元素 | + +- 示例: + ``` + let stack = new Stack(); + stack.push("a"); + stack.push(1); + let b = [1, 2, 3]; + stack.push(b); + let c = {name : "lala", age : "13"}; + stack.push(false); + ``` + +### pop + +pop(): T; + +删除栈顶元素并返回该删除元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(2); + stack.push(4); + stack.pop(); + ``` + +### peek + +peek(): T; + +获取并返回栈顶元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回栈顶元素 | + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(2); + stack.peek(); + ``` +### locate + +locate(element: T): number; + +返回指定元素第一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 找到就返回下标值,查找失败返回-1 | +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(2); + stack.locate(2); + ``` + +### forEach +forEach(callbackfn: (value: T, index?: number, stack?: Stack<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历Stack实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素。 | + | index | number | 否 | 当前遍历到的下标值。 | + | stack | Stack<T> | 否 | 当前调用forEach方法的实例对象。 | + + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(4); + stack.forEach((value, index) => { + console.log(value, index); + }); + ``` +### isEmpty +isEmpty(): boolean; + +判断该栈是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(4); + stack.isEmpty(); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(4); + + // 使用方法一: + for (let item of stack) { + console.log(item); + } + + // 使用方法二: + let iter = stack[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-treemap.md b/zh-cn/application-dev/reference/apis/js-apis-treemap.md new file mode 100644 index 0000000000000000000000000000000000000000..c5c7abe34f92fd7d6de77c0abbf36ae4caa853a8 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-treemap.md @@ -0,0 +1,476 @@ +# 非线性容器TreeMap + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {TreeMap} from '@ohos.util.TreeMap' +``` + + +## 权限 + +无 + +## TreeMap + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | TreeMap的元素个数 | + + +### constructor + +constructor(comparator?:(firstValue: K, secondValue: K) => boolean); + +TreeMap的构造函数。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 否 | 用户自定义的比较函数 | + +- 示例: + ``` + let treeMap = new TreeMap(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该容器是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const treeMap = new TreeMap(); + treeMap.isEmpty(); + ``` + + +### hasKey + +hasKey(key: K): boolean; + +判断此容器中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### hasValue + +hasValue(value: V): boolean; + +判断此容器中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.hasValue(123); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.hasValue(123); + ``` + + +### get + +get(key: K): V; + +获取指定key所对应的value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回key映射的value值 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.get("sdfs"); + ``` + + +### getFirstKey + +getFirstKey(): K; + +获取容器中排序第一的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回排序第一的数据 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let result = treeMap.getFirstKey(); + ``` + + +### getLastKey + +getLastKey(): K; + +获取容器中排序最后的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回排序最后的数据 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let result = treeMap.getLastKey(); + ``` + + +### setAll + +setAll(map: TreeMap): void; + +将一个treemap中的所有元素组添加到另一个treemap中。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | map | TreeMap | 是 | 被添加元素的treemap | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let map = new TreeMap(); + treeMap.setAll(map); + ``` + + +### set +set(key: K, value: V): Object; + +向treemap中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 添加成员数据的键名 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Object | 返回添加后的hashmap | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + ``` + + +### remove + +remove(key: K): V; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回删除元素的值 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.remove("sdfs"); + ``` + + +### getLowerByKey + +getLowerByKey(key: K): K; + +获取容器中比传入key排序靠前一位的key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 对比的key值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回排序中key前一位的数据 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.set("zdfgsd", 356); + let result = treeMap.getLowerByKey("sdfs"); + ``` + + +### getHigherByKey + +getHigherByKey(key: K): K; + +获取容器中比传入key排序靠后一位的key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 对比的key值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回排序中key后一位的数据 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.set("zdfgsd", 356); + let result = treeMap.getHigherByKey("sdfs"); + ``` + + +### replace +replace(key: K, value: V): boolean; + +对TreeMap中一组数据进行更新(替换)。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定替换的元素 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功对已有数据进行替换 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("sdfs", 123); + treeMap.replace("sdfs", 357); + ``` + + +### clear + +clear(): void; + +清除TreeMap中的所有元素,并把length置为0。 + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.clear(); + ``` + + +### keys + +keys(): IterableIterator<K>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<K> | 返回一个迭代器 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let iter = treeMap.keys(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### values + +values(): IterableIterator<V>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<V> | 返回一个迭代器 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let iter = treeMap.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### forEach + +forEach(callbackfn: (value: V, key?: K, treeMap?: TreeMap) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 当前遍历到的元素键值对的值 | + | key | K | 是 | 当前遍历到的元素键值对的键 | + | treeMap | TreeMap | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("sdfs", 123); + treeMap.set("dfsghsf", 357); + treeMap.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries + +entries(): IterableIterator<[K, V]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let iter = treeMap.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<[K, V]>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + + // 使用方法一: + for (let item of treeMap) { + console.log("key: " + item[0]); + console.log("value: " + item[1]); + } + + // 使用方法二: + let iter = treeMap[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-treeset.md b/zh-cn/application-dev/reference/apis/js-apis-treeset.md new file mode 100644 index 0000000000000000000000000000000000000000..30f1a22033dc77341aa214bcb1d835055c8922cf --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-treeset.md @@ -0,0 +1,393 @@ +# 非线性容器TreeSet + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {TreeSet} from '@ohos.util.TreeSet' +``` + + +## 权限 + +无 + +## TreeSet + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | TreeSet的元素个数 | + + +### constructor + +constructor(comparator?:(firstValue: T, secondValue: T) => boolean); + +TreeSet的构造函数。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 否 | 用户自定义的比较函数 | + +- 示例: + ``` + let treeSet = new TreeSet(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该容器是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const treeSet = new TreeSet(); + treeSet.isEmpty(); + ``` + + +### has + +has(value: T): boolean; + +判断此容器中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.has(123); + treeSet.add(123); + treeSet.has(123); + ``` + + +### getFirstValue + +getFirstValue(): T; + +获取容器中排序第一的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回排序第一的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let result = treeSet.getFirstValue(); + ``` + + +### getLastValue + +getLastValue(): T; + +获取容器中排序最后的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回排序最后的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let result = treeSet.getLastValue(); + ``` + + +### add +add(value: T): boolean; + +向TreeSet中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 添加的成员数据 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功添加新数据至容器 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### remove + +remove(key: T): boolean; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 指定的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 判断是否成功删除元素 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + treeSet.remove("sdfs"); + ``` + + +### getLowerValue + +getLowerValue(key: T): T; + +获取容器中比传入元素排序靠前一位的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 对比的元素值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回排序中对比元素前一位的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + treeSet.add("zdfgsd"); + let result = treeSet.getLowerValue("sdfs"); + ``` + + +### getHigherValue + +getHigherValue(key: T): T; + +获取容器中比传入元素排序靠后一位的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 对比的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回排序中传入元素后一位的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + treeSet.add("zdfgsd"); + let result = treeSet.getHigherValue("sdfs"); + ``` + + +### popFirst + +popFirst(): T; + +删除容器中排序最前的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let result = treeSet.popFirst(); + ``` + + +### popLast + +popLast(): T; + +删除容器中排序最后的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let result = treeSet.popLast(); + ``` + + +### clear + +clear(): void; + +清除容器中的所有元素,并把length置为0。 + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + treeSet.clear(); + ``` + + +### values + +values(): IterableIterator<T>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let iter = treeSet.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### forEach + +forEach(callbackfn: (value: T, key?: T, treeSet?: TreeSet<T>) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | key | T | 否 | 当前遍历到的元素(和value相同). | + | treeSet | TreeSet<T> | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("sdfs"); + treeSet.add("dfsghsf"); + treeSet.forEach((value, key) => { + console.log(value, key) + }); + ``` + + +### entries + +entries(): IterableIterator<[T, T]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[T, T]> | 返回一个迭代器 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let iter = treeSet.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + + // 使用方法一: + for (let item of treeSet) { + console.log("value: " + item); + } + + // 使用方法二: + let iter = treeSet[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-uri.md b/zh-cn/application-dev/reference/apis/js-apis-uri.md index 3d557c30957aba3b1b92df02452bb8a90a087847..8979b69c8ae98a5ede706c80c876528be29337d6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uri.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uri.md @@ -10,12 +10,6 @@ import uri from '@ohos.uri' ``` - -## 权限 - -无 - - ## URI @@ -64,7 +58,7 @@ toString(): string - 返回值: | 类型 | 说明 | | -------- | -------- | - | string | 用于返回网址的字符串序列化。 | + | string | 返回网址的字符串序列化。 | - 示例: ``` @@ -87,7 +81,7 @@ equals(other: URI): boolean - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 用于测试此URI是否与其他URI对象相等。 | + | boolean | 返回true表示相等,否则返回false。 | - 示例: ``` @@ -96,15 +90,16 @@ equals(other: URI): boolean uriInstance.equals(uriInstance1); ``` - ### checkIsAbsolute -判断此URI是否为绝对URI。 +checkIsAbsolute(): boolean + +判断此URI是否为绝对URI(是否定义了scheme组件)。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 用于说明此URI是否为绝对URI(是否定义了scheme组件)。 | + | boolean | 返回true表示该URI是否为绝对URI。 | - 示例: ``` @@ -122,7 +117,7 @@ normalize(): URI - 返回值: | 类型 | 说明 | | -------- | -------- | - | URI | 用于规范化此URI的路径,并返回一个path被规范化后的URI对象。 | + | URI | 返回一个path被规范化后的URI对象。 | - 示例: ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-url.md b/zh-cn/application-dev/reference/apis/js-apis-url.md index bbe12540d1a55d2357a60ab06ac3fe49d04d84ce..e8b003482705ae144781b70d18953e481f045f7a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-url.md +++ b/zh-cn/application-dev/reference/apis/js-apis-url.md @@ -11,11 +11,6 @@ import Url from '@ohos.url' ``` -## 权限 - -无 - - ## URLSearchParams diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index 71707c4098ba3429ec091d68d343c151453bdf49..0a49bd1313bfb8dc938163bf9f78311415e1f8b2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -15,11 +15,6 @@ import util from '@ohos.util'; ``` -## 权限 - -无 - - ## util.printf printf(format: string, ...args: Object[]): string @@ -296,7 +291,7 @@ RationalNumber的构造函数。 - 示例: ``` - var rationalNumber = new util.RationalNumber(1,2); + var rationalNumber = new util.RationalNumber(1,2); ``` @@ -551,7 +546,7 @@ constructor(capacity?:number) - 示例: ``` - var lrubuffer= new util.LruBuffer(); + var lrubuffer= new util.LruBuffer(); ``` @@ -661,7 +656,7 @@ getMissCount():number ``` var pro = new util.LruBuffer(); pro.put(2,10); - pro.get(2) + pro.get(2); var result = pro.getMissCount(); ``` @@ -896,7 +891,7 @@ afterRemoval(isEvict:boolean,key:K,value:V,newValue:V):void } } } - ChildLruBuffer.getInstance().afterRemoval(false,10,30,null); + ChildLruBuffer.getInstance().afterRemoval(false,10,30,null); ``` @@ -1115,7 +1110,7 @@ intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope var tempMiDF = new Temperature(35); var tempMidS = new Temperature(39); var range = new util.Scope(tempLower, tempUpper); - var result = range.intersect(tempMiDF, tempMidS); + var result = range.intersect(tempMiDF, tempMidS); ``` @@ -1135,7 +1130,7 @@ getUpper():ScopeType var tempLower = new Temperature(30); var tempUpper = new Temperature(40); var range = new util.Scope(tempLower, tempUpper); - var result = range.getUpper(); + var result = range.getUpper(); ``` @@ -1155,7 +1150,7 @@ getLower():ScopeType var tempLower = new Temperature(30); var tempUpper = new Temperature(40); var range = new util.Scope(tempLower, tempUpper); - var result = range.getLower(); + var result = range.getLower(); ``` @@ -1183,7 +1178,7 @@ expand(lowerObj:ScopeType,upperObj:ScopeType):Scope var tempMiDF = new Temperature(35); var tempMidS = new Temperature(39); var range = new util.Scope(tempLower, tempUpper); - var result = range.expand(tempMiDF, tempMidS); + var result = range.expand(tempMiDF, tempMidS); ``` @@ -1211,7 +1206,7 @@ expand(range:Scope):Scope var tempMidS = new Temperature(39); var range = new util.Scope(tempLower, tempUpper); var rangeFir = new util.Scope(tempMiDF, tempMidS); - var result = range.expand(rangeFir); + var result = range.expand(rangeFir); ``` @@ -1237,7 +1232,7 @@ expand(value:ScopeType):Scope var tempUpper = new Temperature(40); var tempMiDF = new Temperature(35); var range = new util.Scope(tempLower, tempUpper); - var result = range.expand(tempMiDF); + var result = range.expand(tempMiDF); ``` @@ -1263,7 +1258,7 @@ contains(value:ScopeType):boolean var tempUpper = new Temperature(40); var tempMiDF = new Temperature(35); var range = new util.Scope(tempLower, tempUpper); - range.contains(tempMiDF); + range.contains(tempMiDF); ``` @@ -1291,7 +1286,7 @@ contains(range:Scope):boolean var tempLess = new Temperature(20); var tempMore = new Temperature(45); var rangeSec = new util.Scope(tempLess, tempMore); - var result = range.contains(rangeSec); + var result = range.contains(rangeSec); ``` @@ -1309,7 +1304,7 @@ clamp(value:ScopeType):ScopeType - 返回值: | 类型 | 说明 | | -------- | -------- | - | [ScopeType](#scopetype8) | 如果传入的value小于下限,则返回lowerObj;如果大于上限值则返回upperObj;如果在当前范围内,则返回value | + | [ScopeType](#scopetype8) | 如果传入的value小于下限,则返回lowerObj;如果大于上限值则返回upperObj;如果在当前范围内,则返回value。 | - 示例: ``` @@ -1317,7 +1312,7 @@ clamp(value:ScopeType):ScopeType var tempUpper = new Temperature(40); var tempMiDF = new Temperature(35); var range = new util.Scope(tempLower, tempUpper); - var result = range.clamp(tempMiDF); + var result = range.clamp(tempMiDF); ``` @@ -1332,7 +1327,7 @@ Base64的构造函数。 - 示例: ``` - var base64 = new util.Base64(); + var base64 = new util.Base64(); ``` @@ -1429,12 +1424,11 @@ encode(src:Uint8Array):Promise<Uint8Array> var that = new util.Base64(); var array = new Uint8Array([115,49,51]); var rarray = new Uint8Array([99,122,69,122]); - await that.encode(array).then(val=>{ + that.encode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { expect(val[i]).assertEqual(rarray[i]) } }) - done(); ``` @@ -1458,10 +1452,9 @@ encodeToString(src:Uint8Array):Promise<string> ``` var that = new util.Base64(); var array = new Uint8Array([115,49,51]); - await that.encodeToString(array).then(val=>{ + that.encodeToString(array).then(val=>{ expect(val).assertEqual('czEz') }) - done(); ``` @@ -1486,12 +1479,11 @@ decode(src:Uint8Array | string):Promise<Uint8Array> var that = new util.Base64(); var array = new Uint8Array([99,122,69,122]); var rarray = new Uint8Array([115,49,51]); - await that.decode(array).then(val=>{ + that.decode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { expect(val[i]).assertEqual(rarray[i]) } }) - done(); ``` @@ -1588,7 +1580,7 @@ isArgumentsObject(value: Object):boolean isArrayBuffer(value: Object):boolean -检查输入的value是否是ArrayBuffer对象类型。 +检查输入的value是否是ArrayBuffer类型。 - 参数: | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-vector.md b/zh-cn/application-dev/reference/apis/js-apis-vector.md new file mode 100644 index 0000000000000000000000000000000000000000..4453db94cb7b85427b75b61025df0e41fa752b72 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-vector.md @@ -0,0 +1,684 @@ +# 线性容器Vector + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import {Vector} from '@ohos.util.Vector' +``` + + +## 权限 + +无 + + +## Vector + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | Vector的元素个数 | + + +### constructor + +constructor(); + +Vector的构造函数。 + +- 示例: + ``` + let vector = new Vector(); + ``` + + +### add + +add(element: T): boolean; + +在Vector中尾部插入元素 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let vector = new Vector(); + vector.add("a"); + vector.add(1); + let b = [1, 2, 3]; + vector.add(b); + let c = {name : "lala", age : "13"}; + vector.add(false); + ``` + +### insert + +insert(element: T, index: number): void; + +在长度范围内任意插入指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 被插入的元素 | + | index | number | 是 | 被插入的位置索引 | + +- 示例: + ``` + let vector = new Vector(); + vector.insert("A", 0); + vector.insert(0, 1); + vector.insert(true, 2); + ``` + +### has + +has(element: T): boolean; + +判断此Vector中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let vector = new Vector(); + vector.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + vector.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + vector.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + +### getIndexOf + +getIndexOf(element: T): number; + +返回指定元素第一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(2); + vector.add(1); + vector.add(2); + vector.add(4); + vector.getIndexOf(2); + ``` +### getLastIndexOf + +getLastIndexOf(element: T): number; + +返回指定元素最后一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素最后一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(2); + vector.add(1); + vector.add(2); + vector.add(4); + vector.getLastIndexOf(2); + ``` +### removeByIndex + +removeByIndex(index: number): T; + +根据元素的下标值查找元素,返回元素后将其删除。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定元素的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(2); + vector.add(4); + vector.removeByIndex(2); + ``` + +### remove + +remove(element: T): boolean; + +删除查找到的第一个指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.remove(2); + ``` +### removeByRange +removeByRange(fromIndex: number, toIndex: number): void; + +从一段范围内删除元素,包括起始值但不包括终止值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.removeByRange(2,4); + vector.removeByRange(4,3); + vector.removeByRange(2,6); + ``` + +### replaceAllElements +replaceAllElements(callbackfn: (value: T, index?: number, vector?: Vector<T>) => T, +thisArg?: Object): void; + +用户操作Vector中的元素,用操作后的元素替换原元素并返回操作后的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | vector | Vector<T> | 否 | 当前调用replaceAllElements方法的实例对象 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.replaceAllElements((value, index) => { + return value = 2 * value; + }); + vector.replaceAllElements((value, index) => { + return value = value - 2; + }); + ``` +### forEach +forEach(callbackfn: (value: T, index?: number, vector?: Vector<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历Vector实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数。 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素。 | + | index | number | 否 | 当前遍历到的下标值。 | + | vector | Vector<T> | 否 | 当前调用forEach方法的实例对象。 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.forEach((value, index) => { + console.log(value, index) + }); + + ``` +### sort +sort(comparator?: (firstValue: T, secondValue: T) => number): void; + +对Vector中的元素进行一个排序操作。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 否 | 回调函数。 | + +- comparator的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | firstValue | T | 是 | 前一项元素 | + | secondValue | T | 是 | 后一项元素 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.sort(a, (b => a - b)); + vector.sort(a, (b => b - a)); + vector.sort(); + ``` +### subVector +subVector(fromIndex: number, toIndex: number): Vector<T>; + +根据下标截取Vector中的一段元素,并返回这一段vector实例,包括起始值但不包括终止值。 +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Vector<T> | 返回Vector对象实例 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.subVector(2,4); + vector.subVector(4,3); + vector.subVector(2,6); + + ``` + +### clear +clear(): void; + +清除Vector中的所有元素,并把length置为0。 + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.clear(); + ``` +### clone +clone(): Vector<T>; + +克隆一个与Vector一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Vector<T> | 返回Vector对象实例 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.clone(); + ``` +### getCapacity +getCapacity(): number; + +获取当前实例的容量大小。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回Vector的容量大小 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.getCapacity(); + ``` +### convertToArray +convertToArray(): Array<T>; + +把当前Vector实例转换成数组,并返回转换后的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回数组类型 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.convertToArray(); + ``` +### isEmpty +isEmpty(): boolean; + +判断该Vector是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.isEmpty(); + ``` +### increaseCapacityTo +increaseCapacityTo(newCapacity: number): void; + +如果传入的新容量大于或等于Vector中的元素个数,将容量变更为新容量。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | newCapacity | number | 是 | 新容量 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.increaseCapacityTo(2); + vector.increaseCapacityTo(8); + ``` +### trimToCurrentLength +trimToCurrentLength(): void; + +把容量限制为当前的length大小。 + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.trimToCurrentLength(2); + ``` +### toString + +toString(): string; +用","将Vector实例中的元素按顺序拼接成字符串。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | string | 返回字符串类型 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.toSting(); + ``` + +### copyToArray + +copyToArray(array: Array<T>): void; +将Vector实例中的元素按照下标复制进array。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | array | Array<T> | 是 | 数组 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + let array = ["a", "b", "c", "d", "e", "f"]; + vector.copyToArray(array); + ``` +### getFirstElement + +getFirstElement(): T; +获取实例中的第一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.getFirstElement(); + ``` +### getLastElement + +getLastElement(): T; +获取Vector实例中的最后一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.getLastElement(); + ``` +### getLastIndexFrom + +getLastIndexFrom(element: T, index: number): number; + +从指定索引向后搜索, 返回该元素的下标索引,如果查找失败,则返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 要查找的元素 | + | index | number | 是 | 从指定索引开始搜索 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回该元素的下标 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.add("a"); + vector.getLastIndexFrom(4,3); + ``` +### getIndexFrom + +getIndexFrom(element: T, index: number): number; + +从指定索引向前搜索, 返回该元素的下标索引,如果查找失败,则返回 -1 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 要查找的元素 | + | index | number | 是 | 从指定索引开始搜索 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回该元素的下标 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.add("a"); + vector.getIndexFrom(4, 3); + ``` +### setLength +setLength(newSize: number): void; +设置Vector实例的元素个数。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | newSize | number | 是 | 设置的新长度 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.setLength(8); + vector.setLength(2); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器。 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + + // 使用方法一: + for (let item of vector) { + console.log(item); + } + + // 使用方法二: + let iter = vector[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md index 9cfa6ff54f467089e50f0d2e26cab8a01e9e27b4..7e4d658d1a434da4af2e0b54d058bc7da917300d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md @@ -7,16 +7,19 @@ ## 导入模块 ``` -import vibrate from '@ohos.vibrator'; +import vibrator from '@ohos.vibrator'; ``` +## 系统能力 + +SystemCapability.Sensors.MiscDevice ## 权限列表 ohos.permission.VIBRATE -## vibrate.vibrate +## vibrator.vibrate vibrate(duration: number): Promise<void> @@ -37,17 +40,15 @@ vibrate(duration: number): Promise<void> - 示例: ``` - 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.”); - } - } + vibrator.vibrate(1000).then(()=>{ + console.log("Promise returned to indicate a successful vibration."); + }, (error)=>{ + console.log("error.code"+error.code+"error.message"+error.message); + }); ``` -## vibrate.vibrate +## vibrator.vibrate vibrate(duration: number, callback?: AsyncCallback<void>): void @@ -62,16 +63,16 @@ vibrate(duration: number, callback?: AsyncCallback<void>): void - 示例**:** ``` 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.”); - } + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + console.log("Callback returned to indicate a successful vibration."); + } }) ``` -## vibrate.vibrate +## vibrator.vibrate vibrate(effectId: EffectId): Promise<void> @@ -89,17 +90,15 @@ vibrate(effectId: EffectId): Promise<void> - 示例: ``` - 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.”); - } - } + vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ + console.log("Promise returned to indicate a successful vibration."); + }, (error)=>{ + console.log("error.code"+error.code+"error.message"+error.message); + }); ``` -## vibrate.vibrate +## vibrator.vibrate vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void @@ -113,17 +112,17 @@ vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void - 示例: ``` - 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.”); - } + vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, 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 +## vibrator.stop stop(stopMode: VibratorStopMode): Promise<void> @@ -141,17 +140,15 @@ stop(stopMode: VibratorStopMode): Promise<void> - 示例: ``` - 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 successful.”); - } - }) + vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ + console.log("Promise returned to indicate a successful vibration."); + }, (error)=>{ + console.log("error.code"+error.code+"error.message"+error.message); + }); ``` -## vibrate.stop +## vibrator.stop stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void; @@ -165,12 +162,12 @@ stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void; - 示例: ``` - 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 successful.”); - } + vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ + if(error){ + console.log("error.code"+error.code+"error.message"+error.message); + }else{ + console.log("Callback returned to indicate successful."); + } }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index ff45b896576008a906846753b579d928b04cbaf1..7ceb3a6c4b5c0ed422b81e41d329679df0464c73 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -11,6 +11,11 @@ import window from '@ohos.window'; ``` +## 系统能力 +SystemCapability.WindowManager.WindowManager.Core + + + ## 权限列表 ohos.permission.SYSTEM_FLOAT_WINDOW @@ -189,7 +194,7 @@ getAbilityWindowMode(callback: AsyncCallback<WindowMode>): void ``` window.getAbilityWindowMode((err, data) => { if (err) { - console.error(''Failed to obtain the window mode. Cause:' + JSON.stringify(err)); + console.error('Failed to obtain the window mode. Cause:' + JSON.stringify(err)); return; } console.info('Window mode obtained. Data:' + JSON.stringify(data)) diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 32c60ad58e313e0bae553022f4e6a742903c9341..57eaaf62badf4a17f228717065573bc2d9be67e4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -11,11 +11,6 @@ import worker from '@ohos.worker'; ``` -## 权限 - -无 - - ## 属性 | 名称 | 参数类型 | 可读 | 可写 | 说明 | @@ -51,7 +46,7 @@ worker构造函数。 | options | [WorkerOptions](#workeroptions) | 否 | worker构造的选项。 | - 返回值: - | 参数名 | 说明 | + | 类型 | 说明 | | -------- | -------- | | worker | 执行Worker构造函数生成的Worker对象,失败则返回undefined。 | @@ -294,7 +289,7 @@ dispatchEvent(event: Event): boolean | event | [Event](#event) | 是 | 需要分发的事件。 | - 返回值: - | 参数名 | 说明 | + | 类型 | 说明 | | -------- | -------- | | boolean | 分发的结果,false表示分发失败。 | @@ -347,7 +342,7 @@ worker向宿主线程发送消息。 ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ parentPort.postMessage("receive data from main.js") @@ -369,7 +364,7 @@ close(): void ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { parentPort.close() @@ -397,7 +392,7 @@ DedicatedWorkerGlobalScope的onmessage属性表示worker线程收到来自其宿 ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { console.log("receive main.js message") @@ -424,7 +419,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当 Worker 对象接收 ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessageerror= function(e) { console.log("worker.js onmessageerror") @@ -466,7 +461,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当 Worker 对象接收 | evt | [Event](#event) | 是 | 回调的事件类。 | - 返回值 - | 参数名 | 说明 | + | 类型 | 说明 | | -------- | -------- | | void \| Promise<void> | 无返回值或者以Promise形式返回。 | @@ -533,7 +528,7 @@ WorkerGlobalScope的onerror属性表示worker在执行过程中发生异常被 ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort parentPort.onerror = function(e){ console.log("worker.js onerror") diff --git a/zh-cn/application-dev/reference/apis/js-apis-xml.md b/zh-cn/application-dev/reference/apis/js-apis-xml.md index fe319f9f62406f7282e42d1afa540525efb3555f..3765c3ff2c2b877bb4b7c16a2ff57b1669ff2933 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-xml.md +++ b/zh-cn/application-dev/reference/apis/js-apis-xml.md @@ -11,11 +11,6 @@ import xml from '@ohos.xml'; ``` -## 权限 - -无 - - ## XmlSerializer @@ -28,7 +23,7 @@ XmlSerializer的构造函数。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | buffer | ArrayBuffer \| DataView | 是 | 用于接收写入xml信息的ArrayBuffer \| DataView内存。 | + | buffer | ArrayBuffer \| DataView | 是 | 用于接收写入xml信息的ArrayBuffer或DataView内存。 | | encoding | string | 否 | 编码格式。 | - 示例: @@ -48,8 +43,8 @@ setAttributes(name: string, value: string):void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | string | 是 | 属性的key值 | - | value | string | 是 | 属性的value值 | + | name | string | 是 | 属性的key值。 | + | value | string | 是 | 属性的value值。 | - 示例: ``` @@ -67,7 +62,7 @@ addEmptyElement(name: string): void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | string | 是 | 该空元素的元素名 | + | name | string | 是 | 该空元素的元素名。 | - 示例: ``` @@ -93,12 +88,12 @@ setDeclaration(): void startElement(name: string): void -XmlSerializer的构造函数。 +根据给定名称写入元素开始标记。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | string | 是 | 当前元素的元素名 | + | name | string | 是 | 当前元素的元素名。 | - 示例: ``` @@ -113,7 +108,7 @@ XmlSerializer的构造函数。 endElement(): void -设置结束元素方法。 +写入元素结束标记。 - 示例: ``` @@ -135,8 +130,8 @@ setNamespace(prefix: string, namespace: string): void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | prefix | string | 是 | 当前元素及其子元素的前缀 | - | namespace | string | 是 | 当前元素及其子元素的命名空间 | + | prefix | string | 是 | 当前元素及其子元素的前缀。 | + | namespace | string | 是 | 当前元素及其子元素的命名空间。 | - 示例: ``` @@ -148,43 +143,43 @@ setNamespace(prefix: string, namespace: string): void thatSer.endElement();// = >'\r\n'; ``` -### setCommnet +### setComment -setCommnet(text: string): void +setComment(text: string): void 写入comment属性。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | text | string | 是 | 当前元素的注释内容 | + | text | string | 是 | 当前元素的注释内容。 | - 示例: ``` var arrayBuffer = new ArrayBuffer(1024); var thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); - thatSer.setCommnet("Hi!"); + thatSer.setComment("Hi!"); thatSer.endElement(); // => '\r\n \r\n'; ``` -### setCData +### setCDATA -setCData(text: string): void +setCDATA(text: string): void -写入CData属性。 +写入CDATA属性。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | text | string | 是 | CDate属性的内容 | + | text | string | 是 | CDATA属性的内容。 | - 示例: ``` var arrayBuffer = new ArrayBuffer(1028); var thatSer = new xml.XmlSerializer(arrayBuffer); - thatSer.setCData('root SYSTEM') // => ''; + thatSer.setCDATA('root SYSTEM') // => ''; ``` @@ -197,7 +192,7 @@ setText(text: string): void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | text | string | 是 | text属性的内容 | + | text | string | 是 | text属性的内容。 | - 示例: ``` @@ -219,7 +214,7 @@ setDocType(text: string): void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | text | string | 是 | DocType属性的内容 | + | text | string | 是 | DocType属性的内容。 | - 示例: ``` @@ -241,8 +236,8 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string) - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | buffer | ArrayBuffer \| DataView | 是 | 含有xml文本信息的ArrayBuffer 或者DataView | - | encoding | string | 否 | 编码格式(仅支持utf-8) | + | buffer | ArrayBuffer \| DataView | 是 | 含有xml文本信息的ArrayBuffer或者DataView。 | + | encoding | string | 否 | 编码格式(仅支持utf-8)。 | - 示例: ``` @@ -325,12 +320,12 @@ xml解析选项。 getColumnNumber(): number -获取当前行号,从1开始。 +获取当前列号,从1开始。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 返回当前行号。 | + | number | 返回当前列号。 | ### getDepth @@ -349,12 +344,12 @@ getDepth(): number getLineNumber(): number -获取当前列号,从1开始。 +获取当前行号,从1开始。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 返回当前列号。 | + | number | 返回当前行号。 | ### getName diff --git a/zh-cn/contribute/OpenHarmony-64bits-coding-guide.md b/zh-cn/contribute/OpenHarmony-64bits-coding-guide.md index a9a6b2b27ecd7c5b357b520ad8646817b80eeb44..4b13d58fcaf4829611ed49195b4fcf618772ab7c 100755 --- a/zh-cn/contribute/OpenHarmony-64bits-coding-guide.md +++ b/zh-cn/contribute/OpenHarmony-64bits-coding-guide.md @@ -7,7 +7,7 @@ OpenHarmony的目标是面向全场景、全连接、全智能时代,基于开源的方式,搭建一个智能终端设备操作系统的框架和平台,促进万物互联产业的繁荣发展。具有“硬件互助,资源共享”、“一次开发,多端部署”、“统一OS,弹性部署”的技术特性。 OpenHarmony支持三种系统类型: -1. 轻量系统(mini system),面向从MCU类处理器(例如Arm Cortex-M、RISC-V 32位)的轻量设备,硬件资源极其有限,支持的设备最小内存为128KiB; +1. 轻量系统(mini system),面向MCU类处理器(例如Arm Cortex-M、RISC-V 32位)的轻量设备,硬件资源极其有限,支持的设备最小内存为128KiB; 2. 小型系统(small system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为1MiB 3. 标准系统(standard system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为128MiB @@ -35,7 +35,7 @@ OpenHarmony支持三种系统类型: | size_t | **4** | **8** | **8** | 4 | 8 | | pointer | **4** | **8** | **8** | 4 | 8 | -上表中只包含了部分基本类型,下表分别将ILP32和LP64的siziof和print`进行对比,展示了更全面的常量和类型对应的差异: +上表中只包含了部分基本类型,下表分别将ILP32和LP64的sizeof和print`进行对比,展示了更全面的常量和类型对应的差异: | Type | ILP32 sizeof | ILP32 print | LP64 sizeof | LP64 print | 备注 | | ------------------ | ------------ | ----------- | ----------- | ---------- | ------ | @@ -115,8 +115,8 @@ typedef struct tagFoo { | uint16_t | 2 | 2 | %u | 代替unsigned short | | int32_t | 4 | 4 | %d | 代替int | | uint32_t | 4 | 4 | %u | 代替unsigned int | -| int64_t | 8 | 8 | %PRId64 | 代替long long,宏实现代码兼容 | -| uint64_t | 8 | 8 | %PRIu64 | 代替unsigned longlong,宏实现代码兼容 | +| int64_t | 8 | 8 | %PRId64 | 代替long long、宏实现代码兼容 | +| uint64_t | 8 | 8 | %PRIu64 | 代替unsigned long long、宏实现代码兼容 | | float | 4 | 4 | %f | 单精度浮点数 | | double | 8 | 8 | %lf | 双精度浮点数 | | bool | 1 | 1 | %d | 布尔类型 | @@ -170,7 +170,7 @@ long var; #### 【规则】当需要采用整型变量来存储指针时,变量应该定义成uintptr_t以适应不同的位宽 -【说明】uintptr_t类型用于用于存储指针长度级别的数据,其长度在32位和64位可自动适应。 +【说明】uintptr_t类型用于用于存储指针长度的数据,其长度在32位和64位可自动适应。 【示例】 @@ -262,7 +262,7 @@ format ‘%p’ expects argument of type ‘void *’, but argument 2 has type | 0x80000000LL | 8 | 8 | 增加LL后缀,小于uint32_t范围,长度固定 | | 0x8000000000 | **NA或8** | **8** | 无后缀,超过uint32_t的范围,编译器默认为LL或无效,64位下固定为uint64_t类型 | | 0x8000000000L | **NA或8** | **8** | 后缀为L,对超过uint32_t的范围常数,增加该参数没有意义,应当避免使用 | -| 0x8000000000LL | 8 | 8 | 默认为LL,uint64_t类型 | +| 0x8000000000LL | 8 | 8 | 后缀为LL,uint64_t类型 | 从上表中可看出,使用L或UL后缀的常量,其长度在32位和64位下发生变化,不利于代码的可移植性,因此禁止使用这个后缀。 @@ -533,7 +533,7 @@ q = (int32_t *) (int32_t)&i; int32_t length = (int32_t)strlen(str); // 错误 ``` -strlen返回size_t(它在LP64中是unsigned long),当赋值给一个int32_t时,截断是必然发生的。而通常,截断只会在str的长度大于2GB时才会发生,这种情况在程序中一般不会出现,容易出现问题。 +strlen返回size_t(它在LP64中是unsigned long),当赋值给一个int32_t时,截断是必然发生的。而通常,截断只会在str的长度大于2GB时才会发生,这种情况在程序中一般不会出现,容易忽略。 #### 【规则】在64位环境下使用大数组或大for循环索引时,索引类型应当与下标边界保持一致 diff --git a/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md b/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md index 1c7ae8e8f2bf412c75499e91eb5d1eace88de77e..1521c5dab674669f3497d607275ac24a723aff52 100755 --- a/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md +++ b/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md @@ -16,7 +16,7 @@ HDF(Hardware Driver Foundation)驱动框架,为开发者提供驱动框架 #### 【规则】OpenHarmony的驱动程序,应当使用HDF框架提供的能力实现 -【说明】HDF驱动框架提供了驱动加载、驱动服务管理和驱动消息机制,同时还提供了操作系统抽象层(OSAL, Operating System Abstract Layer)和平台抽象层(PAL, Platform Abstract Layer)来保证驱动程序的跨系统跨平台部署的特性。除此之外,HDF提供了驱动模型的抽象、公共工具、外围器件框架等能力。开发者应该基于HDF提供的这些能力开发驱动,从而保证驱动程序可以在各种形态的OpenHarmony上进行部署。 +【说明】HDF驱动框架提供了驱动加载、驱动服务管理和驱动消息机制,同时还提供了操作系统抽象层(OSAL, Operating System Abstraction Layer)和平台抽象层(PAL, Platform Abstraction Layer)来保证驱动程序的跨系统跨平台部署的特性。除此之外,HDF提供了驱动模型的抽象、公共工具、外围器件框架等能力。开发者应该基于HDF提供的这些能力开发驱动,从而保证驱动程序可以在各种形态的OpenHarmony上进行部署。 #### 【规则】开发者应当遵循此规范要求,开发能够同时满足内核态和用户态的驱动 @@ -332,7 +332,7 @@ root { #### 【建议】当preload字段配置为默认加载时,应当根据业务要求配置按序加载的优先级 -【说明】在HDF框架定义的device_info.hcs配置文件中,priority字段(取值范围为整数0到200)是用来表示Host和驱动的优先级。不同的Host内的驱动,Host的priority值越小,驱动加载优先级越高;同一个Host内驱动的priority值越小,加载优先级越高。priority字段的默认值为100,当未配置或字段值相同时,HDF框架将不保证驱动的加载顺序。开发者应当根据业务场景的要求,配置preority字段,保证各个驱动的启动顺序。 +【说明】在HDF框架定义的device_info.hcs配置文件中,priority字段(取值范围为整数0到200)是用来表示Host和驱动的优先级。不同的Host内的驱动,Host的priority值越小,驱动加载优先级越高;同一个Host内驱动的priority值越小,加载优先级越高。priority字段的默认值为100,当未配置或字段值相同时,HDF框架将不保证驱动的加载顺序。开发者应当根据业务场景的要求,配置priority字段,保证各个驱动的启动顺序。 【样例】 diff --git a/zh-cn/contribute/template/js-template.md b/zh-cn/contribute/template/js-template.md index 4612480a72e4715594e7a9f41ea30f2b82af336c..24f948162f0da63d13a80fac1b770fe54b68bdf3 100644 --- a/zh-cn/contribute/template/js-template.md +++ b/zh-cn/contribute/template/js-template.md @@ -66,6 +66,12 @@ ```js import call from '@ohos.telephony.call'; ``` +## 系统能力 +> *写作说明* +> +> 3.1 - 必选。 +> +示例:SystemCapability.BundleManager.BundleFramework ## 属性 diff --git a/zh-cn/device-dev/get-code/gettools-acquire.md b/zh-cn/device-dev/get-code/gettools-acquire.md index 9fe2e55209f388f28f3bddae6e5d6a75c2f95fa0..dc8a50e2512fb9d81540f85e30f573545bf987d2 100644 --- a/zh-cn/device-dev/get-code/gettools-acquire.md +++ b/zh-cn/device-dev/get-code/gettools-acquire.md @@ -43,7 +43,7 @@ OpenHarmony为开发者提供了两种Docker环境,以帮助开发者快速完

swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker

-

0.0.5

+

0.0.6

标准系统

@@ -73,6 +73,7 @@ OpenHarmony为开发者提供了两种Docker环境,以帮助开发者快速完 + ## 环境准备 在使用docker环境前需要先完成以下操作: @@ -90,12 +91,10 @@ OpenHarmony的Docker镜像托管在[HuaweiCloud SWR](https://console.huaweicloud ### 搭建Docker环境-轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB) -**方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:** - 1. 获取Docker镜像。 ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 2. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 @@ -103,43 +102,13 @@ OpenHarmony的Docker镜像托管在[HuaweiCloud SWR](https://console.huaweicloud ubuntu下执行: ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 - ``` - - windows下执行(假设源码目录为D:\\OpenHarmony): - - ``` - docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 - ``` - - -**方式二:通过Dockerfile 构建本地Docker镜像进行构建** - -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像。 - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令。 - - ``` - cd docs/docker - ./build.sh - ``` - -3. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 - - ubuntu下执行: - - ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` windows下执行(假设源码目录为D:\\OpenHarmony): ``` - docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` @@ -192,28 +161,6 @@ hb set ``` -**方式二:通过Dockerfile 构建本地Docker镜像进行构建** - -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像。 - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令。 - - ``` - cd docs/docker/standard - ./build.sh - ``` - -3. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 - - ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 - ``` - - ### 编译源码-标准系统类设备(参考内存≥128MB) 通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。 diff --git a/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md b/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md index b3bbbe227c2a6799451c612f1b8e9081febc75bc..f2725ccc22379214adc7003b25463a1850aacc5d 100644 --- a/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md +++ b/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md @@ -71,15 +71,14 @@ kernel_version = "3.0.0" --- 内核版本,跟config.json中kern 3. 验证`hb set`配置是否正确,输入`hb set`能够显示如下图片表示配置正确。 - 详细地,执行`hb set`输入项目根目录,并且回车,遍历所有`//vendor//`目录下的`config.json`,给出可选产品编译选项,`config.json`的`product_name`用于显示产品名,`device_company`和`board`用于关联出`//device/board//`目录,并且匹配`/config.gni`文件,如果能够匹配多个文件,表示该单板适配了多个内核,那么可以根据`config.json`的`kernel_type`和`kernel_version`来唯一匹配`config.gni`的`kernel_type`和`kernel_version`,这样就可以确定了需要编译适配了哪个内核的单板。 - + 执行`hb set`输入项目根目录,并且回车,`hb`命令会遍历所有`//vendor//`目录下的`config.json`,给出可选产品编译选项,`config.json`的`product_name`用于显示产品名,`device_company`和`board`用于关联出`//device/board//`目录,并且匹配`/config.gni`文件,如果能够匹配多个文件,表示该单板适配了多个内核,那么可以根据`config.json`的`kernel_type`和`kernel_version`来唯一匹配`config.gni`的`kernel_type`和`kernel_version`,即可确定了需要编译适配了哪个内核的单板。 ![hb set](figure/bes2600_hb_set.png) ​ 通过`hb env`可以查看选择出来的预编译环境变量。 ![hb env](figure/bes2600_hb_env.png) -在执行`hb build`之前,需要准备好`LiteOS-M`内核适配,具体适配步骤请参考[内核移植](内核移植)。 +在执行`hb build`之前,需要准备好`LiteOS-M`内核适配,具体适配步骤请参[内核移植](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/porting/porting-bes2600w-on-minisystem-display-demo.md#%E5%86%85%E6%A0%B8%E7%A7%BB%E6%A4%8D)。 ## 内核移植 @@ -143,18 +142,18 @@ orsource "../../device/soc/*/Kconfig.liteos_m.soc" ``` . -├── v200zr --- v200zr单板配置目录 -│   ├── Kconfig.liteos_m.board --- 提供v200zr单板的配置选项 -│   ├── Kconfig.liteos_m.defconfig.board --- 提供v200zr单板的默认配置项 +├── v200zr --- v200zr单板配置目录 +│   ├── Kconfig.liteos_m.board --- 提供v200zr单板的配置选项 +│   ├── Kconfig.liteos_m.defconfig.board --- 提供v200zr单板的默认配置项 │   └── liteos_m │   └── config.gni -├── Kconfig.liteos_m.boards --- 提供fnlink单板厂商下Boards配置信息 -├── Kconfig.liteos_m.defconfig.boards --- 提供fnlink单板厂商下Boards默认配置信息 -├── Kconfig.liteos_m.shields --- 提供fnlink单板厂商下扩展板配置信息 -└── shields --- fnlink单板厂商的扩展板目录 - ├── v200zr-t0 --- fnlink单板厂商的扩展板v200zr-t0 - │   ├── Kconfig.liteos_m.defconfig.shield --- 扩展板v200zr-t0默认配置 - │   └── Kconfig.liteos_m.shield --- 扩展板v200zr-t0配置信息 +├── Kconfig.liteos_m.boards --- 提供fnlink单板厂商下Boards配置信息 +├── Kconfig.liteos_m.defconfig.boards --- 提供fnlink单板厂商下Boards默认配置信息 +├── Kconfig.liteos_m.shields --- 提供fnlink单板厂商下扩展板配置信息 +└── shields --- fnlink单板厂商的扩展板目录 + ├── v200zr-t0 --- fnlink单板厂商的扩展板v200zr-t0 + │   ├── Kconfig.liteos_m.defconfig.shield --- 扩展板v200zr-t0默认配置 + │   └── Kconfig.liteos_m.shield --- 扩展板v200zr-t0配置信息 ├── v200zr-t1 │   ├── Kconfig.liteos_m.defconfig.shield │   └── Kconfig.liteos_m.shield @@ -166,7 +165,7 @@ orsource "../../device/soc/*/Kconfig.liteos_m.soc" ``` config BOARD_v200zr bool "select board v200zr" - depends on SOC_BES2600W --- v200zr单板用的bes2600w的SoC,只有 bes2600w的SoC被选择后,v200zr单板配置选项才可见,可以被选择。 + depends on SOC_BES2600W --- v200zr单板用的bes2600w的SoC,只有 bes2600w的SoC被选择后,v200zr单板配置选项才可见,可以被选择。 ``` 在 `v200zr/Kconfig.liteos_m.defconfig.board`需要配置选择该单板后,默认定义 `BOARD` 的名字为 `"v200zr"` ,如下: @@ -174,7 +173,7 @@ config BOARD_v200zr ``` if BOARD_v200zr config BOARD - string --- string后没有带提示,因此用户不可见 + string --- string后没有带提示,因此用户不可见 default "v200zr" endif # BOARD_v200zr @@ -184,24 +183,24 @@ endif # BOARD_v200zr ``` . -├── bes2600 --- bes2600 SoC系列 -│   ├── Kconfig.liteos_m.defconfig.bes2600w --- bestechnic芯片厂商bes2600w SoC Series配置 -│   ├── Kconfig.liteos_m.defconfig.series --- bestechnic芯片厂商bes2600默认配置 -│   ├── Kconfig.liteos_m.series --- bestechnic芯片厂商bes2600 SoC Series配置 -│   └── Kconfig.liteos_m.soc --- bestechnic芯片厂商bes2600 SoC配置 -├── Kconfig.liteos_m.defconfig --- bestechnic芯片厂商SoC默认配置 -├── Kconfig.liteos_m.series --- bestechnic芯片厂商SoC Series配置 -└── Kconfig.liteos_m.soc --- bestechnic芯片厂商 SoC配置 +├── bes2600 --- bes2600 SoC系列 +│   ├── Kconfig.liteos_m.defconfig.bes2600w --- bestechnic芯片厂商bes2600w SoC Series配置 +│   ├── Kconfig.liteos_m.defconfig.series --- bestechnic芯片厂商bes2600默认配置 +│   ├── Kconfig.liteos_m.series --- bestechnic芯片厂商bes2600 SoC Series配置 +│   └── Kconfig.liteos_m.soc --- bestechnic芯片厂商bes2600 SoC配置 +├── Kconfig.liteos_m.defconfig --- bestechnic芯片厂商SoC默认配置 +├── Kconfig.liteos_m.series --- bestechnic芯片厂商SoC Series配置 +└── Kconfig.liteos_m.soc --- bestechnic芯片厂商 SoC配置 ``` 在 `bes2600/Kconfig.liteos_m.series` 需要配置`bes2600 SoC series`,以及它的芯片架构等信息,如下: ``` -config SOC_SERIES_BES2600 --- 提供bes2600 SoC Series选项 +config SOC_SERIES_BES2600 --- 提供bes2600 SoC Series选项 bool "Bestechnic 2600 Series" - select ARM --- 选择bes2600后,默认选择ARM架构 - select SOC_COMPANY_BESTECHNIC --- 选择bes2600后,默认选择bestechnic芯片公司,驱动会依赖这个宏配置,选择配置编译对应厂商的驱动 - select CPU_CORTEX_M33 --- 选择bes2600后,默认选择cortex-m33 CPU + select ARM --- 选择bes2600后,默认选择ARM架构 + select SOC_COMPANY_BESTECHNIC --- 选择bes2600后,默认选择bestechnic芯片公司,驱动会依赖这个宏配置,选择配置编译对应厂商的驱动 + select CPU_CORTEX_M33 --- 选择bes2600后,默认选择cortex-m33 CPU help Enable support for Bestechnic 2600 series ``` @@ -211,9 +210,9 @@ config SOC_SERIES_BES2600 --- 提供bes2600 SoC Series选项 ``` choice prompt "Bestechnic 2600 series SoC" - depends on SOC_SERIES_BES2600 --- 只有选择了bes2600 Series后,才会出现如下配置选项 + depends on SOC_SERIES_BES2600 --- 只有选择了bes2600 Series后,才会出现如下配置选项 -config SOC_BES2600W --- 增加bes2600w SoC配置选择项 +config SOC_BES2600W --- 增加bes2600w SoC配置选择项 bool "SoC BES2600w" endchoice @@ -222,11 +221,11 @@ endchoice 在 `bes2600/Kconfig.liteos_m.defconfig.series` 需要提供`bes2600 SoC series`选择后的默认配置,如下: ``` -if SOC_SERIES_BES2600 --- 选择了bes2600 Series后,才会增加如下默认配置选项 +if SOC_SERIES_BES2600 --- 选择了bes2600 Series后,才会增加如下默认配置选项 -rsource "Kconfig.liteos_m.defconfig.bes2600w" --- 增加bes2600w SoC的默认配置 +rsource "Kconfig.liteos_m.defconfig.bes2600w" --- 增加bes2600w SoC的默认配置 -config SOC_SERIES --- 增加SOC_SERIES的默认配置 +config SOC_SERIES --- 增加SOC_SERIES的默认配置 string default "bes2600" @@ -242,7 +241,7 @@ endif ifeq ($(RELEASE:1=y),y) CONFIG ?= $(PRODUCT_PATH)/kernel_configs/release$(tee).config else -CONFIG ?= $(PRODUCT_PATH)/kernel_configs/debug$(tee).config --- 配置文件保存在$(CONFIG)中,由产品最终定义 +CONFIG ?= $(PRODUCT_PATH)/kernel_configs/debug$(tee).config --- 配置文件保存在$(CONFIG)中,由产品最终定义 endif …… @@ -281,11 +280,11 @@ deps += [ "//device/soc/$LOSCFG_SOC_COMPANY" ] 在`//device/board/fnlink/BUILD.gn`中,新增内容如下: ``` -if (ohos_kernel_type == "liteos_m") { --- 由于多内核设计,对于LiteOS-M内核适配,需要用宏来隔离 - import("//kernel/liteos_m/liteos.gni") --- 引入内核gn编写模板 - module_name = get_path_info(rebase_path("."), "name") --- 动态获取当前文件目录作为模块名,防止目录名修改后,这里还需要跟着修改 - module_group(module_name) { --- 采用module_group模板 - modules = [ --- 添加需要编译的模块 +if (ohos_kernel_type == "liteos_m") { --- 由于多内核设计,对于LiteOS-M内核适配,需要用宏来隔离 + import("//kernel/liteos_m/liteos.gni") --- 引入内核gn编写模板 + module_name = get_path_info(rebase_path("."), "name") --- 动态获取当前文件目录作为模块名,防止目录名修改后,这里还需要跟着修改 + module_group(module_name) { --- 采用module_group模板 + modules = [ --- 添加需要编译的模块 ] } } @@ -312,9 +311,9 @@ if (ohos_kernel_type == "liteos_m") { ... if(!ret) { ... - OhosSystemAdapterHooks(); --- 系统启动时候设置钩子,启动OpenHarmonyOHOS_SystemInit的之前完成打印和驱动的初始化 + OhosSystemAdapterHooks(); --- 系统启动时候设置钩子,启动OpenHarmonyOHOS_SystemInit的之前完成打印和驱动的初始化 ... - OHOS_SystemInit(); --- 启动OpenHarmony服务,以及组件初始化 + OHOS_SystemInit(); --- 启动OpenHarmony服务,以及组件初始化 } .... ``` @@ -324,8 +323,8 @@ if (ohos_kernel_type == "liteos_m") { ``` int OhosSystemAdapterHooks(void) { - init_trace_system(); --- 初始化打印函数 - DeviceManagerStart(); --- 调用DeviceManagerStart函数进行HDF驱动初始化,这个过程会调用单板代码中的驱动配置文件hdf.hcs以及drivers源码实现 + init_trace_system(); --- 初始化打印函数 + DeviceManagerStart(); --- 调用DeviceManagerStart函数进行HDF驱动初始化,这个过程会调用单板代码中的驱动配置文件hdf.hcs以及drivers源码实现 return 0; } @@ -338,7 +337,7 @@ int OhosSystemAdapterHooks(void) 1. 配置指定目录放置打包文件系统`config.json`,通过`flash_partition_dir`指定目录: ``` - "flash_partition_dir": "fs" --- 表示在vendor/bestechnic/display_demo/fs目录下放置文件系统预置文件 + "flash_partition_dir": "fs" --- 表示在vendor/bestechnic/display_demo/fs目录下放置文件系统预置文件 ``` 2. 在指定目录`vendor/bestechnic/display_demo/fs`下放置两部分内容: @@ -532,7 +531,7 @@ struct HdfDriverEntry g_GpioDriverEntry = { .Init = GpioDriverInit, .Release = GpioDriverRelease, }; -HDF_INIT(g_GpioDriverEntry); --- 通过HDF_INIT 加载GPIO驱动 +HDF_INIT(g_GpioDriverEntry); --- 通过HDF_INIT 加载GPIO驱动 ``` 然后,在初始化的时候会获取`hcs`参数进行初始化,如下: @@ -548,7 +547,7 @@ static int32_t GpioDriverInit(struct HdfDeviceObject *device) return HDF_ERR_INVALID_PARAM; } - gpioCntlr = GpioCntlrFromDevice(device); --- gpioCntlr节点变量就可以获取具体gpio配置 + gpioCntlr = GpioCntlrFromDevice(device); --- gpioCntlr节点变量就可以获取具体gpio配置 if (gpioCntlr == NULL) { ... ``` @@ -640,7 +639,7 @@ static int32_t PanelDriverInit(struct HdfDeviceObject *object) "component": "wifi_lite", …… "targets": [ - "//foundation/communication/wifi_lite:wifi" --- wifi_lite的编译目标 + "//foundation/communication/wifi_lite:wifi" --- wifi_lite的编译目标 ], …… }, @@ -651,7 +650,7 @@ static int32_t PanelDriverInit(struct HdfDeviceObject *object) ``` config("include") { - include_dirs = [ "interfaces/wifiservice" ] --- 因为wifi_lite只提供头文件,不提供wifi的具体实现,所以wifi模块暴露出适配的目录路径提供给硬件厂商来适配,厂商提供wifi协议栈源码实现。 + include_dirs = [ "interfaces/wifiservice" ] --- 因为wifi_lite只提供头文件,不提供wifi的具体实现,所以wifi模块暴露出适配的目录路径提供给硬件厂商来适配,厂商提供wifi协议栈源码实现。 } group("wifi") { @@ -663,7 +662,7 @@ group("wifi") { ``` …… -WifiErrorCode Scan(void) --- wifi_device.c中扫描wifi热点的函数,对wifi_device.h中Scan函数的适配实现 +WifiErrorCode Scan(void) --- wifi_device.c中扫描wifi热点的函数,对wifi_device.h中Scan函数的适配实现 { WifiErrorCode ret = ERROR_WIFI_BUSY; @@ -682,7 +681,7 @@ WifiErrorCode Scan(void) --- wifi_device.c中扫描wifi热点的函数 return ret; } …… -int GetSignalLevel(int rssi, int band) --- wifi_hotspot.c中获取wifi信号热点函数,对wifi_hotspot.h中GetSignalLevel函数的适配实现。 +int GetSignalLevel(int rssi, int band) --- wifi_hotspot.c中获取wifi信号热点函数,对wifi_hotspot.h中GetSignalLevel函数的适配实现。 { if (band == HOTSPOT_BAND_TYPE_2G) { if (rssi >= RSSI_LEVEL_4_2_G) @@ -757,11 +756,11 @@ config("public") { #ifndef _PORTING_LWIPOPTS_H_ #define _PORTING_LWIPOPTS_H_ -#include_next "lwip/lwipopts.h" --- 保持原来的配置项不变 +#include_next "lwip/lwipopts.h" --- 保持原来的配置项不变 #define LWIP_NETIF_STATUS_CALLBACK 1 #define LWIP_CHECKSUM_ON_COPY 0 -#define CHECKSUM_GEN_UDP 0 --- 新增硬件适配选项 +#define CHECKSUM_GEN_UDP 0 --- 新增硬件适配选项 #endif /* _PORTING_LWIPOPTS_H_ */ @@ -802,10 +801,10 @@ ethernetif_init(struct netif *netif) "subsystem": "startup", "components": [ { - "component": "bootstrap_lite" --- bootstrap_lite 部件 + "component": "bootstrap_lite" --- bootstrap_lite 部件 }, { - "component": "syspara_lite", --- syspara_lite 部件 + "component": "syspara_lite", --- syspara_lite 部件 "features": [ "enable_ohos_startup_syspara_lite_use_posix_file_api = true" ] @@ -915,7 +914,7 @@ ethernetif_init(struct netif *netif) }, ``` -​ `bootstrap_lite`部件会编译`//base/startup/bootstrap_lite/services/source/bootstrap_service.c`,该文件中,通过`SYS_SERVICE_INIT`将`Init`函数符号灌段到`__zinitcall_sys_service_start`和`__zinitcall_sys_service_end`中,由于`Init`函数是没有显示调用它,所以需要将它强制链接到最终的镜像。如下: +​ `bootstrap_lite`部件会编译`//base/startup/bootstrap_lite/services/source/bootstrap_service.c`,该文件中,通过`SYS_SERVICE_INIT`将`Init`函数符号灌段到`__zinitcall_sys_service_start`和`__zinitcall_sys_service_end`中,由于`Init`函数是没有显式调用它,所以需要将它强制链接到最终的镜像。如下: ``` static void Init(void) @@ -928,7 +927,7 @@ static void Init(void) bootstrap.flag = FALSE; SAMGR_GetInstance()->RegisterService((Service *)&bootstrap); } -SYS_SERVICE_INIT(Init); --- 通过SYS启动即SYS_INIT启动就需要强制链接生成的lib +SYS_SERVICE_INIT(Init); --- 通过SYS启动即SYS_INIT启动就需要强制链接生成的lib ``` ​ 在`//base/startup/bootstrap_lite/services/source/BUILD.gn`文件中,描述了在`out/v200zr/display_demo/libs` 生成 `libbootstrap.a`,如下: @@ -953,7 +952,7 @@ static_library("bootstrap") { "burn_name": "rtos_main", "enable": "true", "force_link_libs": [ - "bootstrap", --- 强制链接libbootstrap.a + "bootstrap", --- 强制链接libbootstrap.a ... ] }, @@ -981,15 +980,15 @@ static_library("bootstrap") { typedef unsigned char u8; -static char serialNumber[2*ETH_ALEN + 1]; --- 最后一位留作'\0'结束符标识 +static char serialNumber[2*ETH_ALEN + 1]; --- 最后一位留作'\0'结束符标识 static char Hex2Char(u8 hex) { if (hex < HEX_A) { - return hex + CHAR_NUM_OFFSET; --- 将数值0转为char的'0' + return hex + CHAR_NUM_OFFSET; --- 将数值0转为char的'0' } else { - return hex + CHAR_CAPITAL_OFFSET; --- 将数值0xa转为char的'A' + return hex + CHAR_CAPITAL_OFFSET; --- 将数值0xa转为char的'A' } } @@ -998,9 +997,9 @@ const char* HalGetSerial(void) char macAddr[ETH_ALEN]; // as devboard has no production serial number, we just // use wifi mac address as device serial number. - if (serialNumber[0] == STR_END_FLAG) { --- 只有第一次调用时,才去获取mac地址 + if (serialNumber[0] == STR_END_FLAG) { --- 只有第一次调用时,才去获取mac地址 extern int bwifi_get_own_mac(u8 *addr); - bwifi_get_own_mac(macAddr); --- 获取mac地址 + bwifi_get_own_mac(macAddr); --- 获取mac地址 int j = 0; for (int i = 0; i < ETH_ALEN; i++) { u8 lowFour, highFour; @@ -1010,7 +1009,7 @@ const char* HalGetSerial(void) lowFour = macAddr[i] & MAC_LOW_MASK; serialNumber[j] = Hex2Char(lowFour); j++; - } --- 将mac地址值转化为serial number + } --- 将mac地址值转化为serial number } return serialNumber; } @@ -1042,10 +1041,7 @@ boolean HilogProc_Impl(const HiLogContent *hilogContent, uint32 len) char tempOutStr[LOG_FMT_MAX_LEN] = {0}; if (LogContentFmt(tempOutStr, sizeof(tempOutStr), hilogContent) > 0) { printf(tempOutStr); -#ifdef LOG_FLUSH - hHiviewRegisterHilogProc(HilogProc_Impl);al_trace_flush_buffer(); -#endif - } + } return TRUE; } @@ -1149,9 +1145,9 @@ giflib + libjpeg + libpng + qrcodegen + freetype... (图形第三方库) void RunApp() { #ifdef UI_TEST - AnimatorDemoStart(); --- native ui demo + AnimatorDemoStart(); --- native ui demo #elif defined(ABILITY_TEST) - StartJSApp(); --- js demo + StartJSApp(); --- js demo #endif } @@ -1208,8 +1204,8 @@ APP_FEATURE_INIT(AppEntry); { "component": "aafwk_lite", "features": [ - "enable_ohos_appexecfwk_feature_ability = true", --- 支持FA特性,即包含图形能力 - "config_ohos_aafwk_ams_task_size = 4096" --- 配置ams栈的大小 + "enable_ohos_appexecfwk_feature_ability = true", --- 支持FA特性,即包含图形能力 + "config_ohos_aafwk_ams_task_size = 4096" --- 配置ams栈的大小 ] } ] @@ -1242,11 +1238,11 @@ APP_FEATURE_INIT(AppEntry); ### 产品兼容性规范 -产品兼容性规范文档请参考[产品兼容性SIG介绍](https://gitee.com/openharmony-sig/compatibility/tree/master) +产品兼容性规范文档请参考[产品兼容性SIG介绍](https://gitee.com/openharmony-sig/compatibility/tree/master)。 ### XTS用例 -`XTS`测试参考资料见[xts参考资料](https://www.openharmony.cn/xts/),进行`XTS`子系统适配需要添加`xts_acts`/`xts_tools`部件,直接在`config.json`配置即可,配置如下: +`XTS`测试参考资料见[xts参考资料](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/subsystems/subsys-xts-guide.md),进行`XTS`子系统适配需要添加`xts_acts`/`xts_tools`部件,直接在`config.json`配置即可,配置如下: { "subsystem": "xts", diff --git a/zh-cn/device-dev/quick-start/quickstart-lite-docker-environment.md b/zh-cn/device-dev/quick-start/quickstart-lite-docker-environment.md index 85474c3659acd7dfd0af2bd7d92b98e108750eee..274c2bd34af59d48c27921b739e2a590e943fc2d 100644 --- a/zh-cn/device-dev/quick-start/quickstart-lite-docker-environment.md +++ b/zh-cn/device-dev/quick-start/quickstart-lite-docker-environment.md @@ -21,40 +21,14 @@ OpenHarmony的Docker镜像托管在[HuaweiCloud SWR](https://console.huaweicloud.com/swr/?region=cn-south-1#/app/warehouse/warehouseMangeDetail/goldensir/openharmony-docker/openharmony-docker?type=ownImage)上。开发者可以通过该镜像在很大程度上简化编译前的环境配置。下文将介绍具体使用步骤。 -**方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:** - 1. 获取Docker镜像。 ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 2. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` - - -**方式二:通过Dockerfile 构建本地Docker镜像进行构建:** - -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像。 - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令。 - - ``` - cd docs/docker - ./build.sh - ``` - -3. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 - - ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 - ``` - - diff --git a/zh-cn/device-dev/quick-start/quickstart-standard-running-hi3516-build.md b/zh-cn/device-dev/quick-start/quickstart-standard-running-hi3516-build.md index fd9ae39f0364b3d4291b0dc821dbd6ce5cd3073c..25e6a863755583987be76f4fda5f52d7594a7b26 100644 --- a/zh-cn/device-dev/quick-start/quickstart-standard-running-hi3516-build.md +++ b/zh-cn/device-dev/quick-start/quickstart-standard-running-hi3516-build.md @@ -38,8 +38,6 @@ bash build/prebuilts_download.sh ### 获取Docker环境 -**方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:** - 1. 获取Docker镜像。 ``` @@ -53,28 +51,6 @@ bash build/prebuilts_download.sh ``` -**方式二:通过Dockerfile 构建本地Docker镜像进行构建**: - -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像。 - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令。 - - ``` - cd docs/docker/standard - ./build.sh - ``` - -3. 进入源码根目录执行如下命令,从而进入Docker构建环境。 - - ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 - ``` - - ## 使用安装包方式获取编译工具链 ### 安装依赖工具 diff --git a/zh-cn/device-dev/quick-start/quickstart-standard-running-rk3568-build.md b/zh-cn/device-dev/quick-start/quickstart-standard-running-rk3568-build.md index 6ae878c55c2ec6f1a539f64b56852b759833133a..62933e064b28f0d7407f59491597759bdff32839 100644 --- a/zh-cn/device-dev/quick-start/quickstart-standard-running-rk3568-build.md +++ b/zh-cn/device-dev/quick-start/quickstart-standard-running-rk3568-build.md @@ -38,8 +38,6 @@ bash build/prebuilts_download.sh ### 获取Docker环境 -**方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:** - 1. 获取Docker镜像。 ``` @@ -53,28 +51,6 @@ bash build/prebuilts_download.sh ``` -**方式二:通过Dockerfile 构建本地Docker镜像进行构建**: - -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像。 - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令。 - - ``` - cd docs/docker/standard - ./build.sh - ``` - -3. 进入源码根目录执行如下命令,从而进入Docker构建环境。 - - ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 - ``` - - ## 使用安装包方式获取编译工具链 ### 安装依赖工具 diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-read.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-read.md index 9291457f4c9e3d055dfe7df3528e031ffd97c9ef..716bdfc479b1d1a161354fd8b1a5c2c0bf8108be 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-read.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-read.md @@ -1,41 +1,52 @@ # HiSysEvent订阅指导 - [概述](#section315316685112) -- [接口说明](#section0342191810519) -- [开发实例](#section123181432175110) - - [C++接口实例](#section2016116181902) - + - [功能简介](#section123181433335224) + - [约束与限制](#section123181433375224) +- [开发指导](#section315316685113) + - [接口说明](#section0342191810519) + - [开发实例](#section123181432175110) ## 概述 +### 功能简介 + HiSysEvent提供了跨进程订阅机制,开发者可以通过注册订阅接口实时获取关注的事件,例如电池模块侦听功耗相关的事件,用于分析耗电情况。 -## 接口说明 +### 约束与限制 + +**HiSysEvent事件订阅条件约束:** + +- 在订阅HiSysEvent事件之前,需要先完成HiSysEvent打点配置,具体配置方法请参考[《HiSysEvent打点配置指导》](subsys-dfx-hisysevent-write-config.md)。 + +## 开发指导 + +### 接口说明 **表 1** HiSysEvent订阅接口 -

接口名

+ - - - - - @@ -43,110 +54,144 @@ HiSysEvent提供了跨进程订阅机制,开发者可以通过注册订阅接 **表 2** ListenerRule订阅规则对象 - -

接口名称

描述

+

描述

int HiSysEventManager::AddEventListener(std::shared_ptr<HiSysEventSubscribeCallBackBase> listener, std::vector<struct ListenerRule>& rules)

+

int HiSysEventManager::AddEventListener(std::shared_ptr<HiSysEventSubscribeCallBackBase> listener, std::vector<ListenerRule>& rules)

接口功能:注册订阅HiSysEvent系统事件侦听对象,可设置规则订阅某些事件。

+

接口功能:
  注册订阅HiSysEvent系统事件侦听对象,可设置规则订阅某些事件。

输入参数:

  • listener:订阅回调对象。
  • rules:事件订阅规则。

返回值:

  • 0:订阅成功,重复订阅。
  • 1:订阅成功,初次订阅。
  • 其他返回值:订阅失败。

void HiSysEventManager::RemoveListener(std::shared_ptr<HiSysEventSubscribeCallBackBase> listener)

+

void HiSysEventManager::RemoveListener(std::shared_ptr<HiSysEventSubscribeCallBackBase> listener)

接口功能:移除订阅hisysevent系统事件侦听对象。

+

接口功能:
  移除订阅hisysevent系统事件侦听对象。

输入参数:

  • listener:订阅回调对象。
-

返回值:无。

+

返回值:
  无。

属性名称

+ + - - - - - - -

接口名称

描述

+

描述

uint32_t ruleType

+

ListenerRule(const std::string& tag, RuleType ruleType = RuleType::WHOLE_WORD)

规则类型(匹配范围包括domain以及eventName):

-
  • 1:全字符匹配。
  • 2:前缀匹配。
  • 3:正则表达式匹配。
  • 其他值:无效的匹配方式。
+

接口功能:
  订阅规则构造函数,创建事件标签订阅规则对象。

+

输入参数:

+
    +
  • tag:订阅规则的HisysEvent事件标签,字符串类型,最大长度16个字符(含),有效字符包含大小写字母及数字。
  • +
  • ruleType:订阅规则的规则类型,RuleType枚举类型(参考表3)。

std::string domain

+

ListenerRule(const std::string& domain, const std::string& eventName, RuleType ruleType = RuleType::WHOLE_WORD)

  • domain:事件所属领域,如果传入的是空字符串,则默认事件领域字段匹配成功。
+

接口功能:
  订阅规则构造函数,创建事件领域与事件名称订阅规则对象。

+

输入参数:

+
    +
  • domain:订阅规则的HisysEvent事件领域,字符串类型,最大长度16个字符(含),有效字符包含大写字母、数字及下划线。
  • +
  • eventName:订阅规则的HisysEvent事件名称,字符串类型,最大长度32个字符(含),有效字符包含大写字母、数字及下划线。
  • +
  • ruleType:订阅规则的规则类型,RuleType枚举类型(参考表3)。

std::string eventName

+

ListenerRule(const std::string& domain, const std::string& eventName, const std::string& tag, RuleType ruleType = RuleType::WHOLE_WORD)

  • eventName:事件的名称,如果传入的是空字符串,则默认事件名称字段匹配成功。
+

接口功能:
  订阅规则构造函数,创建事件领域、事件名称,事件标签订阅规则对象。

+

输入参数:

+
    +
  • tag:订阅规则的HisysEvent事件标签,字符串类型,最大长度16个字符(含),有效字符包含大小写字母及数字。
  • +
  • domain:订阅规则的HisysEvent事件领域,字符串类型,最大长度16个字符(含),有效字符包含大写字母、数字及下划线。
  • +
  • eventName:订阅规则的HisysEvent事件名称,字符串类型,最大长度32个字符(含),有效字符包含大写字母、数字及下划线。
  • +
  • ruleType:订阅规则的规则类型,RuleType枚举类型(参考表3)。
-**表 3** HiSysEventSubscribeCallBackBase订阅对象 +**表 3** RuleType类型 + +| 枚举值 | 描述 | +| ------------ | ------------- | +| WHOLE_WORD | 全词匹配类型 | +| PREFIX | 前缀匹配类型 | +| REGULAR | 正则匹配类型 | + +**表 4** HiSysEventSubscribeCallBackBase订阅对象 -

接口名称

+ + - - -

接口名称

描述

+

描述

void HiSysEventSubscribeCallBackBase::OnHandle(const std::string& domain, const std::string& eventName, const int eventType, const std::string& eventDetail)

+

void HiSysEventSubscribeCallBackBase::OnHandle(const std::string& domain, const std::string& eventName, const int eventType, const std::string& eventDetail)

接口功能:订阅事件的回调接口。

+

接口功能:
  订阅事件的回调接口。

输入参数:

  • domain:事件所属领域。
  • eventName:事件的名称。
  • eventType:事件类型。
  • eventDetail:包含事件相关信息的字符串,以json的形式体现。
-

返回值:无。

+

返回值:
  无。

-## 开发实例 +### 开发实例 -### C++接口实例 +订阅HiSysEvent事件C++接口实例 -本实例介绍如何订阅domain=HIVIEWDFX的所有系统事件。 +1. 源代码开发 -1. 源代码开发: + 自定义订阅回调实现类头文件DemoListener.h: - - 引入对应的头文件: + ``` + #ifndef DEMO_LISTENER_H + #define DEMO_LISTENER_H - hisysevent\_manager.h。 + #include "hisysevent_subscribe_callback_native.h" - - 实现回调接口: + #include - HiSysEventSubscribeCallBackBase::OnHandle\(const std::string& domain, const std::string& eventName, const int eventType, const std::string& eventDetail\)。 + class DemoListener : public OHOS::HiviewDFX::HiSysEventSubscribeCallBackNative { + public: + explicit DemoListener() : HiSysEventSubscribeCallBackNative() {} + void OnHandle(const std::string& domain, const std::string& eventName, const int eventType, + const std::string& eventDetail); + virtual ~DemoListener() {} + void OnServiceDied(); + }; + + #endif DEMO_LISTENER_H + ``` - - 注册回调对象: + 增加DemoListener.cpp文件,在DemoListener类中根据实际需求自定义订阅回调接口的实现逻辑: - HiSysEventManager::AddEventListener\(std::shared\_ptr listener, std::vector& rules\)。 + ``` + #include "demo_listener.h" + #include - ``` - // 以下是订阅domain=HIVIEWDFX的所有系统事件的应用例子 - #include "hisysevent_manager.h" - #include - namespace OHOS { - namespace HiviewDFX { - // 实现订阅回调对象的接口 - 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 - - // 调用订阅接口注册开发实现的订阅对象 - 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); - ``` + void DemoListener::OnHandle(const std::string& domain, const std::string& eventName, + const int eventType, const std::string& eventDetail) + { + std::cout << eventDetail << std::endl; + } -2. 编译设置: + void DemoListener::OnServiceDied() + { + std::cout << std::string("service disconnect, exit") << std::endl; + exit(0); + } + ``` - 在BUILD.gn编译文件中,需要添加依赖hisysevent\_native部件的libhisyseventmanager库。 + 通过HiSysEventManager类提供的AddEventListener接口注册回调对象,完成对HiSysEvent的订阅: - ``` - external_deps = [ "hisysevent_native:libhisyseventmanager", ] - ``` + ``` + auto demoListener = std::make_shared(); + // 事件标签规则订阅,规则类型为默认的全词匹配类型 + ListenerRule tagRule("dfx"); + // 事件标签规则订阅,规则类型为正则匹配类型 + ListenerRule regRule("dfx.*", RuleType::REGULAR); + // 事件领域及事件名称规则订阅,规则类型为前缀匹配类型 + ListenerRule domainNameRule("HIVIEWDFX", "APP_USAGE", RuleType::PREFIX); + std::vector sysRules; + sysRules.push_back(tagRule); + sysRules.push_back(regRule); + sysRules.push_back(domainNameRule); + HiSysEventManager::AddEventListener(demoListener, sysRules); + ``` + +2. 编译配置 + 在BUILD.gn编译文件中,需要添加依赖hisysevent\_native组件的libhisyseventmanager库: + ``` + external_deps = [ "hisysevent_native:libhisyseventmanager", ] + ``` diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-select.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-select.md index 2641463433d4d786d1b655247b5a9496167d6d30..867e8eef6e4faa81def895e53d75344a08445eaa 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-select.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-select.md @@ -1,16 +1,17 @@ # HiSysEvent查询指导 - [概述](#section279684125212) -- [接口说明](#section03869128521) -- [开发实例](#section14286111855212) - - [C++接口实例](#section162045551743) - +- [开发指导](#section315316761113) + - [接口说明](#section03869128521) + - [开发实例](#section14286111855212) ## 概述 HiSysEvent提供了查询接口,支持开发者设置条件查询HiSysEvent事件,例如功耗部件可以通过该接口获取所需的系统事件进行业务分析。 -## 接口说明 +## 开发指导 + +### 接口说明 **表 1** HiSysEvent查询接口 @@ -115,11 +116,9 @@ HiSysEvent提供了查询接口,支持开发者设置条件查询HiSysEvent事
-## 开发实例 - -### C++接口实例 +### 开发实例 -本实例介绍如何查询所有系统事件。 +C++接口实例。 1. 源代码开发: diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md index 37a5aaea1127b102290eb2afb2c6ce5fa887a0a9..7f27de82e6fc0d33f934193f0bb496ac7736919c 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent-tool.md @@ -1,41 +1,102 @@ # HiSysEvent工具使用指导 - [概述](#section1886702718521) -- [使用指导](#section1210623418527) +- [实时订阅HiSysEvent事件相关命令](#section1210623418527) +- [查询历史HiSysEvent事件相关命令](#section1210623418539) ## 概述 -目前系统预制了HiSysEvent小工具,可以通过命令行参数,设置查询条件,查询满足要求的HiSysEvent系统事件,支撑开发者在开发过程中是否打点成功,以及故障定位时系统所发生的事件等研发场景。 +目前在系统的/system/bin目录下预置了hisysevent工具,开发者可以通过此工具实时订阅HiSysEvent事件及查询历史HiSysEvent事件。 -## 使用指导 +## 实时订阅HiSysEvent事件相关命令 -1. HiSysEvent工具的参数: +- 实时订阅HiSysEvent事件的基础命令: - 工具预置在/system/bin目录下,命令可以在任意目录执行。 + ``` + hisysevent -r + ``` + + 选项说明: + + | 选项名称 | 功能说明 | + | -------- | --------- | + | -r  | 以缺省设置实时订阅HiSysEvent事件,在此种订阅方式下有任何实时HiSysEvent事件产生,都会在控制台上打印此HiSysEvent事件 | + +- 打开调试模式: ``` - hisysevent [-r | -l [-s
-## 开发实例 +### 开发实例 C++接口实例 @@ -281,5 +294,3 @@ C++接口实例 ``` external_deps = [ "hisysevent_native:libhisysevent" ] ``` - - diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent.md b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent.md index e6c333696abf1c8a39af48a4c9cc03158ff0e77d..cefb6adc2836733ea35533a733c4f8fb4bb50e69 100755 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hisysevent.md @@ -1,11 +1,11 @@ # HiSysEvent开发指导 -- **[HiSysEvent打点指导](subsys-dfx-hisysevent-write.md)** +- **[HiSysEvent打点配置指导](subsys-dfx-hisysevent-write-config.md)** -- **[HiSysEvent订阅指导](subsys-dfx-hisysevent-read.md)** +- **[HiSysEvent打点指导](subsys-dfx-hisysevent-write.md)** -- **[HiSysEvent查询指导](subsys-dfx-hisysevent-select.md)** - -- **[HiSysEvent工具使用指导](subsys-dfx-hisysevent-tool.md)** +- **[HiSysEvent订阅指导](subsys-dfx-hisysevent-read.md)** +- **[HiSysEvent查询指导](subsys-dfx-hisysevent-select.md)** +- **[HiSysEvent工具使用指导](subsys-dfx-hisysevent-tool.md)** \ No newline at end of file