提交 5012849a 编写于 作者: B bird_j 提交者: Gitee

Merge branch 'master' of gitee.com:openharmony/docs into local_api_docs

Signed-off-by: Nbird_j <jianghongpeng@huawei.com>
...@@ -14,15 +14,17 @@ This repository stores device and application development documents provided by ...@@ -14,15 +14,17 @@ This repository stores device and application development documents provided by
### Latest Versions ### 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 ### Historical Stable Versions
......
### 0.0.6 (2022/02/10)
1、更新hb。
2、增加安装ruby。
### 0.0.5 (2021/06/21) ### 0.0.5 (2021/06/21)
1、更新llvm版本从10.0.1-53907更新到10.0.1-62608,支撑ipcamera_hispark_taurus_linux编译。 1、更新llvm版本从10.0.1-53907更新到10.0.1-62608,支撑ipcamera_hispark_taurus_linux编译。
......
### 0.0.5 (2021/06/21)
1\. Updated hb.
2\. Added the installation of ruby.
### 0.0.5 (2021/06/21) ### 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. 1\. Updated LLVM from 10.0.1-53907 to 10.0.1-62608. Introduced support for ipcamera\_hispark\_taurus\_linux.
......
...@@ -43,16 +43,17 @@ RUN apt-get update -y \ ...@@ -43,16 +43,17 @@ RUN apt-get update -y \
&& apt-get install gcc-arm-linux-gnueabi -y \ && apt-get install gcc-arm-linux-gnueabi -y \
&& apt-get install build-essential \ && apt-get install build-essential \
&& apt-get install locales \ && apt-get install locales \
&& apt-get install ruby -y \
&& locale-gen "en_US.UTF-8" \ && locale-gen "en_US.UTF-8" \
&& rm -rf /bin/sh /usr/bin/python /usr/bin/python3 \ && rm -rf /bin/sh /usr/bin/python /usr/bin/python3 \
&& ln -s /bin/bash /bin/sh \ && ln -s /bin/bash /bin/sh \
&& ln -s /usr/bin/python3.8 /usr/bin/python3 \ && ln -s /usr/bin/python3.8 /usr/bin/python3 \
&& ln -s /usr/bin/python3.8 /usr/bin/python \ && 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 https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple setuptools \
&& pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple kconfiglib \ && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple kconfiglib \
&& pip3 install --trusted-host mirrors.aliyun.com -i http://mirrors.aliyun.com/pypi/simple pycryptodome \ && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple pycryptodome \
&& pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple ecdsa \ && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/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 ohos-build \
&& mkdir -p /home/tools \ && 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/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 \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/hc-gen/0.65/linux/hc-gen-0.65-linux.tar \
......
...@@ -8,21 +8,19 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通 ...@@ -8,21 +8,19 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通
| Docker镜像仓库 | 标签 | 说明 | | 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系统为例进行使用介绍。 开发者在配置好开发环境后,可以通过以下步骤来使用我们提供的Docker环境。详情请参见[Docker编译环境](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/gettools-acquire.md)
#### 方式一:从**HuaweiCloud SWR**上直接获取Docker镜像进行构建:
1. 获取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构建环境 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. 通过如下命令启动不同平台的编译 3. 通过如下命令启动不同平台的编译
``` ```
...@@ -31,25 +29,3 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通 ...@@ -31,25 +29,3 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通
在显示的页面中通过键盘上下键选择需要编译的平台,通过回车确定选择。 在显示的页面中通过键盘上下键选择需要编译的平台,通过回车确定选择。
hb build -f #执行编译。 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 #执行编译。
```
...@@ -8,21 +8,19 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua ...@@ -8,21 +8,19 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua
| Docker Image Repository | Tag | Description | | 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 ### 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). After configuring the development environments, perform the steps below to access the Docker environment.
#### **Method 1: Obtaining the Docker image from HuaweiCloud SWR**:
1. Obtain the Docker image. 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: 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. 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 ...@@ -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. Press the Up or Down key to select the platform to build on, then press Enter.
hb build -f # Start building. 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.
```
...@@ -13,4 +13,4 @@ ...@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and # See the License for the specific language governing permissions and
# limitations under the License. # limitations under the License.
docker build -t openharmony-docker:0.0.5 . docker build -t openharmony-docker:0.0.6 .
...@@ -6,8 +6,6 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua ...@@ -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) ### 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. 1. Obtain the Docker image.
``` ```
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 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 ...@@ -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 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) ### Building for Standard-System Devices (reference memory ≥ 128 MB)
Run the following script to start building for Standard-System Devices (reference memory ≥ 128 MB) Run the following script to start building for Standard-System Devices (reference memory ≥ 128 MB)
......
...@@ -2,12 +2,10 @@ ...@@ -2,12 +2,10 @@
本文为标准系统类设备Docker使用指导,[点此查看](https://gitee.com/openharmony/docs/blob/master/docker/README.md)小型和轻量系统类设备使用指导。 本文为标准系统类设备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) ### 搭建Docker环境-标准系统类设备(参考内存≥128MB)
##### 方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:
1. 获取Docker镜像。 1. 获取Docker镜像。
``` ```
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 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 ...@@ -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 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)
通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。 通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。
......
# 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&nbsp;requestSuspendDelay(reason:&nbsp;string,&nbsp;callback:&nbsp;Callback&lt;void&gt;):&nbsp;**DelaySuspendInfo**; | Requests delayed suspension after the application switches to the background. <br/>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&nbsp;getRemainingDelayTime(requestId:&nbsp;number,&nbsp;callback:&nbsp;AsyncCallback&lt;number&gt;):&nbsp;void;<br/>function&nbsp;getRemainingDelayTime(requestId:&nbsp;number):&nbsp;Promise&lt;number&gt;; | Obtains the remaining duration before the application is suspended. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)<br/>Two asynchronous methods are provided: callback and promise.|
| function&nbsp;cancelSuspendDelay(requestId:&nbsp;number):&nbsp;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);
```
# 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.)
...@@ -2,127 +2,178 @@ ...@@ -2,127 +2,178 @@
## When to Use ## 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 **Figure 1** Playback status
![](figures/playback-status.png "playback-status")
![en-us_image_20220117](figures/en-us_image_20220117.jpg)
## Available APIs ## How to Develop
**Table 1** APIs for audio playback For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md).
| API| Description| ### Full-Process Scenario
| -------- | -------- |
| media.createAudioPlayer() | Creates an **AudioPlayer** instance.| 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.
| AudioPlayer | Provides audio playback features. For details, see the table below.|
For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_Attributes).
**Table 2** AudioPlayer methods
```js
| Method| Description| function SetCallBack(audioPlayer) {
| -------- | -------- | audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
| release() | Releases audio resources.| console.info('audio set source success');
| play() | Starts audio playback.| // The playback page is ready. You can click the Play button to start the playback.
| pause() | Pauses playback.| });
| stop() | Stops playback.| audioPlayer.on('play', () => { // Set the 'play' event callback.
| reset()<sup>7+</sup> | Resets the audio source to be played.| console.info('audio play success');
| setVolume(vol:&nbsp;number) | Sets playback volume.| // The Play button is changed to the pausable state.
| seek(timeMs:&nbsp;number) | Changes the playback position.| });
| src:string | Defines the URI of an audio file to play.| audioPlayer.on('pause', () => { // Set the 'pause' event callback.
| state:AudioState | Defines the playback state.| console.info('audio pause success');
| currentTime:number | Defines the current playback position.| // The Play button is changed to the playable state.
| 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.| audioPlayer.on('stop', () => { // Set the 'stop' event callback.
| on('play',&nbsp;function&nbsp;callback) | Subscribes to the playback start event.| console.info('audio stop success');
| on('pause',&nbsp;function&nbsp;callback) | Subscribes to the playback pause event.| // The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state.
| on('stop',&nbsp;function&nbsp;callback) | Subscribes to the playback stop event.| });
| on('reset',&nbsp;function&nbsp;callback) | Subscribes to the playback reset event.| audioPlayer.on('reset', () => { // Set the 'reset' event callback.
| on('finish',function&nbsp;callback) | Subscribes to the playback end event.| console.info('audio reset success');
| on('error',&nbsp;function&nbsp;callback) | Subscribes to the playback error event.| // You can reconfigure the src attribute to play another audio file.
| on('dataload',&nbsp;function&nbsp;callback) | Subscribes to the data loading event.| });
| on('volumeChange',&nbsp;function&nbsp;callback) | Subscribes to the volume change event.| audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
| on('timeUpdate',&nbsp;function&nbsp;callback) | Subscribes to the progress change event.| if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail');
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.');
return; 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.'); console.info('audio seek success, and seek time is ' + seekDoneTime);
}); // The playback progress bar is updated to the seek position.
player.on('timeUpdate', (seekTime, action) => { });
console.info('Seek time: ' + seekTime); audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('Current player time: ' + player.currentTime); console.info('audio volumeChange success');
var newTime = player.currentTime; // Display the updated volume.
if(newTime == 30000) { });
console.info('Seek succeeded. New time: ' + newTime); audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
} else { console.info('audio play finish');
console.error('Seek failed: ', + newTime); });
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(); } else {
}); console.log(`audio getTrackDescription fail, error:${error.message}`);
player.on('error', (err) => { }
console.error('Player error: ${err.message}'); });
}); // 8. Stop playback.
``` audioPlayer.stop(); // Trigger the 'stop' event callback.
// 9. Reset the playback resources.
3. Start playback. audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
``` // 10. Release the resource.
var audioSourceMp3 = 'file://test.mp3'; audioPlayer.release(); // Release the AudioPlayer resource.
player.src = audioSourceMp3; audioPlayer = undefined;
player.loop = true; ```
```
### 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.
```
...@@ -6,11 +6,11 @@ ...@@ -6,11 +6,11 @@
After the OpenHarmony SDK is configured, you can get started to develop your app by **importing a sample project**. 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. 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) ![](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) ![](figures/en-us_image_0000001164498191.png)
......
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
- [Internationalization \(i18n\) ](js-apis-i18n.md) - [Internationalization \(i18n\) ](js-apis-i18n.md)
- Media - Media
- [Audio Management](js-apis-audio.md) - [Audio Management](js-apis-audio.md)
- [Media Playback and Recording](js-apis-media.md) - [Media](js-apis-media.md)
- Security - Security
- [User Authentication](js-apis-useriam-userauth.md) - [User Authentication](js-apis-useriam-userauth.md)
- Data Management - Data Management
......
# 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&lt;void&gt;): 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&lt;void&gt; | 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&lt;void&gt;;
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&lt;void&gt; | 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&lt;AbilityResult&gt;): 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&lt;[AbilityResult](js-apis-featureAbility.md#abilityresult)&gt; | 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&lt;AbilityResult&gt;;
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&lt;[AbilityResult](js-apis-featureAbility.md#abilityresult)&gt; | 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&lt;void&gt;): void;
Terminates this ability. This method uses a callback to return the result.
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | 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&lt;void&gt;;
Terminates this ability. This method uses a promise to return the result.
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | 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&lt;void&gt;): 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&lt;void&gt; | 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&lt;void&gt;;
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&lt;void&gt; | Promise used to return the result.|
- Example
```
this.context.terminateSelfWithResult(
{
want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"},
resultCode: 100
}).then((result) => {
console.log("terminateSelfWithResult")
}
)
```
...@@ -337,13 +337,6 @@ Enumerates the audio channels. ...@@ -337,13 +337,6 @@ Enumerates the audio channels.
| :----- | :------------ | :--------------- | | :----- | :------------ | :--------------- |
| CHANNEL_1 | 0x1 << 0 | Channel count 1. | | CHANNEL_1 | 0x1 << 0 | Channel count 1. |
| CHANNEL_2 | 0x1 << 1 | Channel count 2. | | 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. |
## AudioSamplingRate<sup>8+</sup><a name="audiosamplingrate"></a> ## AudioSamplingRate<sup>8+</sup><a name="audiosamplingrate"></a>
Enumerates the audio sampling rates. Enumerates the audio sampling rates.
......
# 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&lt;void&gt;): 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&lt;void&gt; | 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&lt;number&gt;): 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&lt;number&gt; | 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&lt;number&gt;
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&lt;number&gt; | 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. <br/>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.|
# 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.|
# 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 ## Modules to Import
``` ```js
import media from '@ohos.multimedia.media'; import media from '@ohos.multimedia.media';
``` ```
## Required Permissions ## media.createAudioPlayer
None
## media.createAudioPlayer createAudioPlayer(): [AudioPlayer](#audioplayer)
Creates an **AudioPlayer** instance. Creates an **AudioPlayer** instance in synchronous mode.
**Return values** **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.createAudioPlayerAsync<sup>8+</sup>
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** **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.createAudioPlayerAsync<sup>8+</sup>
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 ## media.createAudioRecorder
createAudioRecorder(): AudioRecorder createAudioRecorder(): AudioRecorder
Creates an **AudioRecorder** instance to control audio recording. Creates an **AudioRecorder** instance to control audio recording.
**Return values** **Return values**
| Type | Description | | Type| Description|
| ------------------------------- | ------------------------------------------------------------ | | ------------------------------- | ----------------------------------------- |
| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. | | [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.|
**Example** **Example**
...@@ -44,255 +107,486 @@ Creates an **AudioRecorder** instance to control audio recording. ...@@ -44,255 +107,486 @@ Creates an **AudioRecorder** instance to control audio recording.
var audiorecorder = media.createAudioRecorder(); var audiorecorder = media.createAudioRecorder();
``` ```
## MediaErrorCode<sup>8+</sup>
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.|
## MediaType<sup>8+</sup>
Enumerates the media types.
| Name| Value| Description|
| ------------------- | ---- | ------------------ |
| MEDIA_TYPE_AUD | 0 | Media.|
| MEDIA_TYPE_VID | 1 | Video.|
| MEDIA_TYPE_SUBTITLE | 2 | Subtitle. (under development)|
## CodecMimeType<sup>8+</sup>
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.|
## MediaDescriptionKey<sup>8+</sup>
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.|
## BufferingInfoType<sup>8+</sup>
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 ## 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<a name=audioplayer_Attributes></a>
| Name | Type | Readable | Writable | Description | | 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://**. | | src | string | Yes| Yes| Audio media URI. The mainstream audio formats (MP4, AAC, MP3, and OGG) are supported. <br>**Examples of supported URIs**:<br>1. Local absolute path: file:///data/data/ohos.xxx.xxx/files/test.mp4<br>![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)<br>2. HTTP network playback path (under development)<br>3. HLS network playback path (under development)<br>4. FD playback (under development)<br>**Precautions**: <br>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 playback. | | 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 playback position. | | currentTime | number | Yes| No| Current audio playback position.|
| duration | number | Yes | No | Audio duration. | | duration | number | Yes| No| Audio duration.|
| state | [AudioState](#audiostate) | Yes | No | Playback status. | | state | [AudioState](#audiostate) | Yes| No| Audio playback state.|
### play ### play<a name=audioplayer_play></a>
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** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('play', () => { // Set the 'play' event callback.
audioplayer.on('play', () => { console.log('audio play success');
console.log('Playback starts.');
}); });
audioplayer.play(); audioPlayer.play();
``` ```
### pause ### pause<a name=audioplayer_pause></a>
pause\(\): void pause(): void
Pauses audio playback. Pauses audio playback.
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('pause', () => { // Set the 'pause' event callback.
audioplayer.on('pause', () => { console.log('audio pause success');
console.log('Playback paused.');
}); });
audioplayer.pause(); audioPlayer.pause();
``` ```
### stop<a name=audioplayer_stop></a>
### stop stop(): void
stop\(\): void
Stops audio playback. Stops audio playback.
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('stop', () => { // Set the 'stop' event callback.
audioplayer.on('stop',() => { console.log('audio stop success');
console.log('Playback stopped.');
}); });
audioplayer.stop(); audioPlayer.stop();
``` ```
### reset<sup>7+</sup><a name=audioplayer_reset></a>
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<a name=audioplayer_seek></a>
seek(timeMs: number): void
Seeks to the specified playback position. Seeks to the specified playback position.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| ------ | ------ | --------- | ----------------------------- | | ------ | ------ | ---- | ------------------------------ |
| timeMs | number | Yes | Playback position to seek to. | | timeMs | number | Yes| Position to seek to, in milliseconds.|
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
audioplayer.on('timeupdate', (action) => { if (typeof (seekDoneTime) == 'undefined') {
var newTime = audioplayer.currenTime; console.info('audio seek fail');
if(newTime >= 30000) { return;
console.info('Seek succeeded. New time: ' + newTime); }
} else { console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
console.info('Seek failed.');
}
}); });
audioplayer.seek(30000); audioPlayer.seek(30000); // Seek to 30000 ms.
``` ```
### setVolume ### setVolume<a name=audioplayer_setvolume></a>
setVolume\(vol: number\): void setVolume(vol: number): void
Sets the volume. Sets the volume.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | 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%). | | vol | number | Yes| Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).|
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/media/sounds.mp4'; audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
audioplayer.on('volumeChange', () => { console.log('audio volumeChange success');
console.log('Playback volume changed.');
}); });
audioplayer.setVolume(1); audioPlayer.setVolume(1); // Set the volume to 100%.
``` ```
### reset<sup>7+</sup> ### release<a name=audioplayer_release></a>
reset\(\): void release(): void
Switches the audio resource to be played. Releases this **AudioPlayer** instance.
**Example** **Example**
``` ```js
audioplay.reset(); audioPlayer.release();
audioPlayer = undefined;
``` ```
### release ### getTrackDescription<sup>8+</sup><a name=audioplayer_gettrackdescription1></a>
getTrackDescription(callback: AsyncCallback<Array<[MediaDescription](#mediadescription8)>>): 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<Array<[MediaDescription](#mediadescription8)>> | Yes| Callback used to return the audio track information obtained.|
**Example** **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();
### getTrackDescription<sup>8+</sup><a name=audioplayer_gettrackdescription2></a>
getTrackDescription(): Promise<Array<[MediaDescription](#mediadescription8)>>
Obtains the audio track information. This method uses a promise to return the result.
**Return values**
| Type| Description|
| ------------------------------------------------------ | ------------------------------- |
| Promise<Array<[MediaDescription](#mediadescription8)>> | 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')<sup>8+</sup>
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** **Parameters**
| Name | Type | Mandatory | Description | | 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**.<br>- The **play** event is triggered when audio playback starts. <br/>- The **pause** event is triggered when audio playback is paused.<br/>- The **stop** event is triggered when audio playback stops.<br/>- The **reset** event is triggered when the player is reset.<br/>- The **dataLoad** event is triggered when audio data is loaded.<br/>- The **finish** event is triggered when audio playback is finished.<br/>- The **volumeChange** event is triggered when the playback volume changes. | | type | string | Yes| Type of the event to subscribe to, which is 'bufferingUpdate' in this example.|
| callback | function | Yes | Callback used to listen for the playback event. | | callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | Yes| Callback invoked when the event is triggered. <br>When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.|
**Example** **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', () => { ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange')
console.log('Playback starts.');
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' <br>- The 'play' event is triggered when the [play()](#audioplayer_play) method is called and audio playback starts. <br>- The 'pause' event is triggered when the [pause()](#audioplayer_pause) method is called and audio playback is paused. <br>- The 'stop' event is triggered when the [stop()](#audioplayer_stop) method is called and audio playback stops. <br>- The 'reset' event is triggered when the [reset()](#audioplayer_reset) method is called and audio playback is reset. <br>- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured. <br>- The 'finish' event is triggered when the audio playback is finished. <br>- 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('timeUpdate')
on(type: 'timeUpdate', callback: Callback\<number>): void on(type: 'timeUpdate', callback: Callback\<number>): void
Listens for audio playback timestamp update events. Subscribes to the 'timeUpdate' event.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | ---------------------- | --------- | ------------------------------------------------------------ | | -------- | ----------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the playback event to listen for. Only the **timeUpdate** event is supported.<br>- The **timeUpdate** event is triggered when the audio playback timestamp is updated. It is also triggered when the **seek** method is called. | | type | string | Yes| Type of the event to subscribe to, which is 'timeUpdate' in this method. <br>The 'timeUpdate' event is triggered when the [seek()](#audioplayer_seek) method is called.|
| callback | Callback&lt;number&gt; | Yes | Callback used to listen for the playback event. | | callback | Callback\<number> | Yes| Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful.|
**Example** **Example**
``` ```js
audioplayer.src = 'file://xxx/sounds.mp4'; audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback.
audioplayer.on('timeupdate', (newTime ) => { if (typeof (seekDoneTime) == 'undefined') {
if(newTime >= 30000) { console.info('audio seek fail');
console.info('Seek succeeded. New time: ' + newTime); return;
} else { }
console.info('Seek failed.'); console.log('audio seek success. seekDoneTime: ' + seekDoneTime);
}
}); });
audioplayer.seek(30000); audioPlayer.seek(30000); // Seek to 30000 ms.
``` ```
### on('error') ### on('error')
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
Listens for playback error events. Subscribes to the audio playback error event.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | ------------- | --------- | ------------------------------------------------------------ | | -------- | ------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the playback error event to listen for.<br>- The **error** event is triggered when an error occurs during audio playback. | | type | string | Yes| Type of the event to subscribe to, which is 'error' in this method. <br>The 'error' event is triggered when an error occurs during audio playback.|
| callback | ErrorCallback | Yes | Callback used to listen for the playback event. | | callback | ErrorCallback | Yes| Callback invoked when the event is triggered.|
**Example** **Example**
``` ```js
audioplayer.src = 'file:///data/sounds.mp4'; audioPlayer.on('error', (error) => { // Set the error event callback.
audioplayer.on('error', (err) => { console.info(`audio error called, errName is ${error.name}`); // Print the error name.
console.info('error callback info: ' + err); 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 ## 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.|
| error<sup>8+</sup> | string | Audio playback is in the error state.|
| Name | Description | ## MediaDescription<sup>8+</sup>
| ------- | -------------------------- |
| idle | Audio playback is idle. | ### [key : string] : any
| playing | The audio is being played. |
| paused | Audio playback is paused. | Defines media information in key-value mode.
| stopped | Audio playback is stopped. |
| 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 ## 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
prepare(config: AudioRecorderConfig): void prepare(config: AudioRecorderConfig): void
Prepares for recording.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| ------ | ------------------------------------------- | --------- | ------------------------------------------------------------ | | ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ |
| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels | | config | [AudioRecorderConfig](#audiorecorderconfig) | Yes| Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels.|
**Example** **Example**
``` ```
let audioRecorderConfig = { let audioRecorderConfig = {
audioEncoder : AAC_LC , audioEncoder : AAC_LC ,
audioEncodeBitRate : 22050, audioEncodeBitRate : 22050,
audioSampleRate : 22050, audioSampleRate : 22050,
numberOfChannels : 2, numberOfChannels : 2,
format : AAC_ADTS, format : AAC_ADTS,
uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a',
} }
audiorecorder.prepare(audioRecorderConfig) audiorecorder.prepare(audioRecorderConfig)
``` ```
### start ### start
start(): void start(): void
...@@ -321,6 +615,8 @@ audiorecorder.stop(); ...@@ -321,6 +615,8 @@ audiorecorder.stop();
release(): void release(): void
Releases this **AudioRecorder** instance.
**Example** **Example**
``` ```
...@@ -333,7 +629,7 @@ reset(): void ...@@ -333,7 +629,7 @@ reset(): void
Resets audio recording. 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** **Example**
...@@ -345,14 +641,14 @@ audiorecorder.reset(); ...@@ -345,14 +641,14 @@ audiorecorder.reset();
on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void
Listens for audio recording events. Subscribes to the audio recording events.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | 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**.<br>- The **prepare** event is triggered when the audio recording preparation is complete.<br/>- The **start** event is triggered when audio recording starts.<br/>- The **stop** event is triggered when audio recording stops.<br/>- The **release** event is triggered when resources related to audio recording are released.<br/>- The **reset** event is triggered when audio recording is reset. | | type | string | Yes| Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\|'stop'\|'release'\|'reset' <br/>- The 'prepare' event is triggered when audio recording preparation is complete. <br/>- The 'start' event is triggered when audio recording starts. <br/>- The 'stop' event is triggered when audio recording is stopped. <br/>- The 'release' event is triggered when the resources related to audio recording are released. <br/>- The 'reset' event is triggered when audio recording is reset.|
| callback | function | Yes | Callback used to listen for the audio recording event. | | callback | function | Yes| Callback invoked when the event is triggered.|
**Example** **Example**
...@@ -367,41 +663,44 @@ audiorecorder.on('prepare', () => { ...@@ -367,41 +663,44 @@ audiorecorder.on('prepare', () => {
on(type: 'error', callback: ErrorCallback): void on(type: 'error', callback: ErrorCallback): void
Listens for audio recording error events. Subscribes to the audio recording error event.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | --------- | ------------------------------------------------------------ | | -------- | ------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of the audio recording error event to listen for.<br>- The **error** event is triggered when an error occurs during audio recording. | | type | string | Yes| Type of the event to subscribe to, which is 'error' in this method. <br/>The 'error' event is triggered when an error occurs during audio recording.|
| callback | function | Yes | Callback used to listen for the audio recording event. | | callback | ErrorCallback | Yes| Callback invoked when the event is triggered.|
## AudioRecorderConfig ## AudioRecorderConfig
Describes audio recording configurations. Describes audio recording configurations.
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| ------------------ | --------------------------------------- | --------- | ------------------------------------------------------------ | | ------------------ | --------------------------------------- | ---- | ------------------------------------------------------------ |
| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**. | | 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**. | | audioEncodeBitRate | number | No| Audio encoding bit rate. The default value is **48000**.|
| audioSampleRate | number | No | Audio sampling 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**. | | 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**. | | 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:<br/>1. Absolute path:<br>file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)<br/> 2. Path with the file descriptor (FD): file://1 (FD number) | | uri | string | Yes| Audio output URI. The following URI types are supported:<br/> 1. Absolute file path: file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)<br/>2. FD path: file://1&nbsp;(fd&nbsp;number)|
## AudioEncoder ## 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 ## AudioOutputFormat
Enumerates audio output formats. Enumerates the audio output formats.
| Name | Default Value | Description | | Name| Default Value| Description|
| -------- | ------------- | ------------------------------------------------------------ | | -------- | ------ | ------------------------------------------------------------ |
| MPEG_4 | 2 | MPEG-4. | | MPEG_4 | 2 | MPEG-4.|
| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), a transmission stream format of Advanced Audio Coding (AAC) audio. | | AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.|
\ No newline at end of file
# 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&lt;void&gt;): 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&lt;void&gt; | 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&lt;void&gt;;
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&lt;void&gt; | 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&lt;void&gt;): void;
Terminates this ability. This method uses a callback to return the result.
- Parameters
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;void&gt; | 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&lt;void&gt;;
Terminates this ability. This method uses a promise to return the result.
- Return value
| Type| Description|
| -------- | -------- |
| Promise&lt;void&gt; | 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&lt;void&gt;): 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&lt;void&gt; | 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&lt;void&gt;;
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&lt;void&gt; | 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,&nbsp;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:&nbsp;number) | Called when the connection fails.|
# 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);
}
```
# 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 <stdio.h>
#include <stdint.h>
#include <inttypes.h>
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 <cstdio>
#include <cinttypes>
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<void *>(reinterpret_cast<uintptr_t>(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.
# OpenHarmony Java Secure Coding Guide # Java Secure Coding Guide
This document provides secure coding suggestions for Java-based development. This document provides secure coding suggestions for Java-based development.
...@@ -1786,7 +1786,7 @@ public void xsltTrans(String src, String dst, String xslt) { ...@@ -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 ## Try best to simplify the regular expression (regex) to prevent regular expression denial of service (ReDoS) attacks
......
# 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. This document provides some secure coding suggestions based on the C\&C++ language to guide development.
......
# 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 <core/hdf_device_desc.h>
#include <hdf_device_desc.h> // 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 <utils/hcs_macro.h>
#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 <hdf_log.h>
#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 <osal/osal_mem.h>
#include <util/hdf_log.h>
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 <osal/osal_time.h>
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 <platform/gpio_if.h>
#include <util/hdf_log.h>
#include <osal/osal_irq.h>
#include <osal/osal_time.h>
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;
}
```
...@@ -8,6 +8,8 @@ ...@@ -8,6 +8,8 @@
- [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md) - [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md)
- [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md)
### Code Style ### Code Style
Develop, review, and test code following the OpenHarmony coding standards. Make sure code is written in the same 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 ...@@ -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) - [JavaScript Coding Style Guide](OpenHarmony-JavaScript-coding-style-guide.md)
- [Python Coding Style Guide](https://pep8.org/) - [Python Coding Style Guide](https://pep8.org/)
- [C&C++ Secure Coding Guide](OpenHarmony-c-cpp-secure-coding-guide.md) - [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) - [Java Secure Coding Guide](OpenHarmony-Java-secure-coding-guide.md)
- [Logging Guide](OpenHarmony-Log-guide.md) - [Logging Guide](OpenHarmony-Log-guide.md)
...@@ -28,6 +32,6 @@ For details, see [Contribution Process](contribution-process.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) - [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)
...@@ -30,7 +30,7 @@ OpenHarmony provides the following two types of Docker environments for you to q ...@@ -30,7 +30,7 @@ OpenHarmony provides the following two types of Docker environments for you to q
</td> </td>
<td class="cellrowborder" valign="top" width="35.8935893589359%" headers="mcps1.2.6.1.4 "><p id="p12667431305"><a name="p12667431305"></a><a name="p12667431305"></a>swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker</p> <td class="cellrowborder" valign="top" width="35.8935893589359%" headers="mcps1.2.6.1.4 "><p id="p12667431305"><a name="p12667431305"></a><a name="p12667431305"></a>swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker</p>
</td> </td>
<td class="cellrowborder" valign="top" width="15.69156915691569%" headers="mcps1.2.6.1.5 "><p id="p143320173017"><a name="p143320173017"></a><a name="p143320173017"></a>0.0.5</p> <td class="cellrowborder" valign="top" width="15.69156915691569%" headers="mcps1.2.6.1.5 "><p id="p143320173017"><a name="p143320173017"></a><a name="p143320173017"></a>0.0.6</p>
</td> </td>
</tr> </tr>
<tr id="row998612174129"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p1998617172126"><a name="p1998617172126"></a><a name="p1998617172126"></a>Standard system</p> <tr id="row998612174129"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p1998617172126"><a name="p1998617172126"></a><a name="p1998617172126"></a>Standard system</p>
...@@ -60,6 +60,7 @@ OpenHarmony provides the following two types of Docker environments for you to q ...@@ -60,6 +60,7 @@ OpenHarmony provides the following two types of Docker environments for you to q
## Preparations<a name="section7337134183512"></a> ## Preparations<a name="section7337134183512"></a>
Before using the Docker environment, perform the following operations: 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 ...@@ -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\)<a name="section319412277287"></a> ### Setting Up the Docker Environment for Mini-System Devices \(reference memory ≥ 128 KB\) and Small-System Devices \(reference memory ≥ 1 MB\)<a name="section319412277287"></a>
**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR**
1. Obtain the Docker image. 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: 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 ...@@ -90,43 +89,13 @@ The Docker image of OpenHarmony is hosted on [HUAWEI CLOUD SWR](https://console
Run the following command in Ubuntu: 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
```
**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
``` ```
Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\): 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 ...@@ -164,8 +133,6 @@ hb set
### Setting Up the Docker Environment for Standard-System Devices \(reference memory ≥ 128 MB\)<a name="section13585262391"></a> ### Setting Up the Docker Environment for Standard-System Devices \(reference memory ≥ 128 MB\)<a name="section13585262391"></a>
**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR**
1. Obtain the Docker image. 1. Obtain the Docker image.
``` ```
...@@ -179,28 +146,6 @@ hb set ...@@ -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\)<a name="section193711513406"></a> ### Building for Standard-System Devices \(reference memory ≥ 128 MB\)<a name="section193711513406"></a>
Run the following script to start 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 ...@@ -209,7 +154,7 @@ Run the following script to start building for standard-system devices \(referen
./build.sh --product-name {product_name} --ccache ./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. 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.
......
...@@ -61,8 +61,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. ...@@ -61,8 +61,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2.
## Obtaining the Docker Environment<a name="section181431248132513"></a> ## Obtaining the Docker Environment<a name="section181431248132513"></a>
**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR**
1. Obtain the Docker image. 1. Obtain the Docker image.
``` ```
...@@ -76,28 +74,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. ...@@ -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<a name="section92391739152318"></a> ## Building Source Code<a name="section92391739152318"></a>
1. Run the following script to start building for standard-system devices \(reference memory ≥ 128 MB\). 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. ...@@ -106,7 +82,7 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2.
./build.sh --product-name {product_name} --ccache ./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. 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.
......
...@@ -68,7 +68,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -68,7 +68,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
Table 5 API for deleting data Table 5 API for deleting data
| Class| API| Description| | Class| API| Description|
| ---- | ---- | ---- | | ---- | ---- | ---- |
| RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data. <ul><li> **deletedRows**: specifies the number of rows to delete. </li><li> **predicates**: specifies the table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes: <ul><li> **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**. </li><li> **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only. </li></ul></li></ul> | | RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data. <ul><li> **deletedRows**: specifies the number of rows to delete. </li><li> **predicates**: specifies the table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes: <ul><li> **RdbPredicates**: specifies delete conditions by calling its methods, such as **equalTo**. </li><li> **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only. </li></ul></li></ul> |
- Updating data - Updating data
......
# DeviceProfile<a name="ZH-CN_TOPIC_0000001128264105"></a>
## Introduction<a name="section11660541593"></a>
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<a name="section13587185873516"></a>
**Figure 1** Architecture of the DeviceProfile subsystem<a name="fig4460722185514"></a>
![](figures/dp-architecture.png)
## Directory Structure<a name="section1464106163817"></a>
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<a name="section1718733212019"></a>
- 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<a name="section10729231131110"></a>
### 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<ProfileEventCallback>());
```
### 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<ProfileEventCallback>();
std::list<SubscribeInfo> 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<ProfileEvent> failedEvents;
// Call SubscribeProfileEvents.
DistributedDeviceProfileClient::GetInstance().SubscribeProfileEvents(subscribeInfos,
callback, failedEvents);
sleep(SUBSCRIBE_SLEEP_TIME);
std::list<ProfileEvent> profileEvents;
profileEvents.emplace_back(ProfileEvent::EVENT_PROFILE_CHANGED);
failedEvents.clear();
// Cancel the subscription.
DistributedDeviceProfileClient::GetInstance().UnsubscribeProfileEvents(profileEvents,
callback, failedEvents);
```
## Repositories Involved<a name="section176111311166"></a>
**DeviceProfile subsystem**
[device\_profile\_core](https://gitee.com/openharmony/device_profile_core)
...@@ -8,23 +8,24 @@ This subsystem offers various media services covering audio, videos, and cameras ...@@ -8,23 +8,24 @@ This subsystem offers various media services covering audio, videos, and cameras
- Audio playback and recording - Audio playback and recording
- Video playback and recording - Video playback and recording
- Photographing and recording \(with cameras\) - Photographing and recording \(with cameras\)
## Architecture<a name="section11660541594"></a> ## System Architecture<a name="section11660541594"></a>
**Figure 1** Common architecture of the multimedia subsystem<a name="fig13371156141412"></a>
![](figures/en-us_image_0000001163462711.png)
**Figure 2** Architecture of the multimedia subsystem suitable for the small system<a name="fig866802061417"></a> **Figure 1** Architecture of the multimedia subsystem<a name="fig99659301300"></a>
![](figures/multimedia-architecture.png)
![](figures/multimedia-subsystem-architecture.png) - **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.
**Figure 3** Multimedia service flow for the small system<a name="fig1334042801419"></a> - 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).
![](figures/multimedia-service-flow-for-the-small-system.png "multimedia-service-flow-for-the-small-system") - 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<a name="section161941989596"></a> ## Directory Structure<a name="section161941989596"></a>
...@@ -59,6 +60,13 @@ The structure of the repository directory is as follows: ...@@ -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 │ ├── 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 │ ├── frameworks # Playback and recording framework implementation for the standard system
│ └── interfaces # Playback and recording module APIs 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 └── utils # Subsystem utility module
└── lite # Utility module for the small system └── lite # Utility module for the small system
├── figures # Architecture and process figures of the 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 ...@@ -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\_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\_camera\_standard](https://gitee.com/openharmony/multimedia_camera_standard)
[multimedia\_audio\_standard](https://gitee.com/openharmony/multimedia_audio_standard) [multimedia\_audio\_standard](https://gitee.com/openharmony/multimedia_audio_standard)
[multimedia\_media\_standard](https://gitee.com/openharmony/multimedia_media_standard) [multimedia\_media\_standard](https://gitee.com/openharmony/multimedia_media_standard)
# 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&nbsp;LTS | NA |
| SDK | 3.0.0.0 (API&nbsp;Version&nbsp;7&nbsp;release) | NA |
| (Optional) HUAWEI&nbsp;DevEco&nbsp;Studio| 3.0&nbsp;Beta1 | Recommended for developing OpenHarmony applications|
| (Optional) HUAWEI&nbsp;DevEco&nbsp;Device&nbsp;Tool| 2.2&nbsp;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 **\<Picker>** component does not respond to clicks.|
| [I4CMMH](https://gitee.com/openharmony/ace_ace_engine/issues/I4CMMH) | The display effect of the **\<Toggle>** 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-&gt;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 |
# OpenHarmony Release Notes # OpenHarmony Release Notes
## OpenHarmony 3.x Releases ## OpenHarmony 3.x Releases
- [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md) - [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 v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md)
## OpenHarmony 2.x Releases ## OpenHarmony 2.x Releases
- [OpenHarmony v2.2 beta2 (2021-08-04)](OpenHarmony-v2.2-beta2.md) - [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 1.x Releases
- [OpenHarmony v1.1.3 LTS (2021-09-30)](OpenHarmony-v1-1-3-LTS.md) - [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) - [OpenHarmony v1.1.2 LTS (2021-08-04)](OpenHarmony-v1.1.2-LTS.md)
......
...@@ -34,7 +34,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; ...@@ -34,7 +34,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager';
import backgroundTaskManager from '@ohos.backgroundTaskManager'; import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay'; let myReason = 'test requestSuspendDelay';
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { 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); var id = delayInfo.requestId;console.info("requestId is: " + id);
``` ```
...@@ -61,7 +61,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; ...@@ -61,7 +61,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay'; let myReason = 'test requestSuspendDelay';
// 申请延迟挂起 // 申请延迟挂起
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { 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; var id = delayInfo.requestId;
......
...@@ -20,6 +20,7 @@ ...@@ -20,6 +20,7 @@
- [媒体服务](js-apis-media.md) - [媒体服务](js-apis-media.md)
- 安全 - 安全
- [用户认证](js-apis-useriam-userauth.md) - [用户认证](js-apis-useriam-userauth.md)
- [访问控制](js-apis-security-accessToken.md)
- 数据管理 - 数据管理
- [轻量级存储](js-apis-data-storage.md) - [轻量级存储](js-apis-data-storage.md)
- [分布式数据管理](js-apis-distributed-data.md) - [分布式数据管理](js-apis-distributed-data.md)
...@@ -31,6 +32,7 @@ ...@@ -31,6 +32,7 @@
- [文件管理](js-apis-fileio.md) - [文件管理](js-apis-fileio.md)
- [Statfs](js-apis-statfs.md) - [Statfs](js-apis-statfs.md)
- [目录环境](js-apis-environment.md) - [目录环境](js-apis-environment.md)
- [公共文件访问与管理](js-apis-filemanager.md)
- 账号管理 - 账号管理
- [分布式帐号管理](js-apis-distributed-account.md) - [分布式帐号管理](js-apis-distributed-account.md)
- [应用帐号管理](js-apis-appAccount.md) - [应用帐号管理](js-apis-appAccount.md)
...@@ -75,4 +77,18 @@ ...@@ -75,4 +77,18 @@
- [xml解析与生成](js-apis-xml.md) - [xml解析与生成](js-apis-xml.md)
- [xml转换JavaScript](js-apis-convertxml.md) - [xml转换JavaScript](js-apis-convertxml.md)
- [启动一个worker](js-apis-worker.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)
# 线性容器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&lt;T&gt;) => T,
thisArg?: Object): void;
用户操作ArrayList中的元素,用操作后的元素替换原元素并返回操作后的元素。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素 |
| index | number | 否 | 当前遍历到的下标值 |
| arraylist | ArrayList&lt;T&gt; | 否 | 当前调用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&lt;T&gt;) => void,
thisArg?: Object): void;
通过回调函数来遍历ArrayList实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数。 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素。 |
| index | number | 否 | 当前遍历到的下标值。 |
| arraylist | ArrayList&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
根据下标截取ArrayList中的一段元素,并返回这一段ArrayList实例, 包括起始值但不包括终止值
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| fromIndex | number | 是 | 起始下标 |
| toIndex | number | 是 | 终止下标 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| ArrayList&lt;T&gt; | 返回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&lt;T&gt; ;
克隆一个与ArrayList一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| ArrayList&lt;T&gt; | 返回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&lt;T&gt;;
把当前ArrayList实例转换成数组,并返回转换后的数组。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Array&lt;T&gt; | 返回数组类型 |
- 示例:
```
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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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
...@@ -7,11 +7,6 @@ import audio from '@ohos.multimedia.audio'; ...@@ -7,11 +7,6 @@ import audio from '@ohos.multimedia.audio';
``` ```
## 权限
## getAudioManager ## getAudioManager
getAudioManager(): AudioManager getAudioManager(): AudioManager
...@@ -115,6 +110,7 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l ...@@ -115,6 +110,7 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err)=>{ audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err)=>{
if (err) { if (err) {
console.error('Failed to set the volume. ${err.message}'); console.error('Failed to set the volume. ${err.message}');
...@@ -146,6 +142,7 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise&lt;void&gt; ...@@ -146,6 +142,7 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise&lt;void&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(()=> audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(()=>
console.log('Promise returned to indicate a successful volume setting.'); console.log('Promise returned to indicate a successful volume setting.');
) )
...@@ -167,6 +164,7 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;): v ...@@ -167,6 +164,7 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;): v
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the volume. ${err.message}'); console.error('Failed to obtain the volume. ${err.message}');
...@@ -197,6 +195,7 @@ getVolume(volumeType: AudioVolumeType): Promise&lt;number&gt; ...@@ -197,6 +195,7 @@ getVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) =>
console.log('Promise returned to indicate that the volume is obtained.' + value); console.log('Promise returned to indicate that the volume is obtained.' + value);
) )
...@@ -218,6 +217,7 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;) ...@@ -218,6 +217,7 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;)
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the minimum volume. ${err.message}'); console.error('Failed to obtain the minimum volume. ${err.message}');
...@@ -248,6 +248,7 @@ getMinVolume(volumeType: AudioVolumeType): Promise&lt;number&gt; ...@@ -248,6 +248,7 @@ getMinVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) =>
console.log('Promised returned to indicate that the minimum volume is obtained.' + value); console.log('Promised returned to indicate that the minimum volume is obtained.' + value);
) )
...@@ -269,6 +270,7 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;) ...@@ -269,6 +270,7 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;)
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the maximum volume. ${err.message}'); console.error('Failed to obtain the maximum volume. ${err.message}');
...@@ -299,6 +301,7 @@ getMaxVolume(volumeType: AudioVolumeType): Promise&lt;number&gt; ...@@ -299,6 +301,7 @@ getMaxVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data)=> audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data)=>
console.log('Promised returned to indicate that the maximum volume is obtained.'); console.log('Promised returned to indicate that the maximum volume is obtained.');
) )
...@@ -321,6 +324,7 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback&lt;void ...@@ -321,6 +324,7 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback&lt;void
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => {
if (err) { if (err) {
console.error('Failed to mute the stream. ${err.message}'); console.error('Failed to mute the stream. ${err.message}');
...@@ -353,6 +357,7 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise&lt;void&gt; ...@@ -353,6 +357,7 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise&lt;void&gt;
``` ```
var audioManager = audio.getAudioManager();
audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() =>
console.log('Promise returned to indicate that the stream is muted.'); console.log('Promise returned to indicate that the stream is muted.');
) )
...@@ -375,6 +380,7 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): voi ...@@ -375,6 +380,7 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): voi
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the mute status. ${err.message}'); console.error('Failed to obtain the mute status. ${err.message}');
...@@ -406,6 +412,7 @@ isMute(volumeType: AudioVolumeType): Promise&lt;boolean&gt; ...@@ -406,6 +412,7 @@ isMute(volumeType: AudioVolumeType): Promise&lt;boolean&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) =>
console.log('Promise returned to indicate that the mute status of the stream is obtained.' + 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&lt;boolean&gt;): v ...@@ -427,6 +434,7 @@ isActive(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): v
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the active status of the stream. ${err.message}'); console.error('Failed to obtain the active status of the stream. ${err.message}');
...@@ -457,6 +465,7 @@ isActive(volumeType: AudioVolumeType): Promise&lt;boolean&gt; ...@@ -457,6 +465,7 @@ isActive(volumeType: AudioVolumeType): Promise&lt;boolean&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) =>
console.log('Promise returned to indicate that the active status of the stream is obtained.' + 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&lt;void&gt;): void ...@@ -478,6 +487,7 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => {
if (err) { if (err) {
console.error('Failed to set the ringer mode.​ ${err.message}'); console.error('Failed to set the ringer mode.​ ${err.message}');
...@@ -508,6 +518,7 @@ setRingerMode(mode: AudioRingMode): Promise&lt;void&gt; ...@@ -508,6 +518,7 @@ setRingerMode(mode: AudioRingMode): Promise&lt;void&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() =>
console.log('Promise returned to indicate a successful setting of the ringer mode.'); console.log('Promise returned to indicate a successful setting of the ringer mode.');
) )
...@@ -529,6 +540,7 @@ getRingerMode(callback: AsyncCallback&lt;AudioRingMode&gt;): void ...@@ -529,6 +540,7 @@ getRingerMode(callback: AsyncCallback&lt;AudioRingMode&gt;): void
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getRingerMode((err, value) => { audioManager.getRingerMode((err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the ringer mode.​ ${err.message}'); console.error('Failed to obtain the ringer mode.​ ${err.message}');
...@@ -554,6 +566,7 @@ getRingerMode(): Promise&lt;AudioRingMode&gt; ...@@ -554,6 +566,7 @@ getRingerMode(): Promise&lt;AudioRingMode&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getRingerMode().then((value) => audioManager.getRingerMode().then((value) =>
console.log('Promise returned to indicate that the ringer mode is obtained.' + 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&lt;void&gt ...@@ -576,6 +589,7 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback&lt;void&gt
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => { audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => {
if (err) { if (err) {
console.error('Failed to set the audio parameter. ${err.message}'); console.error('Failed to set the audio parameter. ${err.message}');
...@@ -607,6 +621,7 @@ setAudioParameter(key: string, value: string): Promise&lt;void&gt; ...@@ -607,6 +621,7 @@ setAudioParameter(key: string, value: string): Promise&lt;void&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setAudioParameter('PBits per sample', '8 bit').then(() => audioManager.setAudioParameter('PBits per sample', '8 bit').then(() =>
console.log('Promise returned to indicate a successful setting of the audio parameter.'); console.log('Promise returned to indicate a successful setting of the audio parameter.');
) )
...@@ -628,6 +643,7 @@ getAudioParameter(key: string, callback: AsyncCallback&lt;string&gt;): void ...@@ -628,6 +643,7 @@ getAudioParameter(key: string, callback: AsyncCallback&lt;string&gt;): void
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getAudioParameter('PBits per sample', (err, value) => { audioManager.getAudioParameter('PBits per sample', (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the value of the audio parameter. ${err.message}'); console.error('Failed to obtain the value of the audio parameter. ${err.message}');
...@@ -658,6 +674,7 @@ getAudioParameter(key: string): Promise&lt;string&gt; ...@@ -658,6 +674,7 @@ getAudioParameter(key: string): Promise&lt;string&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getAudioParameter('PBits per sample').then((value) => audioManager.getAudioParameter('PBits per sample').then((value) =>
console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + 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&lt;AudioDeviceDescrip ...@@ -678,6 +695,7 @@ getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback&lt;AudioDeviceDescrip
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{
if (err) { if (err) {
console.error('Failed to obtain the device list. ${err.message}'); console.error('Failed to obtain the device list. ${err.message}');
...@@ -708,6 +726,7 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{ ...@@ -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)=> audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data)=>
console.log('Promise returned to indicate that the device list is obtained.'); console.log('Promise returned to indicate that the device list is obtained.');
) )
...@@ -730,6 +749,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean, callback: AsyncCallback ...@@ -730,6 +749,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean, callback: AsyncCallback
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true, (err)=> { audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true, (err)=> {
if (err) { if (err) {
console.error('Failed to set the active status of the device. ${err.message}'); console.error('Failed to set the active status of the device. ${err.message}');
...@@ -762,6 +782,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean): Promise&lt;void&gt; ...@@ -762,6 +782,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean): Promise&lt;void&gt;
``` ```
var audioManager = audio.getAudioManager();
audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true).then(()=> audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true).then(()=>
console.log('Promise returned to indicate that the device is set to the active status.'); console.log('Promise returned to indicate that the device is set to the active status.');
) )
...@@ -783,6 +804,7 @@ isDeviceActive(deviceType: DeviceType, callback: AsyncCallback&lt;boolean&gt;): ...@@ -783,6 +804,7 @@ isDeviceActive(deviceType: DeviceType, callback: AsyncCallback&lt;boolean&gt;):
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.isDeviceActive(audio.DeviceType.SPEAKER, (err, value) => { audioManager.isDeviceActive(audio.DeviceType.SPEAKER, (err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the active status of the device. ${err.message}'); console.error('Failed to obtain the active status of the device. ${err.message}');
...@@ -814,6 +836,7 @@ isDeviceActive(deviceType: DeviceType): Promise&lt;boolean&gt; ...@@ -814,6 +836,7 @@ isDeviceActive(deviceType: DeviceType): Promise&lt;boolean&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.isDeviceActive(audio.DeviceType.SPEAKER).then((value) => audioManager.isDeviceActive(audio.DeviceType.SPEAKER).then((value) =>
console.log('Promise returned to indicate that the active status of the device is obtained.' + value); 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&lt;void&gt;): void ...@@ -835,6 +858,7 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback&lt;void&gt;): void
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setMicrophoneMute(true, (err) => { audioManager.setMicrophoneMute(true, (err) => {
if (err) { if (err) {
console.error('Failed to mute the microphone. ${err.message}'); console.error('Failed to mute the microphone. ${err.message}');
...@@ -865,6 +889,7 @@ setMicrophoneMute(mute: boolean): Promise&lt;void&gt; ...@@ -865,6 +889,7 @@ setMicrophoneMute(mute: boolean): Promise&lt;void&gt;
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.setMicrophoneMute(true).then(() => audioManager.setMicrophoneMute(true).then(() =>
console.log('Promise returned to indicate that the microphone is muted.'); console.log('Promise returned to indicate that the microphone is muted.');
) )
...@@ -885,6 +910,7 @@ isMicrophoneMute(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -885,6 +910,7 @@ isMicrophoneMute(callback: AsyncCallback&lt;boolean&gt;): void
**示例:** **示例:**
``` ```
var audioManager = audio.getAudioManager();
audioManager.isMicrophoneMute((err, value) => { audioManager.isMicrophoneMute((err, value) => {
if (err) { if (err) {
console.error('Failed to obtain the mute status of the microphone. ${err.message}'); console.error('Failed to obtain the mute status of the microphone. ${err.message}');
...@@ -910,6 +936,7 @@ isMicrophoneMute(): Promise&lt;boolean&gt; ...@@ -910,6 +936,7 @@ isMicrophoneMute(): Promise&lt;boolean&gt;
``` ```
var audioManager = audio.getAudioManager();
audioManager.isMicrophoneMute().then((value) => audioManager.isMicrophoneMute().then((value) =>
console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value); console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value);
) )
......
...@@ -39,7 +39,7 @@ requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): DelaySuspen ...@@ -39,7 +39,7 @@ requestSuspendDelay(reason: string, callback: Callback&lt;void&gt;): DelaySuspen
``` ```
let myReason = 'test requestSuspendDelay'; let myReason = 'test requestSuspendDelay';
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspend delay will time out."); console.info("Request suspension delay will time out.");
}) })
``` ```
......
...@@ -10,6 +10,9 @@ ...@@ -10,6 +10,9 @@
import batteryInfo from '@ohos.batteryInfo'; import batteryInfo from '@ohos.batteryInfo';
``` ```
## 系统能力
SystemCapability.PowerManager.BatteryManager
## 属性 ## 属性
......
...@@ -10,6 +10,9 @@ ...@@ -10,6 +10,9 @@
import brightness from '@ohos.brightness'; import brightness from '@ohos.brightness';
``` ```
## 系统能力
SystemCapability.PowerManager.DisplayPowerManager
## brightness.setValue ## brightness.setValue
......
...@@ -7,14 +7,9 @@ ...@@ -7,14 +7,9 @@
## 导入模块 ## 导入模块
``` ```
import convertxml from '@ohos.convertxml' import convertxml from '@ohos.convertxml';
``` ```
## 权限
## ConvertXML ## ConvertXML
...@@ -48,7 +43,7 @@ convert(xml: string, options?: ConvertOptions) : Object ...@@ -48,7 +43,7 @@ convert(xml: string, options?: ConvertOptions) : Object
' <todo>Work</todo>' + ' <todo>Work</todo>' +
' <todo>Play</todo>' + ' <todo>Play</todo>' +
'</note>'; '</note>';
var conv= new convertxml.ConvertXML(); var conv = new convertxml.ConvertXML();
var result1 = conv.convert(xml, {trim: false, ignoreDeclaration: false}); var result1 = conv.convert(xml, {trim: false, ignoreDeclaration: false});
console.log(result1) console.log(result1)
``` ```
...@@ -63,7 +58,7 @@ convert(xml: string, options?: ConvertOptions) : Object ...@@ -63,7 +58,7 @@ convert(xml: string, options?: ConvertOptions) : Object
| ignoreInstruction | boolean | 否 | 是否忽略xml的写入处理指令,默认false。 | | ignoreInstruction | boolean | 否 | 是否忽略xml的写入处理指令,默认false。 |
| ignoreAttributes | boolean | 否 | 是否跨多行打印属性并缩进属性,默认false。 | | ignoreAttributes | boolean | 否 | 是否跨多行打印属性并缩进属性,默认false。 |
| ignoreComment | boolean | 否 | 是否忽略元素的注释信息,默认false。 | | ignoreComment | boolean | 否 | 是否忽略元素的注释信息,默认false。 |
| ignoreCdata | boolean | 否 | 是否忽略元素的CData信息,默认false。 | | ignoreCDATA | boolean | 否 | 是否忽略元素的CDATA信息,默认false。 |
| ignoreDoctype | boolean | 否 | 是否忽略元素的Doctype信息,默认false。 | | ignoreDoctype | boolean | 否 | 是否忽略元素的Doctype信息,默认false。 |
| ignoreText | boolean | 否 | 是否忽略元素的文本信息,默认false。 | | ignoreText | boolean | 否 | 是否忽略元素的文本信息,默认false。 |
| declarationKey | string | 否 | 用于输出对象中declaration的属性键的名称,默认_declaration。 | | declarationKey | string | 否 | 用于输出对象中declaration的属性键的名称,默认_declaration。 |
......
# 线性容器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&lt;T&gt;) => void,
thisArg?: Object): void;
通过回调函数来遍历Deque实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素 |
| index | number | 否 | 当前遍历到的下标值 |
| deque | Deque&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器。 |
- 示例:
```
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
# 目录环境能力 # 目录环境能力
> ![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'; import environment from '@ohos.environment';
``` ```
## 系统能力
SystemCapability.FileManagement.File.Environment
## 权限列表
## environment.getStorageDataDir ## environment.getStorageDataDir
...@@ -28,7 +27,7 @@ getStorageDataDir():Promise&lt;string&gt; ...@@ -28,7 +27,7 @@ getStorageDataDir():Promise&lt;string&gt;
- 示例: - 示例:
``` ```js
environment.getStorageDataDir().then(function(path){ environment.getStorageDataDir().then(function(path){
// do something // do something
}).catch(function(error){ }).catch(function(error){
...@@ -50,7 +49,7 @@ getStorageDataDir(callback:AsyncCallback&lt;string&gt;):void ...@@ -50,7 +49,7 @@ getStorageDataDir(callback:AsyncCallback&lt;string&gt;):void
- 示例: - 示例:
``` ```js
environment.getStorageDataDir(function(error, path){ environment.getStorageDataDir(function(error, path){
// do something // do something
}); });
...@@ -70,7 +69,7 @@ getUserDataDir():Promise&lt;string&gt; ...@@ -70,7 +69,7 @@ getUserDataDir():Promise&lt;string&gt;
- 示例: - 示例:
``` ```js
environment.getUserDataDir().then(function(path){ environment.getUserDataDir().then(function(path){
// do something // do something
}).catch(function(error){ }).catch(function(error){
...@@ -92,7 +91,7 @@ getUserDataDir(callback:AsyncCallback&lt;string&gt;): void ...@@ -92,7 +91,7 @@ getUserDataDir(callback:AsyncCallback&lt;string&gt;): void
- 示例: - 示例:
``` ```js
environment.getUserDataDir(function(error, path){ environment.getUserDataDir(function(error, path){
// do something // do something
}); });
......
# 公共文件访问与管理 # 公共文件访问与管理
>![](../../public_sys-resources/icon-note.gif) **说明:**
>本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块 ## 导入模块
``` ```js
import filemanager from 'ohos.filemanager' import filemanager from 'ohos.filemanager'
``` ```
## 权限 ## 系统能力
应用需要拥有SystemCapability.FileManagement.FileManagerService权限 SystemCapability.FileManagement.FileManagerService
## filemanager.getRoot ## filemanager.getRoot
getRoot(options? : {dev? : DevInfo}) : Promise&lt;FileInfo[]&gt; getRoot(options? : {dev? : DevInfo}) : Promise&lt;FileInfo[]&gt;
以异步方法获取第一层相册,目录信息。使用promise形式返回结果。 以异步方法获取第一层相册,目录信息。使用promise形式返回结果。
...@@ -18,13 +20,13 @@ getRoot(options? : {dev? : DevInfo}) : Promise&lt;FileInfo[]&gt; ...@@ -18,13 +20,13 @@ getRoot(options? : {dev? : DevInfo}) : Promise&lt;FileInfo[]&gt;
- 参数 - 参数
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| --- | --- | --- | -- | | --- | --- | --- | -- |
| dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' |
- 返回值 - 返回值
| 类型 | 说明 | | 类型 | 说明 |
| --- | -- | | --- | -- |
| Promise&lt;FileInfo[]&gt; | 第一层目录相册信息 | | Promise&lt;[FileInfo](#fileinfo)[]&gt; | 第一层目录相册信息 |
- 示例 - 示例
...@@ -52,8 +54,8 @@ getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback&lt;FileInfo[]&gt;) ...@@ -52,8 +54,8 @@ getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback&lt;FileInfo[]&gt;)
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------------- | ---- | ----------------------------- | | -------- | ------------------------- | ---- | ----------------------------- |
| dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' |
| callback | AsyncCallback&lt;FileInfo[]&gt; | 是 | 异步获取文件的信息之后的回调 | | callback | AsyncCallback&lt;[FileInfo](#fileinfo)[]&gt; | 是 | 异步获取文件的信息之后的回调 |
- 示例 - 示例
...@@ -78,10 +80,10 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num ...@@ -78,10 +80,10 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num
| --- | --- | --- | -- | | --- | --- | --- | -- |
| type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" | | type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" |
| path | string | 是 | 待查询目录uri | | path | string | 是 | 待查询目录uri |
| dev | DevInfo | 是 | 设备名, 当前仅支持设备'local' | | dev | [DevInfo](#devinfo) | 是 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' |
| offset | number | 否 | 待查询文件偏移 | | offset | number | 否 | 待查询文件偏移 |
| count | number | 否 | 待查询文件个数 | | count | number | 否 | 待查询文件个数 |
- 返回值 - 返回值
| 类型 | 说明 | | 类型 | 说明 |
...@@ -123,10 +125,10 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num ...@@ -123,10 +125,10 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num
| -------- | ------------------------- | ---- | ------------------------------------------------------------ | | -------- | ------------------------- | ---- | ------------------------------------------------------------ |
| type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" | | type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" |
| path | string | 是 | 待查询目录uri | | path | string | 是 | 待查询目录uri |
| dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' |
| offset | number | 否 | 待查询文件偏移 | | offset | number | 否 | 待查询文件偏移 |
| count | number | 否 | 待查询文件个数 | | count | number | 否 | 待查询文件个数 |
| callback | AsyncCallback&lt;FileInfo[]&gt; | 是 | 异步获取文件的信息之后的回调 | | callback | AsyncCallback&lt;[FileInfo](#fileinfo)[]&gt; | 是 | 异步获取文件的信息之后的回调 |
- 异常 - 异常
| 错误名称 | 错误类型 | 错误码 | 说明 | | 错误名称 | 错误类型 | 错误码 | 说明 |
...@@ -158,7 +160,7 @@ filemanager.createFile(path : string, filename : string, options? : {dev? : DevI ...@@ -158,7 +160,7 @@ filemanager.createFile(path : string, filename : string, options? : {dev? : DevI
| --- | --- | --- | -- | | --- | --- | --- | -- |
| filename | string | 是 | 待创建的文件名 | | filename | string | 是 | 待创建的文件名 |
| path | string | 是 | 待保存目的相册uri | | 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 ...@@ -199,8 +201,8 @@ createFile(path : string, filename: string, options? : {dev? : DevInfo}, callbac
| -------- | ------------------------- | ---- | ----------------------------- | | -------- | ------------------------- | ---- | ----------------------------- |
| filename | string | 是 | 待创建的文件名 | | filename | string | 是 | 待创建的文件名 |
| path | string | 是 | 待保存目的相册uri | | path | string | 是 | 待保存目的相册uri |
| dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' |
| callback | AsyncCallback&lt;FileInfo[]&gt; | 是 | 异步获取文件的信息之后的回调 | | callback | AsyncCallback&lt;[FileInfo](#fileinfo)[]&gt; | 是 | 异步获取文件的信息之后的回调 |
- 异常 - 异常
...@@ -225,6 +227,8 @@ filemanager.createFile(media_path, name, (err, uri) => { ...@@ -225,6 +227,8 @@ filemanager.createFile(media_path, name, (err, uri) => {
## FileInfo ## FileInfo
文件信息类型,通过getRoot, listFile等接口返回的类型。 文件信息类型,通过getRoot, listFile等接口返回的类型。
### 属性
| 参数名 | 类型 | 可读 | 可写 | 说明 | | 参数名 | 类型 | 可读 | 可写 | 说明 |
| --- | -- | -- | -- | -- | | --- | -- | -- | -- | -- |
| name | string | 是 | 否 | 文件名称 | | name | string | 是 | 否 | 文件名称 |
...@@ -237,6 +241,8 @@ filemanager.createFile(media_path, name, (err, uri) => { ...@@ -237,6 +241,8 @@ filemanager.createFile(media_path, name, (err, uri) => {
## DevInfo ## DevInfo
设备类型,配置接口访问的设备类型。 设备类型,配置接口访问的设备类型。
### 属性
| 参数名 | 类型 | 可读 | 可写 | 说明 | | 参数名 | 类型 | 可读 | 可写 | 说明 |
| --- | -- | -- | -- | -- | | --- | -- | -- | -- | -- |
| name | string | 是 | 是 | 设备名称 | | name | string | 是 | 是 | 设备名称 |
\ No newline at end of file
# 非线性容器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<K, V>): void;
将一个HashMap中的所有元素组添加到另一个hashmap中。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| map | HashMap<K, V> | 是 | 被添加元素的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&lt;K&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;K&gt; | 返回一个迭代器 |
- 示例:
```
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&lt;V&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;V&gt; | 返回一个迭代器 |
- 示例:
```
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<K, V>) => void, thisArg?: Object): void;
通过回调函数来遍历HashMap实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | V | 是 | 当前遍历到的元素键值对的值 |
| key | K | 是 | 当前遍历到的元素键值对的键 |
| hashMap | HashMap<K, V> | 否 | 当前调用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&lt;[K, V]&gt;;
返回一个迭代器,迭代器的每一项都是一个 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
# 非线性容器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&lt;T&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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&lt;T&gt;) => void, thisArg?: Object): void;
通过回调函数来遍历实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素键值对的值 |
| key | T | 否 | 当前遍历到的元素键值对的值(和value相同) |
| hashSet | HashSet&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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
# 非线性容器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<K, V>): boolean;
判断此LightWeightMap中是否含有该指定map中的所有元素。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| map | LightWeightMap<K, V> | 是 | 比较对象 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| 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<K, V>): void;
将一个LightWeightMap中的所有元素组添加到另一个lightweightmap中。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| map | LightWeightMap<K, V> | 是 | 被添加元素的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&lt;K&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;K&gt; | 返回一个迭代器 |
- 示例:
```
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&lt;V&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;V&gt; | 返回一个迭代器 |
- 示例:
```
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<K, V>) => void, thisArg?: Object): void;
通过回调函数来遍历实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | V | 是 | 当前遍历到的元素键值对的值 |
| key | K | 是 | 当前遍历到的元素键值对的键 |
| lightWeightMap | LightWeightMap<K, V> | 否 | 当前调用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&lt;[K, V]&gt;;
返回一个迭代器,迭代器的每一项都是一个 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
# 非线性容器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&lt;T&gt;): boolean;
将另一个容器中的所有元素组添加到当前容器中。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| set | LightWeightSet&lt;T&gt; | 是 | 提供添加元素的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&lt;T&gt;): boolean;
判断此容器中是否含有该指定set中的所有元素。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| set | LightWeightSet&lt;T&gt; | 是 | 比较对象 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| 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&lt;T&gt;;
获取包含此容器中所有对象的数组。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Array&lt;T&gt; | 返回一个数组 |
- 示例:
```
let lightWeightSet = new LightWeightSet();
lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf");
lightWeightSet.add("sdfs");
lightWeightSet.toString();
```
### values
values(): IterableIterator&lt;T&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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&lt;T&gt;) => void, thisArg?: Object): void;
通过回调函数来遍历LightWeightSet实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素 |
| key | T | 否 | 当前遍历到的元素(和value相同) |
| lightWeightSet | LightWeightSet&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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
# 线性容器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&lt;T&gt;, _tail?: NodeObj&lt;T&gt;);
LinkedList的构造函数。
- 参数:
| 参数名 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| _head | NodeObj&lt;T&gt; | 是 | 否 | 入参对象,节点对象,含有element,和next指向,和prev指向 |
| _tail | NodeObj&lt;T&gt; | 是 | 否 | 入参对象,节点对象,含有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&lt;T&gt;;
克隆一个与LinkedList一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| LinkedList&lt;T&gt; | 返回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&lt;T&gt;) => void,
thisArg?: Object): void;
通过回调函数来遍历LinkedList实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素 |
| index | number | 否 | 当前遍历到的下标值 |
| linkedlist | LinkedList&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
把当前LinkedList实例转换成数组,并返回转换后的数组。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Array&lt;T&gt; | 返回数组类型 |
- 示例:
```
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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器。 |
- 示例:
```
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
# 线性容器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&lt;T&gt;);
List的构造函数。
- 参数:
| 参数名 | 类型 | 可读 | 可写 | 说明 |
| -------- | -------- | -------- | -------- | -------- |
| _head | NodeObj&lt;T&gt; | 是 | 否 | 入参对象,节点对象,含有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&lt;T&gt;) => T,
thisArg?: Object): void;
用户操作List中的元素,用操作后的元素替换原元素并返回操作后的元素。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素 |
| index | number | 否 | 当前遍历到的下标值 |
| list | List&lt;T&gt; | 否 | 当前调用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&lt;T&gt;) => void,
thisArg?: Object): void;
通过回调函数来遍历List实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素。 |
| index | number | 否 | 当前遍历到的下标值。 |
| list | List&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
根据下标截取List中的一段元素,并返回这一段List实例,包括起始值但不包括终止值。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| fromIndex | number | 是 | 起始下标 |
| toIndex | number | 是 | 终止下标 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| List&lt;T&gt; | 返回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&lt;T&gt;;
把当前List实例转换成数组,并返回转换后的数组。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Array&lt;T&gt; | 返回数组类型 |
- 示例:
```
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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器。 |
- 示例:
```
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
# 非线性容器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&lt;T&gt;;
克隆一个一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| PlainArray&lt;T&gt; | 返回新的对象实例 |
- 示例:
```
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<number, T>) => void, thisArg?: Object): void;
通过回调函数来遍历实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素键值对的值 |
| key | number | 是 | 当前遍历到的元素键值对的键 |
| plainArray | PlainArray<number, T> | 否 | 当前调用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&lt;[number, T]&gt;;
返回一个迭代器,迭代器的每一项都是一个 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
...@@ -10,14 +10,9 @@ ...@@ -10,14 +10,9 @@
import power from '@ohos.power'; import power from '@ohos.power';
``` ```
## 系统能力
## 权限 SystemCapability.PowerManager.PowerManager
关机权限: ohos.permission.SHUTDOWN
重启权限: ohos.permission.REBOOT
重启并进入recovery模式的权限:ohos.permission.REBOOT_RECOVERY
## power.shutdownDevice ## power.shutdownDevice
...@@ -26,6 +21,8 @@ shutdownDevice(reason: string): void ...@@ -26,6 +21,8 @@ shutdownDevice(reason: string): void
系统关机。 系统关机。
需要权限:ohos.permission.SHUTDOWN
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -44,6 +41,8 @@ rebootDevice(reason: string): void ...@@ -44,6 +41,8 @@ rebootDevice(reason: string): void
重启设备。 重启设备。
需要权限:ohos.permission.REBOOT(重启权限)、ohos.permission.REBOOT_RECOVERY(重启并进入recovery模式的权限)
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
......
...@@ -11,11 +11,6 @@ import process from '@ohos.process'; ...@@ -11,11 +11,6 @@ import process from '@ohos.process';
``` ```
## 权限
## 属性 ## 属性
| 名称 | 类型 | 可读 | 可写 | 说明 | | 名称 | 类型 | 可读 | 可写 | 说明 |
...@@ -143,12 +138,12 @@ kill函数用来发送信号给子进程,结束指定进程。 ...@@ -143,12 +138,12 @@ kill函数用来发送信号给子进程,结束指定进程。
isIsolatedProcess(): boolean isIsolatedProcess(): boolean
检查进程是否被隔离。 判断进程是否被隔离。
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| boolean | 进程是否隔离 | | boolean | 返回判断结果,如果返回true表示进程被隔离。 |
- 示例: - 示例:
``` ```
...@@ -160,17 +155,17 @@ isIsolatedProcess(): boolean ...@@ -160,17 +155,17 @@ isIsolatedProcess(): boolean
isAppUid(v:number): 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 ...@@ -182,12 +177,12 @@ isAppUid(v:number): boolean
is64Bit(): boolean is64Bit(): boolean
判断运行环境是不是64位。 判断运行环境是64位。
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| boolean | 是不是64位环境 | | boolean | 返回判断结果,如果返回true表示为64位环境。 |
- 示例: - 示例:
``` ```
...@@ -204,12 +199,12 @@ getUidForName(v:string): number ...@@ -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 ...@@ -221,17 +216,17 @@ getUidForName(v:string): number
getThreadPriority(v:number): number getThreadPriority(v:number): number
根据指定的 TID 获取线程优先级。 根据指定的tid获取线程优先级。
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| v | number | 是 | 进程的id | | v | number | 是 | 指定的线程tid。 |
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| number | 进程的优先级 | | number | 返回线程的优先级。 |
- 示例: - 示例:
``` ```
...@@ -249,7 +244,7 @@ getStartRealtime() :number ...@@ -249,7 +244,7 @@ getStartRealtime() :number
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| number | 时间 | | number | 返回经过的实时时间。|
- 示例: - 示例:
``` ```
...@@ -261,12 +256,12 @@ getStartRealtime() :number ...@@ -261,12 +256,12 @@ getStartRealtime() :number
getAvailableCores() :number[] getAvailableCores() :number[]
获取多核设备上当前进程可用的 CPU 内核。 获取多核设备上当前进程可用的CPU内核。
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| number[] | 可用内核数 | | number[] | 返回可用内核数。 |
- 示例: - 示例:
``` ```
...@@ -283,7 +278,7 @@ getPastCputime() :number ...@@ -283,7 +278,7 @@ getPastCputime() :number
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| number | 时间 | | number | 返回经过的CPU时间。 |
- 示例: - 示例:
``` ```
...@@ -295,17 +290,17 @@ getPastCputime() :number ...@@ -295,17 +290,17 @@ getPastCputime() :number
getSystemConfig(name:number): number getSystemConfig(name:number): number
用该方法发送signal到指定的进程 获取系统配置信息
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | number | 是 | 系统配置参数名 | | name | number | 是 | 指定系统配置参数名。 |
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| number | 配置信息 | | number | 返回系统配置信息。 |
- 示例: - 示例:
``` ```
...@@ -323,12 +318,12 @@ getEnvironmentVar(name:string): string ...@@ -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 ...@@ -367,7 +362,7 @@ runCmd(command: string, options?: { timeout : number, killSignal :number | str
var result = child.wait(); var result = child.wait();
child.getOutput.then(val=>{ child.getOutput.then(val=>{
console.log("child.getOutput = " + val); console.log("child.getOutput = " + val);
} })
``` ```
......
# 线性容器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&lt;T&gt;) => void,
thisArg?: Object): void;
通过回调函数来遍历Queue实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数。 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素 |
| index | number | 否 | 当前遍历到的下标值 |
| queue | Queue&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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
...@@ -11,6 +11,11 @@ import reminderAgent from'@ohos.reminderAgent'; ...@@ -11,6 +11,11 @@ import reminderAgent from'@ohos.reminderAgent';
``` ```
## 系统能力
SystemCapability.Notification.ReminderAgent
## 权限 ## 权限
ohos.permission.PUBLISH_AGENT_REMINDER ohos.permission.PUBLISH_AGENT_REMINDER
......
...@@ -11,9 +11,9 @@ import runninglock from '@ohos.runningLock'; ...@@ -11,9 +11,9 @@ import runninglock from '@ohos.runningLock';
``` ```
## 权限 ## 系统能力
申请、使用锁的权限:ohos.permission.RUNNING_LOCK SystemCapability.PowerManager.PowerManager
## RunningLockType ## RunningLockType
...@@ -84,6 +84,8 @@ createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback&l ...@@ -84,6 +84,8 @@ createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback&l
创建RunningLock锁。 创建RunningLock锁。
需要权限:ohos.permission.RUNNING_LOCK
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
...@@ -113,6 +115,8 @@ createRunningLock(name: string, type: RunningLockType): Promise&lt;RunningLock&g ...@@ -113,6 +115,8 @@ createRunningLock(name: string, type: RunningLockType): Promise&lt;RunningLock&g
创建Runninglock锁。 创建Runninglock锁。
需要权限:ohos.permission.RUNNING_LOCK
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
......
# 访问控制管理
> ![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&lt;GrantStatus&gt;
校验应用是否授予权限,使用Promise方式异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ------------------- | ---- | ------------------------------------------ |
| tokenID | number | 是 | 要校验的目标应用的身份标识。 |
| permissionName | string | 是 | 需要校验的权限名称。 |
- 返回值:
| 类型 | 说明 |
| :------------ | :---------------------------------- |
| Promise&lt;GrantStatus&gt; | 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&lt;number&gt;
授予应用user grant权限,使用Promise方式异步返回结果。
需要权限:ohos.permission.GRANT_SENSITIVE_PERMISSIONS。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------- | ---- | ------------------------------------------------------------ |
| tokenID | number | 是 | 目标应用的身份标识。 |
| permissionName | string | 是 | 被授予的权限名称。 |
| permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 |
- 返回值:
| 类型 | 说明 |
| :------------ | :---------------------------------- |
| Promise&lt;number&gt; | 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&lt;number&gt;): void
授予应用user grant权限,使用callback回调异步返回结果。
需要权限:ohos.permission.GRANT_SENSITIVE_PERMISSIONS。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------- | ---- | ------------------------------------------------------------ |
| tokenID | number | 是 | 目标应用的身份标识。 |
| permissionName | string | 是 | 被授予的权限名称。 |
| permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 检查授予应用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&lt;number&gt;
撤销应用user grant权限,使用Promise方式异步返回结果。
需要权限:ohos.permission.REVOKE_SENSITIVE_PERMISSIONS。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------- | ---- | ------------------------------------------------------------ |
| tokenID | number | 是 | 目标应用的身份标识。 |
| permissionName | string | 是 | 被撤销的权限名称。 |
| permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 |
- 返回值:
| 类型 | 说明 |
| :------------ | :---------------------------------- |
| Promise&lt;number&gt; | 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&lt;number&gt;): void
撤销应用user grant权限,使用callback回调异步返回结果。
需要权限:ohos.permission.REVOKE_SENSITIVE_PERMISSIONS。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------- | ---- | ------------------------------------------------------------ |
| tokenID | number | 是 | 目标应用的身份标识。 |
| permissionName | string | 是 | 被撤销的权限名称。 |
| permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 |
| callback | AsyncCallback&lt;number&gt; | 是 | 检查撤销应用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&lt;number&gt;
获取指定应用的指定权限的flag,使用Promise方式异步返回结果。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| --------- | ------------------- | ---- | ------------------------------------------------------------ |
| tokenID | number | 是 | 目标应用的身份标识。 |
| permissionName | string | 是 | 查询的权限名称。 |
- 返回值:
| 类型 | 说明 |
| :------------ | :---------------------------------- |
| Promise&lt;number&gt; | 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
...@@ -10,6 +10,9 @@ ...@@ -10,6 +10,9 @@
import sensor from '@ohos.sensor'; import sensor from '@ohos.sensor';
``` ```
## 系统能力
SystemCapability.Sensors.Sensor
## 权限列表 ## 权限列表
...@@ -22,9 +25,9 @@ import sensor from '@ohos.sensor'; ...@@ -22,9 +25,9 @@ import sensor from '@ohos.sensor';
陀螺仪:ohos.permission.GYROSCOPE 陀螺仪: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&lt;AccelerometerResponse&gt;,options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback&lt;AccelerometerResponse&gt;,options?: Options): void
监听加速度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听加速度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -39,23 +42,23 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback&lt;Acc ...@@ -39,23 +42,23 @@ on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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&lt;LinearAccelerometerResponse&gt;, options?: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback&lt;LinearAccelerometerResponse&gt;, options?: Options): void
监听线性加速度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听线性加速度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -68,23 +71,23 @@ on(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback&lt; ...@@ -68,23 +71,23 @@ on(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback&lt;
- 示例: - 示例:
``` ```
sensor.on(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(error,data){ sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,function(error,data){
if (error) { 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; return;
} }
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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&lt;AccelerometerUncalibratedResponse&gt;, options?: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallback&lt;AccelerometerUncalibratedResponse&gt;, options?: Options): void
监听未校准加速度计传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听未校准加速度计传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -97,7 +100,7 @@ on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallb ...@@ -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) { 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; return;
...@@ -108,15 +111,15 @@ on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallb ...@@ -108,15 +111,15 @@ on(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallb
console.info('X-coordinate bias: ' + data.biasX); console.info('X-coordinate bias: ' + data.biasX);
console.info('Y-coordinate bias: ' + data.biasY); console.info('Y-coordinate bias: ' + data.biasY);
console.info('Z-coordinate bias: ' + data.biasZ); 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&lt;GravityResponse&gt;,options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback&lt;GravityResponse&gt;,options?: Options): void
监听重力传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听重力传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -129,23 +132,23 @@ on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback&lt;GravityRe ...@@ -129,23 +132,23 @@ on(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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&lt;GyroscopeResponse&gt;, options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback&lt;GyroscopeResponse&gt;, options?: Options): void
监听陀螺仪传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听陀螺仪传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -158,23 +161,23 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback&lt;Gyrosco ...@@ -158,23 +161,23 @@ on(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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&lt;GyroscopeUncalibratedResponse&gt;, options?: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback&lt;GyroscopeUncalibratedResponse&gt;, options?: Options): void
监听未校准陀螺仪传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听未校准陀螺仪传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -187,26 +190,26 @@ on(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback& ...@@ -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) { 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; return;
} }
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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('Y-coordinate bias: ' + data.biasY);
console.info('Z-coordinate bias: ' + data.biasZ); 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&lt;SignificantMotionResponse&gt;, options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: AsyncCallback&lt;SignificantMotionResponse&gt;, options?: Options): void
监听大幅动作传感器数据变化。如果多次调用该接口,仅最后一次调用生效。 监听大幅动作传感器数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -219,21 +222,21 @@ on(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback: AsyncCallback&l ...@@ -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) { 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; return;
} }
console.info('Scalar data: ' + data.scalar); 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&lt;PedometerDetectResponse&gt;, options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: AsyncCallback&lt;PedometerDetectResponse&gt;, options?: Options): void
监听计步检测传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听计步检测传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -246,21 +249,21 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION, callback: AsyncCallback& ...@@ -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) { 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; return;
} }
console.info('Scalar data: ' + data.scalar); 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&lt;PedometerResponse&gt;, options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback&lt;PedometerResponse&gt;, options?: Options): void
监听计步传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听计步传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -273,21 +276,21 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback&lt;Pedomet ...@@ -273,21 +276,21 @@ on(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('Steps: ' + data.steps); 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&lt;AmbientTemperatureResponse&gt;, options?: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback&lt;AmbientTemperatureResponse&gt;, options?: Options): void
监听环境温度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听环境温度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -300,21 +303,21 @@ on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback&lt; ...@@ -300,21 +303,21 @@ on(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback&lt;
- 示例: - 示例:
``` ```
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) { 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; return;
} }
console.info('Temperature: ' + data.temperature); 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&lt;MagneticFieldResponse&gt;,options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt;MagneticFieldResponse&gt;,options?: Options): void
监听磁场传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听磁场传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -327,7 +330,7 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt;Ma ...@@ -327,7 +330,7 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt;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) { 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; return;
...@@ -335,15 +338,15 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt;Ma ...@@ -335,15 +338,15 @@ on(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt;Ma
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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&lt;MagneticFieldUncalibratedResponse&gt;, options: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCallback&lt;MagneticFieldUncalibratedResponse&gt;, options: Options): void
监听未校准磁场传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听未校准磁场传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -356,26 +359,26 @@ on(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCall ...@@ -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) { 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; return;
} }
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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('Y-coordinate bias: ' + data.biasY);
console.info('Z-coordinate bias: ' + data.biasZ); 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&lt;ProximityResponse&gt;,options?: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback&lt;ProximityResponse&gt;,options?: Options): void
监听接近光传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听接近光传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -388,21 +391,21 @@ on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback&lt;Proximi ...@@ -388,21 +391,21 @@ on(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('Distance: ' + data.distance); 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&lt;HumidityResponse&gt;,options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback&lt;HumidityResponse&gt;,options?: Options): void
监听湿度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听湿度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -415,21 +418,21 @@ on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback&lt;Humidity ...@@ -415,21 +418,21 @@ on(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('Humidity: ' + data.humidity); 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&lt;BarometerResponse&gt;,options?: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback&lt;BarometerResponse&gt;,options?: Options): void
监听气压计传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听气压计传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -442,21 +445,21 @@ on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback&lt;Baromet ...@@ -442,21 +445,21 @@ on(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('Atmospheric pressure: ' + data.pressure); 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&lt;HallResponse&gt;, options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback&lt;HallResponse&gt;, options?: Options): void
监听霍尔传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听霍尔传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -469,21 +472,21 @@ on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback&lt;HallResponse ...@@ -469,21 +472,21 @@ on(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('Status: ' + data.status); 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&lt;LightResponse&gt;, options?: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback&lt;LightResponse&gt;, options?: Options): void
监听环境光传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听环境光传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -496,21 +499,21 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback&lt;Lig ...@@ -496,21 +499,21 @@ on(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info(''Illumination: ' + data.intensity); console.info(' Illumination: ' + data.intensity);
} },
{interval: 10000000} {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&lt;OrientationResponse&gt;, options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;OrientationResponse&gt;, options?: Options): void
监听方向传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听方向传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -523,7 +526,7 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;Orien ...@@ -523,7 +526,7 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;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) { 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; return;
...@@ -531,15 +534,15 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;Orien ...@@ -531,15 +534,15 @@ on(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;Orien
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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&lt;RotationVectorResponse&gt;,options?: Options): void on(type:sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback&lt;RotationVectorResponse&gt;,options?: Options): void
监听旋转矢量传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听旋转矢量传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -552,7 +555,7 @@ on(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback&lt;Rota ...@@ -552,7 +555,7 @@ on(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback&lt;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) { 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; return;
...@@ -560,15 +563,15 @@ on(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback&lt;Rota ...@@ -560,15 +563,15 @@ on(type:SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback:AsyncCallback&lt;Rota
console.info('X-coordinate component: ' + data.x); console.info('X-coordinate component: ' + data.x);
console.info('Y-coordinate component: ' + data.y); console.info('Y-coordinate component: ' + data.y);
console.info('Z-coordinate component: ' + data.z); 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&lt;WearDetectionResponse&gt;,options?: Options): void on(type: sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback&lt;WearDetectionResponse&gt;,options?: Options): void
监听佩戴检测传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 监听佩戴检测传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。
...@@ -581,21 +584,21 @@ on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback&lt;We ...@@ -581,21 +584,21 @@ on(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback&lt;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) { 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; return;
} }
console.info('Wear status: ' + data.value); 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&lt;AccelerometerResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback&lt;AccelerometerResponse&gt;): void
监听加速度传感器的数据变化一次。 监听加速度传感器的数据变化一次。
...@@ -607,7 +610,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback&lt;A ...@@ -607,7 +610,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback&lt;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) { 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; return;
...@@ -620,9 +623,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback&lt;A ...@@ -620,9 +623,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback: AsyncCallback&lt;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&lt;LinearAccelerometerResponse&gt;): void once(type:sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback&lt;LinearAccelerometerResponse&gt;): void
监听线性加速度传感器数据变化一次。 监听线性加速度传感器数据变化一次。
...@@ -634,7 +637,7 @@ once(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback&l ...@@ -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) { 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; return;
...@@ -647,9 +650,9 @@ once(type:SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:AsyncCallback&l ...@@ -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&lt;AccelerometerUncalibratedResponse&gt;): void once(type:sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCallback&lt;AccelerometerUncalibratedResponse&gt;): void
监听未校准加速度传感器的数据变化一次。 监听未校准加速度传感器的数据变化一次。
...@@ -661,7 +664,7 @@ once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCal ...@@ -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) { 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; return;
...@@ -677,9 +680,9 @@ once(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback:AsyncCal ...@@ -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&lt;GravityResponse&gt;): void once(type:sensor.SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback&lt;GravityResponse&gt;): void
监听重力传感器的数据变化一次。 监听重力传感器的数据变化一次。
...@@ -691,7 +694,7 @@ once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback&lt;Gravity ...@@ -691,7 +694,7 @@ once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback&lt;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) { 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; return;
...@@ -704,9 +707,9 @@ once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback&lt;Gravity ...@@ -704,9 +707,9 @@ once(type: SensorType.SENSOR_TYPE_ID_GRAVITY, callback: AsyncCallback&lt;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&lt;GyroscopeResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback&lt;GyroscopeResponse&gt;): void
监听陀螺仪传感器的数据变化一次。 监听陀螺仪传感器的数据变化一次。
...@@ -718,7 +721,7 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback&lt;Gyros ...@@ -718,7 +721,7 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback&lt;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) { 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; return;
...@@ -731,9 +734,9 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback&lt;Gyros ...@@ -731,9 +734,9 @@ once(type: SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback: AsyncCallback&lt;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&lt;GyroscopeUncalibratedResponse&gt;): void once(type:sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallback&lt;GyroscopeUncalibratedResponse&gt;): void
监听未校准陀螺仪传感器的数据变化一次。 监听未校准陀螺仪传感器的数据变化一次。
...@@ -745,7 +748,7 @@ once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallbac ...@@ -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) { 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; return;
...@@ -761,9 +764,9 @@ once(type:SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED,callback:AsyncCallbac ...@@ -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&lt;SignificantMotionResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback:AsyncCallback&lt;SignificantMotionResponse&gt;): void
监听有效运动传感器的数据变化一次。 监听有效运动传感器的数据变化一次。
...@@ -775,7 +778,7 @@ once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback:AsyncCallback&l ...@@ -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) { 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; return;
...@@ -786,9 +789,9 @@ once(type: SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION,callback:AsyncCallback&l ...@@ -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&lt;PedometerDetectResponse&gt;): void once(type:sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback:AsyncCallback&lt;PedometerDetectResponse&gt;): void
监听计步检测传感器数据变化一次。 监听计步检测传感器数据变化一次。
...@@ -800,7 +803,7 @@ once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback:AsyncCallback&l ...@@ -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) { 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; return;
...@@ -811,9 +814,9 @@ once(type:SensorType.SENSOR_TYPE_ID_PEDOMETER_DETECTION,callback:AsyncCallback&l ...@@ -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&lt;PedometerResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback&lt;PedometerResponse&gt;): void
监听计步器传感器数据变化一次。 监听计步器传感器数据变化一次。
...@@ -825,7 +828,7 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback&lt;Pedom ...@@ -825,7 +828,7 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback&lt;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) { 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; return;
...@@ -836,9 +839,9 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback&lt;Pedom ...@@ -836,9 +839,9 @@ once(type: SensorType.SENSOR_TYPE_ID_PEDOMETER, callback: AsyncCallback&lt;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&lt;AmbientTemperatureResponse&gt;): void once(type:sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback&lt;AmbientTemperatureResponse&gt;): void
监听环境温度传感器数据变化一次。 监听环境温度传感器数据变化一次。
...@@ -850,7 +853,7 @@ once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback&l ...@@ -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) { 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; return;
...@@ -861,9 +864,9 @@ once(type:SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE,callback:AsyncCallback&l ...@@ -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&lt;MagneticFieldResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt;MagneticFieldResponse&gt;): void
监听磁场传感器数据变化一次。 监听磁场传感器数据变化一次。
...@@ -875,7 +878,7 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt; ...@@ -875,7 +878,7 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt;
- 示例: - 示例:
``` ```
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) { 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; return;
...@@ -888,9 +891,9 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt; ...@@ -888,9 +891,9 @@ once(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback: AsyncCallback&lt;
``` ```
## 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&lt;MagneticFieldUncalibratedResponse&gt;): void once(type:sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCallback&lt;MagneticFieldUncalibratedResponse&gt;): void
监听未校准磁场传感器数据变化一次。 监听未校准磁场传感器数据变化一次。
...@@ -902,7 +905,7 @@ once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCa ...@@ -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) { 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; return;
...@@ -918,9 +921,9 @@ once(type:SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED,callback:AsyncCa ...@@ -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&lt;ProximityResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback&lt;ProximityResponse&gt;): void
监听接近光传感器数据变化一次。 监听接近光传感器数据变化一次。
...@@ -932,7 +935,7 @@ once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback&lt;Proxi ...@@ -932,7 +935,7 @@ once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback&lt;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) { 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; return;
...@@ -943,9 +946,9 @@ once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback&lt;Proxi ...@@ -943,9 +946,9 @@ once(type: SensorType.SENSOR_TYPE_ID_PROXIMITY, callback: AsyncCallback&lt;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&lt;HumidityResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback&lt;HumidityResponse&gt;): void
监听湿度传感器数据变化一次。 监听湿度传感器数据变化一次。
...@@ -957,7 +960,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback&lt;Humidi ...@@ -957,7 +960,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback&lt;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) { 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; return;
...@@ -968,9 +971,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback&lt;Humidi ...@@ -968,9 +971,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback: AsyncCallback&lt;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&lt;BarometerResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback&lt;BarometerResponse&gt;): void
监听气压计传感器数据变化一次。 监听气压计传感器数据变化一次。
...@@ -982,7 +985,7 @@ once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback&lt;Barom ...@@ -982,7 +985,7 @@ once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback&lt;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) { 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; return;
...@@ -993,9 +996,9 @@ once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback&lt;Barom ...@@ -993,9 +996,9 @@ once(type: SensorType.SENSOR_TYPE_ID_BAROMETER, callback: AsyncCallback&lt;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&lt;HallResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback&lt;HallResponse&gt;): void
监听霍尔传感器数据变化一次。 监听霍尔传感器数据变化一次。
...@@ -1007,7 +1010,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback&lt;HallResp ...@@ -1007,7 +1010,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback&lt;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) { 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; return;
...@@ -1018,9 +1021,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback&lt;HallResp ...@@ -1018,9 +1021,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HALL, callback: AsyncCallback&lt;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&lt;LightResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback&lt;LightResponse&gt;): void
监听环境光传感器数据变化一次。 监听环境光传感器数据变化一次。
...@@ -1032,20 +1035,20 @@ once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback&lt;L ...@@ -1032,20 +1035,20 @@ once(type: SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback: AsyncCallback&lt;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) { 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; 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&lt;OrientationResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;OrientationResponse&gt;): void
监听方向传感器数据变化一次。 监听方向传感器数据变化一次。
...@@ -1057,7 +1060,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;Ori ...@@ -1057,7 +1060,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;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) { 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; return;
...@@ -1070,9 +1073,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;Ori ...@@ -1070,9 +1073,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ORIENTATION, callback: AsyncCallback&lt;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&lt;RotationVectorResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback&lt;RotationVectorResponse&gt;): void
监听旋转矢量传感器数据变化一次。 监听旋转矢量传感器数据变化一次。
...@@ -1084,7 +1087,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback&lt ...@@ -1084,7 +1087,7 @@ once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback&lt
- 示例: - 示例:
``` ```
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) { 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; return;
...@@ -1097,9 +1100,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback&lt ...@@ -1097,9 +1100,9 @@ once(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback: AsyncCallback&lt
``` ```
## 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&lt;HeartRateResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback&lt;HeartRateResponse&gt;): void
监听心率传感器数据变化一次。 监听心率传感器数据变化一次。
...@@ -1111,7 +1114,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback&lt;Hear ...@@ -1111,7 +1114,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback&lt;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) { 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; return;
...@@ -1122,9 +1125,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback&lt;Hear ...@@ -1122,9 +1125,9 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: AsyncCallback&lt;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&lt;WearDetectionResponse&gt;): void once(type: sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback&lt;WearDetectionResponse&gt;): void
监听佩戴检测传感器数据变化一次。 监听佩戴检测传感器数据变化一次。
...@@ -1136,7 +1139,7 @@ once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback&lt; ...@@ -1136,7 +1139,7 @@ once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: AsyncCallback&lt;
- 示例: - 示例:
``` ```
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) { if (error) {
console.error("Failed to register data, error code is" + error.code + ", message: " + error.message); console.error("Failed to register data, error code is" + error.code + ", message: " + error.message);
return; return;
...@@ -1161,7 +1164,7 @@ off(type: SensorType, callback?: AsyncCallback&lt;void&gt;): void ...@@ -1161,7 +1164,7 @@ off(type: SensorType, callback?: AsyncCallback&lt;void&gt;): void
- 示例: - 示例:
``` ```
sensor.off(type:SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error) { sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(error) {
if (error) { if (error) {
console.error("Failed to unsubscribe from acceleration sensor data. Error code: " + error.code + "; message: " + error.message); console.error("Failed to unsubscribe from acceleration sensor data. Error code: " + error.code + "; message: " + error.message);
return; return;
......
# 线性容器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&lt;T&gt;) => void,
thisArg?: Object): void;
通过回调函数来遍历Stack实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素。 |
| index | number | 否 | 当前遍历到的下标值。 |
| stack | Stack&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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
# 非线性容器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<K, V>): void;
将一个treemap中的所有元素组添加到另一个treemap中。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| map | TreeMap<K, V> | 是 | 被添加元素的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&lt;K&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;K&gt; | 返回一个迭代器 |
- 示例:
```
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&lt;V&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;V&gt; | 返回一个迭代器 |
- 示例:
```
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<K, V>) => void, thisArg?: Object): void;
通过回调函数来遍历实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | V | 是 | 当前遍历到的元素键值对的值 |
| key | K | 是 | 当前遍历到的元素键值对的键 |
| treeMap | TreeMap<K, V> | 否 | 当前调用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&lt;[K, V]&gt;;
返回一个迭代器,迭代器的每一项都是一个 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
# 非线性容器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&lt;T&gt;;
返回包含此映射中包含的键的新迭代器对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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&lt;T&gt;) => void, thisArg?: Object): void;
通过回调函数来遍历实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素 |
| key | T | 否 | 当前遍历到的元素(和value相同). |
| treeSet | TreeSet&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器 |
- 示例:
```
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
...@@ -10,12 +10,6 @@ ...@@ -10,12 +10,6 @@
import uri from '@ohos.uri' import uri from '@ohos.uri'
``` ```
## 权限
## URI ## URI
...@@ -64,7 +58,7 @@ toString(): string ...@@ -64,7 +58,7 @@ toString(): string
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| string | 用于返回网址的字符串序列化。 | | string | 返回网址的字符串序列化。 |
- 示例: - 示例:
``` ```
...@@ -87,7 +81,7 @@ equals(other: URI): boolean ...@@ -87,7 +81,7 @@ equals(other: URI): boolean
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| boolean | 用于测试此URI是否与其他URI对象相等。 | | boolean | 返回true表示相等,否则返回false。 |
- 示例: - 示例:
``` ```
...@@ -96,15 +90,16 @@ equals(other: URI): boolean ...@@ -96,15 +90,16 @@ equals(other: URI): boolean
uriInstance.equals(uriInstance1); uriInstance.equals(uriInstance1);
``` ```
### checkIsAbsolute ### checkIsAbsolute
判断此URI是否为绝对URI。 checkIsAbsolute(): boolean
判断此URI是否为绝对URI(是否定义了scheme组件)。
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| boolean | 用于说明此URI是否为绝对URI(是否定义了scheme组件)。 | | boolean | 返回true表示该URI是否为绝对URI。 |
- 示例: - 示例:
``` ```
...@@ -122,7 +117,7 @@ normalize(): URI ...@@ -122,7 +117,7 @@ normalize(): URI
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| URI | 用于规范化此URI的路径,并返回一个path被规范化后的URI对象。 | | URI | 返回一个path被规范化后的URI对象。 |
- 示例: - 示例:
``` ```
......
...@@ -11,11 +11,6 @@ import Url from '@ohos.url' ...@@ -11,11 +11,6 @@ import Url from '@ohos.url'
``` ```
## 权限
## URLSearchParams ## URLSearchParams
......
...@@ -15,11 +15,6 @@ import util from '@ohos.util'; ...@@ -15,11 +15,6 @@ import util from '@ohos.util';
``` ```
## 权限
## util.printf ## util.printf
printf(format: string, ...args: Object[]): string printf(format: string, ...args: Object[]): string
...@@ -296,7 +291,7 @@ RationalNumber的构造函数。 ...@@ -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) ...@@ -551,7 +546,7 @@ constructor(capacity?:number)
- 示例: - 示例:
``` ```
var lrubuffer= new util.LruBuffer() var lrubuffer= new util.LruBuffer();
``` ```
...@@ -661,7 +656,7 @@ getMissCount():number ...@@ -661,7 +656,7 @@ getMissCount():number
``` ```
var pro = new util.LruBuffer(); var pro = new util.LruBuffer();
pro.put(2,10); pro.put(2,10);
pro.get(2) pro.get(2);
var result = pro.getMissCount(); var result = pro.getMissCount();
``` ```
...@@ -896,7 +891,7 @@ afterRemoval(isEvict:boolean,key:K,value:V,newValue:V):void ...@@ -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 ...@@ -1115,7 +1110,7 @@ intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope
var tempMiDF = new Temperature(35); var tempMiDF = new Temperature(35);
var tempMidS = new Temperature(39); var tempMidS = new Temperature(39);
var range = new util.Scope(tempLower, tempUpper); 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 ...@@ -1135,7 +1130,7 @@ getUpper():ScopeType
var tempLower = new Temperature(30); var tempLower = new Temperature(30);
var tempUpper = new Temperature(40); var tempUpper = new Temperature(40);
var range = new util.Scope(tempLower, tempUpper); var range = new util.Scope(tempLower, tempUpper);
var result = range.getUpper() var result = range.getUpper();
``` ```
...@@ -1155,7 +1150,7 @@ getLower():ScopeType ...@@ -1155,7 +1150,7 @@ getLower():ScopeType
var tempLower = new Temperature(30); var tempLower = new Temperature(30);
var tempUpper = new Temperature(40); var tempUpper = new Temperature(40);
var range = new util.Scope(tempLower, tempUpper); 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 ...@@ -1183,7 +1178,7 @@ expand(lowerObj:ScopeType,upperObj:ScopeType):Scope
var tempMiDF = new Temperature(35); var tempMiDF = new Temperature(35);
var tempMidS = new Temperature(39); var tempMidS = new Temperature(39);
var range = new util.Scope(tempLower, tempUpper); 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 ...@@ -1211,7 +1206,7 @@ expand(range:Scope):Scope
var tempMidS = new Temperature(39); var tempMidS = new Temperature(39);
var range = new util.Scope(tempLower, tempUpper); var range = new util.Scope(tempLower, tempUpper);
var rangeFir = new util.Scope(tempMiDF, tempMidS); 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 ...@@ -1237,7 +1232,7 @@ expand(value:ScopeType):Scope
var tempUpper = new Temperature(40); var tempUpper = new Temperature(40);
var tempMiDF = new Temperature(35); var tempMiDF = new Temperature(35);
var range = new util.Scope(tempLower, tempUpper); 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 ...@@ -1263,7 +1258,7 @@ contains(value:ScopeType):boolean
var tempUpper = new Temperature(40); var tempUpper = new Temperature(40);
var tempMiDF = new Temperature(35); var tempMiDF = new Temperature(35);
var range = new util.Scope(tempLower, tempUpper); var range = new util.Scope(tempLower, tempUpper);
range.contains(tempMiDF) range.contains(tempMiDF);
``` ```
...@@ -1291,7 +1286,7 @@ contains(range:Scope):boolean ...@@ -1291,7 +1286,7 @@ contains(range:Scope):boolean
var tempLess = new Temperature(20); var tempLess = new Temperature(20);
var tempMore = new Temperature(45); var tempMore = new Temperature(45);
var rangeSec = new util.Scope(tempLess, tempMore); 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 ...@@ -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 ...@@ -1317,7 +1312,7 @@ clamp(value:ScopeType):ScopeType
var tempUpper = new Temperature(40); var tempUpper = new Temperature(40);
var tempMiDF = new Temperature(35); var tempMiDF = new Temperature(35);
var range = new util.Scope(tempLower, tempUpper); var range = new util.Scope(tempLower, tempUpper);
var result = range.clamp(tempMiDF) var result = range.clamp(tempMiDF);
``` ```
...@@ -1332,7 +1327,7 @@ Base64的构造函数。 ...@@ -1332,7 +1327,7 @@ Base64的构造函数。
- 示例: - 示例:
``` ```
var base64 = new util.Base64() var base64 = new util.Base64();
``` ```
...@@ -1429,12 +1424,11 @@ encode(src:Uint8Array):Promise&lt;Uint8Array&gt; ...@@ -1429,12 +1424,11 @@ encode(src:Uint8Array):Promise&lt;Uint8Array&gt;
var that = new util.Base64(); var that = new util.Base64();
var array = new Uint8Array([115,49,51]); var array = new Uint8Array([115,49,51]);
var rarray = new Uint8Array([99,122,69,122]); 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++) { for (var i = 0; i < rarray.length; i++) {
expect(val[i]).assertEqual(rarray[i]) expect(val[i]).assertEqual(rarray[i])
} }
}) })
done();
``` ```
...@@ -1458,10 +1452,9 @@ encodeToString(src:Uint8Array):Promise&lt;string&gt; ...@@ -1458,10 +1452,9 @@ encodeToString(src:Uint8Array):Promise&lt;string&gt;
``` ```
var that = new util.Base64(); var that = new util.Base64();
var array = new Uint8Array([115,49,51]); var array = new Uint8Array([115,49,51]);
await that.encodeToString(array).then(val=>{ that.encodeToString(array).then(val=>{
expect(val).assertEqual('czEz') expect(val).assertEqual('czEz')
}) })
done();
``` ```
...@@ -1486,12 +1479,11 @@ decode(src:Uint8Array | string):Promise&lt;Uint8Array&gt; ...@@ -1486,12 +1479,11 @@ decode(src:Uint8Array | string):Promise&lt;Uint8Array&gt;
var that = new util.Base64(); var that = new util.Base64();
var array = new Uint8Array([99,122,69,122]); var array = new Uint8Array([99,122,69,122]);
var rarray = new Uint8Array([115,49,51]); 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++) { for (var i = 0; i < rarray.length; i++) {
expect(val[i]).assertEqual(rarray[i]) expect(val[i]).assertEqual(rarray[i])
} }
}) })
done();
``` ```
...@@ -1588,7 +1580,7 @@ isArgumentsObject(value: Object):boolean ...@@ -1588,7 +1580,7 @@ isArgumentsObject(value: Object):boolean
isArrayBuffer(value: Object):boolean isArrayBuffer(value: Object):boolean
检查输入的value是否是ArrayBuffer对象类型。 检查输入的value是否是ArrayBuffer类型。
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
......
# 线性容器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&lt;T&gt;) => T,
thisArg?: Object): void;
用户操作Vector中的元素,用操作后的元素替换原元素并返回操作后的元素。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素 |
| index | number | 否 | 当前遍历到的下标值 |
| vector | Vector&lt;T&gt; | 否 | 当前调用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&lt;T&gt;) => void,
thisArg?: Object): void;
通过回调函数来遍历Vector实例对象上的元素以及元素对应的下标。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| callbackfn | function | 是 | 回调函数。 |
| thisArg | Object | 否 | callbackfn被调用时用作this值 |
- callbackfn的参数说明
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| value | T | 是 | 当前遍历到的元素。 |
| index | number | 否 | 当前遍历到的下标值。 |
| vector | Vector&lt;T&gt; | 否 | 当前调用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&lt;T&gt;;
根据下标截取Vector中的一段元素,并返回这一段vector实例,包括起始值但不包括终止值。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| fromIndex | number | 是 | 起始下标 |
| toIndex | number | 是 | 终止下标 |
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Vector&lt;T&gt; | 返回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&lt;T&gt;;
克隆一个与Vector一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Vector&lt;T&gt; | 返回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&lt;T&gt;;
把当前Vector实例转换成数组,并返回转换后的数组。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| Array&lt;T&gt; | 返回数组类型 |
- 示例:
```
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&lt;T&gt;): void;
将Vector实例中的元素按照下标复制进array。
- 参数:
| 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- |
| array | Array&lt;T&gt; | 是 | 数组 |
- 示例:
```
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&lt;T&gt;;
返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。
- 返回值:
| 类型 | 说明 |
| -------- | -------- |
| IterableIterator&lt;T&gt; | 返回一个迭代器。 |
- 示例:
```
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
...@@ -7,16 +7,19 @@ ...@@ -7,16 +7,19 @@
## 导入模块 ## 导入模块
``` ```
import vibrate from '@ohos.vibrator'; import vibrator from '@ohos.vibrator';
``` ```
## 系统能力
SystemCapability.Sensors.MiscDevice
## 权限列表 ## 权限列表
ohos.permission.VIBRATE ohos.permission.VIBRATE
## vibrate.vibrate ## vibrator.vibrate
vibrate(duration: number): Promise&lt;void&gt; vibrate(duration: number): Promise&lt;void&gt;
...@@ -37,17 +40,15 @@ vibrate(duration: number): Promise&lt;void&gt; ...@@ -37,17 +40,15 @@ vibrate(duration: number): Promise&lt;void&gt;
- 示例: - 示例:
``` ```
vibrator.vibrate(1000).then(error)=>{ vibrator.vibrate(1000).then(()=>{
if(error){ console.log("Promise returned to indicate a successful vibration.");
console.log(“error.code”+error.code+“error.message”+error.message); }, (error)=>{
}else{ console.log("error.code"+error.code+"error.message"+error.message);
console.log(“Promise returned to indicate a successful vibration.”); });
}
}
``` ```
## vibrate.vibrate ## vibrator.vibrate
vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void
...@@ -62,16 +63,16 @@ vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void ...@@ -62,16 +63,16 @@ vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void
- 示例**:** - 示例**:**
``` ```
vibrator.vibrate(1000,function(error){ vibrator.vibrate(1000,function(error){
if(error){ if(error){
console.log(“error.code”+error.code+“error.message”+error.message); console.log("error.code"+error.code+"error.message"+error.message);
}else{ }else{
console.log(“Callback returned to indicate a successful vibration.”); console.log("Callback returned to indicate a successful vibration.");
} }
}) })
``` ```
## vibrate.vibrate ## vibrator.vibrate
vibrate(effectId: EffectId): Promise&lt;void&gt; vibrate(effectId: EffectId): Promise&lt;void&gt;
...@@ -89,17 +90,15 @@ vibrate(effectId: EffectId): Promise&lt;void&gt; ...@@ -89,17 +90,15 @@ vibrate(effectId: EffectId): Promise&lt;void&gt;
- 示例: - 示例:
``` ```
vibrator.vibrate(effectId:EffectId).then(error)=>{ vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{
if(error){ console.log("Promise returned to indicate a successful vibration.");
console.log(“error.code”+error.code+“error.message”+error.message); }, (error)=>{
}else{ console.log("error.code"+error.code+"error.message"+error.message);
Console.log(“Promise returned to indicate a successful vibration.”); });
}
}
``` ```
## vibrate.vibrate ## vibrator.vibrate
vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void
...@@ -113,17 +112,17 @@ vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void ...@@ -113,17 +112,17 @@ vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void
- 示例: - 示例:
``` ```
vibrator.vibrate(effectId:EffectId,function(error){ vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){
if(error){ if(error){
console.log(“error.code”+error.code+“error.message”+error.message); console.log("error.code"+error.code+"error.message"+error.message);
}else{ }else{
console.log(“Callback returned to indicate a successful vibration.”); console.log("Callback returned to indicate a successful vibration.");
} }
}) })
``` ```
## vibrate.stop ## vibrator.stop
stop(stopMode: VibratorStopMode): Promise&lt;void&gt; stop(stopMode: VibratorStopMode): Promise&lt;void&gt;
...@@ -141,17 +140,15 @@ stop(stopMode: VibratorStopMode): Promise&lt;void&gt; ...@@ -141,17 +140,15 @@ stop(stopMode: VibratorStopMode): Promise&lt;void&gt;
- 示例: - 示例:
``` ```
vibrator.stop(stopMode:VibratorStopMode).then((error)=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{
if(error){ console.log("Promise returned to indicate a successful vibration.");
console.log(“error.code”+error.code+“error.message”+error.message); }, (error)=>{
}else{ console.log("error.code"+error.code+"error.message"+error.message);
Console.log(“Promise returned to indicate successful.”); });
}
})
``` ```
## vibrate.stop ## vibrator.stop
stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void; stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void;
...@@ -165,12 +162,12 @@ stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void; ...@@ -165,12 +162,12 @@ stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void;
- 示例: - 示例:
``` ```
vibrator.stop(stopMode:VibratorStopMode,function(error){ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){
if(error){ if(error){
console.log(“error.code”+error.code+“error.message”+error.message); console.log("error.code"+error.code+"error.message"+error.message);
}else{ }else{
Console.log(“Callback returned to indicate successful.”); console.log("Callback returned to indicate successful.");
} }
}) })
``` ```
......
...@@ -11,6 +11,11 @@ import window from '@ohos.window'; ...@@ -11,6 +11,11 @@ import window from '@ohos.window';
``` ```
## 系统能力
SystemCapability.WindowManager.WindowManager.Core
## 权限列表 ## 权限列表
ohos.permission.SYSTEM_FLOAT_WINDOW ohos.permission.SYSTEM_FLOAT_WINDOW
...@@ -189,7 +194,7 @@ getAbilityWindowMode(callback: AsyncCallback&lt;WindowMode&gt;): void ...@@ -189,7 +194,7 @@ getAbilityWindowMode(callback: AsyncCallback&lt;WindowMode&gt;): void
``` ```
window.getAbilityWindowMode((err, data) => { window.getAbilityWindowMode((err, data) => {
if (err) { 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; return;
} }
console.info('Window mode obtained. Data:' + JSON.stringify(data)) console.info('Window mode obtained. Data:' + JSON.stringify(data))
......
...@@ -11,11 +11,6 @@ import worker from '@ohos.worker'; ...@@ -11,11 +11,6 @@ import worker from '@ohos.worker';
``` ```
## 权限
## 属性 ## 属性
| 名称 | 参数类型 | 可读 | 可写 | 说明 | | 名称 | 参数类型 | 可读 | 可写 | 说明 |
...@@ -51,7 +46,7 @@ worker构造函数。 ...@@ -51,7 +46,7 @@ worker构造函数。
| options | [WorkerOptions](#workeroptions) | 否 | worker构造的选项。 | | options | [WorkerOptions](#workeroptions) | 否 | worker构造的选项。 |
- 返回值: - 返回值:
| 参数名 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| worker | 执行Worker构造函数生成的Worker对象,失败则返回undefined。 | | worker | 执行Worker构造函数生成的Worker对象,失败则返回undefined。 |
...@@ -294,7 +289,7 @@ dispatchEvent(event: Event): boolean ...@@ -294,7 +289,7 @@ dispatchEvent(event: Event): boolean
| event | [Event](#event) | 是 | 需要分发的事件。 | | event | [Event](#event) | 是 | 需要分发的事件。 |
- 返回值: - 返回值:
| 参数名 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| boolean | 分发的结果,false表示分发失败。 | | boolean | 分发的结果,false表示分发失败。 |
...@@ -347,7 +342,7 @@ worker向宿主线程发送消息。 ...@@ -347,7 +342,7 @@ worker向宿主线程发送消息。
``` ```
``` ```
// worker.js // worker.js
import worker from "@ohos.worker"; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessage = function(e){ parentPort.onmessage = function(e){
parentPort.postMessage("receive data from main.js") parentPort.postMessage("receive data from main.js")
...@@ -369,7 +364,7 @@ close(): void ...@@ -369,7 +364,7 @@ close(): void
``` ```
``` ```
// worker.js // worker.js
import worker from "@ohos.worker"; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessage = function(e) { parentPort.onmessage = function(e) {
parentPort.close() parentPort.close()
...@@ -397,7 +392,7 @@ DedicatedWorkerGlobalScope的onmessage属性表示worker线程收到来自其宿 ...@@ -397,7 +392,7 @@ DedicatedWorkerGlobalScope的onmessage属性表示worker线程收到来自其宿
``` ```
``` ```
// worker.js // worker.js
import worker from "@ohos.worker"; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessage = function(e) { parentPort.onmessage = function(e) {
console.log("receive main.js message") console.log("receive main.js message")
...@@ -424,7 +419,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当 Worker 对象接收 ...@@ -424,7 +419,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当 Worker 对象接收
``` ```
``` ```
// worker.js // worker.js
import worker from "@ohos.worker"; import worker from '@ohos.worker';
const parentPort = worker.parentPort; const parentPort = worker.parentPort;
parentPort.onmessageerror= function(e) { parentPort.onmessageerror= function(e) {
console.log("worker.js onmessageerror") console.log("worker.js onmessageerror")
...@@ -466,7 +461,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当 Worker 对象接收 ...@@ -466,7 +461,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当 Worker 对象接收
| evt | [Event](#event) | 是 | 回调的事件类。 | | evt | [Event](#event) | 是 | 回调的事件类。 |
- 返回值 - 返回值
| 参数名 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| void&nbsp;\|&nbsp;Promise&lt;void&gt; | 无返回值或者以Promise形式返回。 | | void&nbsp;\|&nbsp;Promise&lt;void&gt; | 无返回值或者以Promise形式返回。 |
...@@ -533,7 +528,7 @@ WorkerGlobalScope的onerror属性表示worker在执行过程中发生异常被 ...@@ -533,7 +528,7 @@ WorkerGlobalScope的onerror属性表示worker在执行过程中发生异常被
``` ```
``` ```
// worker.js // worker.js
import worker from "@ohos.worker"; import worker from '@ohos.worker';
const parentPort = worker.parentPort const parentPort = worker.parentPort
parentPort.onerror = function(e){ parentPort.onerror = function(e){
console.log("worker.js onerror") console.log("worker.js onerror")
......
...@@ -11,11 +11,6 @@ import xml from '@ohos.xml'; ...@@ -11,11 +11,6 @@ import xml from '@ohos.xml';
``` ```
## 权限
## XmlSerializer ## XmlSerializer
...@@ -28,7 +23,7 @@ XmlSerializer的构造函数。 ...@@ -28,7 +23,7 @@ XmlSerializer的构造函数。
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| buffer | ArrayBuffer&nbsp;\|&nbsp;DataView | 是 | 用于接收写入xml信息的ArrayBuffer&nbsp;\|&nbsp;DataView内存。 | | buffer | ArrayBuffer&nbsp;\|&nbsp;DataView | 是 | 用于接收写入xml信息的ArrayBufferDataView内存。 |
| encoding | string | 否 | 编码格式。 | | encoding | string | 否 | 编码格式。 |
- 示例: - 示例:
...@@ -48,8 +43,8 @@ setAttributes(name: string, value: string):void ...@@ -48,8 +43,8 @@ setAttributes(name: string, value: string):void
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | 是 | 属性的key值 | | name | string | 是 | 属性的key值 |
| value | string | 是 | 属性的value值 | | value | string | 是 | 属性的value值 |
- 示例: - 示例:
``` ```
...@@ -67,7 +62,7 @@ addEmptyElement(name: string): void ...@@ -67,7 +62,7 @@ addEmptyElement(name: string): void
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | 是 | 该空元素的元素名 | | name | string | 是 | 该空元素的元素名 |
- 示例: - 示例:
``` ```
...@@ -93,12 +88,12 @@ setDeclaration(): void ...@@ -93,12 +88,12 @@ setDeclaration(): void
startElement(name: string): void startElement(name: string): void
XmlSerializer的构造函数 根据给定名称写入元素开始标记
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | 是 | 当前元素的元素名 | | name | string | 是 | 当前元素的元素名 |
- 示例: - 示例:
``` ```
...@@ -113,7 +108,7 @@ XmlSerializer的构造函数。 ...@@ -113,7 +108,7 @@ XmlSerializer的构造函数。
endElement(): void endElement(): void
设置结束元素方法 写入元素结束标记
- 示例: - 示例:
``` ```
...@@ -135,8 +130,8 @@ setNamespace(prefix: string, namespace: string): void ...@@ -135,8 +130,8 @@ setNamespace(prefix: string, namespace: string): void
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| prefix | string | 是 | 当前元素及其子元素的前缀 | | prefix | string | 是 | 当前元素及其子元素的前缀 |
| namespace | string | 是 | 当前元素及其子元素的命名空间 | | namespace | string | 是 | 当前元素及其子元素的命名空间 |
- 示例: - 示例:
``` ```
...@@ -148,43 +143,43 @@ setNamespace(prefix: string, namespace: string): void ...@@ -148,43 +143,43 @@ setNamespace(prefix: string, namespace: string): void
thatSer.endElement();// = >'<?xml version="1.0" encoding="utf-8"?>\r\n<h:note xmlns:h="http://www.w3.org/TR/html4/"/>'; thatSer.endElement();// = >'<?xml version="1.0" encoding="utf-8"?>\r\n<h:note xmlns:h="http://www.w3.org/TR/html4/"/>';
``` ```
### setCommnet ### setComment
setCommnet(text: string): void setComment(text: string): void
写入comment属性。 写入comment属性。
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| text | string | 是 | 当前元素的注释内容 | | text | string | 是 | 当前元素的注释内容 |
- 示例: - 示例:
``` ```
var arrayBuffer = new ArrayBuffer(1024); var arrayBuffer = new ArrayBuffer(1024);
var thatSer = new xml.XmlSerializer(arrayBuffer); var thatSer = new xml.XmlSerializer(arrayBuffer);
thatSer.startElement("note"); thatSer.startElement("note");
thatSer.setCommnet("Hi!"); thatSer.setComment("Hi!");
thatSer.endElement(); // => '<note>\r\n <!--Hi!-->\r\n</note>'; thatSer.endElement(); // => '<note>\r\n <!--Hi!-->\r\n</note>';
``` ```
### setCData ### setCDATA
setCData(text: string): void setCDATA(text: string): void
写入CData属性。 写入CDATA属性。
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| text | string | 是 | CDate属性的内容 | | text | string | 是 | CDATA属性的内容。 |
- 示例: - 示例:
``` ```
var arrayBuffer = new ArrayBuffer(1028); var arrayBuffer = new ArrayBuffer(1028);
var thatSer = new xml.XmlSerializer(arrayBuffer); var thatSer = new xml.XmlSerializer(arrayBuffer);
thatSer.setCData('root SYSTEM') // => '<![CDATA[root SYSTEM]]>'; thatSer.setCDATA('root SYSTEM') // => '<![CDATA[root SYSTEM]]>';
``` ```
...@@ -197,7 +192,7 @@ setText(text: string): void ...@@ -197,7 +192,7 @@ setText(text: string): void
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| text | string | 是 | text属性的内容 | | text | string | 是 | text属性的内容 |
- 示例: - 示例:
``` ```
...@@ -219,7 +214,7 @@ setDocType(text: string): void ...@@ -219,7 +214,7 @@ setDocType(text: string): void
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| text | string | 是 | DocType属性的内容 | | text | string | 是 | DocType属性的内容 |
- 示例: - 示例:
``` ```
...@@ -241,8 +236,8 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string) ...@@ -241,8 +236,8 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string)
- 参数: - 参数:
| 参数名 | 类型 | 必填 | 说明 | | 参数名 | 类型 | 必填 | 说明 |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| buffer | ArrayBuffer&nbsp;\|&nbsp;DataView | 是 | 含有xml文本信息的ArrayBuffer&nbsp;或者DataView | | buffer | ArrayBuffer&nbsp;\|&nbsp;DataView | 是 | 含有xml文本信息的ArrayBuffer或者DataView。 |
| encoding | string | 否 | 编码格式(仅支持utf-8) | | encoding | string | 否 | 编码格式(仅支持utf-8) |
- 示例: - 示例:
``` ```
...@@ -325,12 +320,12 @@ xml解析选项。 ...@@ -325,12 +320,12 @@ xml解析选项。
getColumnNumber(): number getColumnNumber(): number
获取当前号,从1开始。 获取当前号,从1开始。
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| number | 返回当前号。 | | number | 返回当前号。 |
### getDepth ### getDepth
...@@ -349,12 +344,12 @@ getDepth(): number ...@@ -349,12 +344,12 @@ getDepth(): number
getLineNumber(): number getLineNumber(): number
获取当前号,从1开始。 获取当前号,从1开始。
- 返回值: - 返回值:
| 类型 | 说明 | | 类型 | 说明 |
| -------- | -------- | | -------- | -------- |
| number | 返回当前号。 | | number | 返回当前号。 |
### getName ### getName
......
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
OpenHarmony的目标是面向全场景、全连接、全智能时代,基于开源的方式,搭建一个智能终端设备操作系统的框架和平台,促进万物互联产业的繁荣发展。具有“硬件互助,资源共享”、“一次开发,多端部署”、“统一OS,弹性部署”的技术特性。 OpenHarmony的目标是面向全场景、全连接、全智能时代,基于开源的方式,搭建一个智能终端设备操作系统的框架和平台,促进万物互联产业的繁荣发展。具有“硬件互助,资源共享”、“一次开发,多端部署”、“统一OS,弹性部署”的技术特性。
OpenHarmony支持三种系统类型: 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 2. 小型系统(small system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为1MiB
3. 标准系统(standard system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为128MiB 3. 标准系统(standard system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为128MiB
...@@ -35,7 +35,7 @@ OpenHarmony支持三种系统类型: ...@@ -35,7 +35,7 @@ OpenHarmony支持三种系统类型:
| size_t | **4** | **8** | **8** | 4 | 8 | | size_t | **4** | **8** | **8** | 4 | 8 |
| pointer | **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 | 备注 | | Type | ILP32 sizeof | ILP32 print | LP64 sizeof | LP64 print | 备注 |
| ------------------ | ------------ | ----------- | ----------- | ---------- | ------ | | ------------------ | ------------ | ----------- | ----------- | ---------- | ------ |
...@@ -115,8 +115,8 @@ typedef struct tagFoo { ...@@ -115,8 +115,8 @@ typedef struct tagFoo {
| uint16_t | 2 | 2 | %u | 代替unsigned short | | uint16_t | 2 | 2 | %u | 代替unsigned short |
| int32_t | 4 | 4 | %d | 代替int | | int32_t | 4 | 4 | %d | 代替int |
| uint32_t | 4 | 4 | %u | 代替unsigned int | | uint32_t | 4 | 4 | %u | 代替unsigned int |
| int64_t | 8 | 8 | %PRId64 | 代替long long宏实现代码兼容 | | int64_t | 8 | 8 | %PRId64 | 代替long long宏实现代码兼容 |
| uint64_t | 8 | 8 | %PRIu64 | 代替unsigned longlong,宏实现代码兼容 | | uint64_t | 8 | 8 | %PRIu64 | 代替unsigned long long、宏实现代码兼容 |
| float | 4 | 4 | %f | 单精度浮点数 | | float | 4 | 4 | %f | 单精度浮点数 |
| double | 8 | 8 | %lf | 双精度浮点数 | | double | 8 | 8 | %lf | 双精度浮点数 |
| bool | 1 | 1 | %d | 布尔类型 | | bool | 1 | 1 | %d | 布尔类型 |
...@@ -170,7 +170,7 @@ long var; ...@@ -170,7 +170,7 @@ long var;
#### 【规则】当需要采用整型变量来存储指针时,变量应该定义成uintptr_t以适应不同的位宽 #### 【规则】当需要采用整型变量来存储指针时,变量应该定义成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 ...@@ -262,7 +262,7 @@ format ‘%p’ expects argument of type ‘void *’, but argument 2 has type
| 0x80000000LL | 8 | 8 | 增加LL后缀,小于uint32_t范围,长度固定 | | 0x80000000LL | 8 | 8 | 增加LL后缀,小于uint32_t范围,长度固定 |
| 0x8000000000 | **NA或8** | **8** | 无后缀,超过uint32_t的范围,编译器默认为LL或无效,64位下固定为uint64_t类型 | | 0x8000000000 | **NA或8** | **8** | 无后缀,超过uint32_t的范围,编译器默认为LL或无效,64位下固定为uint64_t类型 |
| 0x8000000000L | **NA或8** | **8** | 后缀为L,对超过uint32_t的范围常数,增加该参数没有意义,应当避免使用 | | 0x8000000000L | **NA或8** | **8** | 后缀为L,对超过uint32_t的范围常数,增加该参数没有意义,应当避免使用 |
| 0x8000000000LL | 8 | 8 | 默认为LL,uint64_t类型 | | 0x8000000000LL | 8 | 8 | 后缀为LL,uint64_t类型 |
从上表中可看出,使用L或UL后缀的常量,其长度在32位和64位下发生变化,不利于代码的可移植性,因此禁止使用这个后缀。 从上表中可看出,使用L或UL后缀的常量,其长度在32位和64位下发生变化,不利于代码的可移植性,因此禁止使用这个后缀。
...@@ -533,7 +533,7 @@ q = (int32_t *) (int32_t)&i; ...@@ -533,7 +533,7 @@ q = (int32_t *) (int32_t)&i;
int32_t length = (int32_t)strlen(str); // 错误 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循环索引时,索引类型应当与下标边界保持一致 #### 【规则】在64位环境下使用大数组或大for循环索引时,索引类型应当与下标边界保持一致
......
...@@ -16,7 +16,7 @@ HDF(Hardware Driver Foundation)驱动框架,为开发者提供驱动框架 ...@@ -16,7 +16,7 @@ HDF(Hardware Driver Foundation)驱动框架,为开发者提供驱动框架
#### 【规则】OpenHarmony的驱动程序,应当使用HDF框架提供的能力实现 #### 【规则】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 { ...@@ -332,7 +332,7 @@ root {
#### 【建议】当preload字段配置为默认加载时,应当根据业务要求配置按序加载的优先级 #### 【建议】当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字段,保证各个驱动的启动顺序。
【样例】 【样例】
......
...@@ -66,6 +66,12 @@ ...@@ -66,6 +66,12 @@
```js ```js
import call from '@ohos.telephony.call'; import call from '@ohos.telephony.call';
``` ```
## 系统能力
> *写作说明*
>
> 3.1 - 必选。
>
示例:SystemCapability.BundleManager.BundleFramework
## 属性 ## 属性
......
...@@ -43,7 +43,7 @@ OpenHarmony为开发者提供了两种Docker环境,以帮助开发者快速完 ...@@ -43,7 +43,7 @@ OpenHarmony为开发者提供了两种Docker环境,以帮助开发者快速完
</td> </td>
<td class="cellrowborder" valign="top" width="35.8935893589359%" headers="mcps1.2.6.1.4 "><p id="p12667431305"><a name="p12667431305"></a><a name="p12667431305"></a>swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker</p> <td class="cellrowborder" valign="top" width="35.8935893589359%" headers="mcps1.2.6.1.4 "><p id="p12667431305"><a name="p12667431305"></a><a name="p12667431305"></a>swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker</p>
</td> </td>
<td class="cellrowborder" valign="top" width="15.69156915691569%" headers="mcps1.2.6.1.5 "><p id="p143320173017"><a name="p143320173017"></a><a name="p143320173017"></a>0.0.5</p> <td class="cellrowborder" valign="top" width="15.69156915691569%" headers="mcps1.2.6.1.5 "><p id="p143320173017"><a name="p143320173017"></a><a name="p143320173017"></a>0.0.6</p>
</td> </td>
</tr> </tr>
<tr id="row998612174129"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p1998617172126"><a name="p1998617172126"></a><a name="p1998617172126"></a>标准系统</p> <tr id="row998612174129"><td class="cellrowborder" valign="top" headers="mcps1.2.6.1.1 "><p id="p1998617172126"><a name="p1998617172126"></a><a name="p1998617172126"></a>标准系统</p>
...@@ -73,6 +73,7 @@ OpenHarmony为开发者提供了两种Docker环境,以帮助开发者快速完 ...@@ -73,6 +73,7 @@ OpenHarmony为开发者提供了两种Docker环境,以帮助开发者快速完
## 环境准备<a name="section7337134183512"></a> ## 环境准备<a name="section7337134183512"></a>
在使用docker环境前需要先完成以下操作: 在使用docker环境前需要先完成以下操作:
...@@ -90,12 +91,10 @@ OpenHarmony的Docker镜像托管在[HuaweiCloud SWR](https://console.huaweicloud ...@@ -90,12 +91,10 @@ OpenHarmony的Docker镜像托管在[HuaweiCloud SWR](https://console.huaweicloud
### 搭建Docker环境-轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB)<a name="section319412277287"></a> ### 搭建Docker环境-轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB)<a name="section319412277287"></a>
**方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:**
1. 获取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构建环境。 2. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。
...@@ -103,43 +102,13 @@ OpenHarmony的Docker镜像托管在[HuaweiCloud SWR](https://console.huaweicloud ...@@ -103,43 +102,13 @@ OpenHarmony的Docker镜像托管在[HuaweiCloud SWR](https://console.huaweicloud
ubuntu下执行: 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
```
**方式二:通过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
``` ```
windows下执行(假设源码目录为D:\\OpenHarmony): 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 ...@@ -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)<a name="section193711513406"></a> ### 编译源码-标准系统类设备(参考内存≥128MB)<a name="section193711513406"></a>
通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。 通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。
......
...@@ -71,15 +71,14 @@ kernel_version = "3.0.0" --- 内核版本,跟config.json中kern ...@@ -71,15 +71,14 @@ kernel_version = "3.0.0" --- 内核版本,跟config.json中kern
3. 验证`hb set`配置是否正确,输入`hb set`能够显示如下图片表示配置正确。 3. 验证`hb set`配置是否正确,输入`hb set`能够显示如下图片表示配置正确。
详细地,执行`hb set`输入项目根目录,并且回车,遍历所有`//vendor/<product_company>/<product_name>`目录下的`config.json`,给出可选产品编译选项,`config.json``product_name`用于显示产品名,`device_company``board`用于关联出`//device/board/<device_company>/<board>`目录,并且匹配`<any_dir_name>/config.gni`文件,如果能够匹配多个文件,表示该单板适配了多个内核,那么可以根据`config.json``kernel_type``kernel_version`来唯一匹配`config.gni``kernel_type``kernel_version`,这样就可以确定了需要编译适配了哪个内核的单板。 执行`hb set`输入项目根目录,并且回车,`hb`命令会遍历所有`//vendor/<product_company>/<product_name>`目录下的`config.json`,给出可选产品编译选项,`config.json``product_name`用于显示产品名,`device_company``board`用于关联出`//device/board/<device_company>/<board>`目录,并且匹配`<any_dir_name>/config.gni`文件,如果能够匹配多个文件,表示该单板适配了多个内核,那么可以根据`config.json``kernel_type``kernel_version`来唯一匹配`config.gni``kernel_type``kernel_version`,即可确定了需要编译适配了哪个内核的单板。
![hb set](figure/bes2600_hb_set.png) ![hb set](figure/bes2600_hb_set.png)
​ 通过`hb env`可以查看选择出来的预编译环境变量。 ​ 通过`hb env`可以查看选择出来的预编译环境变量。
![hb env](figure/bes2600_hb_env.png) ![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" ...@@ -143,18 +142,18 @@ orsource "../../device/soc/*/Kconfig.liteos_m.soc"
``` ```
. .
├── v200zr --- v200zr单板配置目录 ├── v200zr --- v200zr单板配置目录
│   ├── Kconfig.liteos_m.board --- 提供v200zr单板的配置选项 │   ├── Kconfig.liteos_m.board --- 提供v200zr单板的配置选项
│   ├── Kconfig.liteos_m.defconfig.board --- 提供v200zr单板的默认配置项 │   ├── Kconfig.liteos_m.defconfig.board --- 提供v200zr单板的默认配置项
│   └── liteos_m │   └── liteos_m
│   └── config.gni │   └── config.gni
├── Kconfig.liteos_m.boards --- 提供fnlink单板厂商下Boards配置信息 ├── Kconfig.liteos_m.boards --- 提供fnlink单板厂商下Boards配置信息
├── Kconfig.liteos_m.defconfig.boards --- 提供fnlink单板厂商下Boards默认配置信息 ├── Kconfig.liteos_m.defconfig.boards --- 提供fnlink单板厂商下Boards默认配置信息
├── Kconfig.liteos_m.shields --- 提供fnlink单板厂商下扩展板配置信息 ├── Kconfig.liteos_m.shields --- 提供fnlink单板厂商下扩展板配置信息
└── shields --- fnlink单板厂商的扩展板目录 └── shields --- fnlink单板厂商的扩展板目录
├── v200zr-t0 --- fnlink单板厂商的扩展板v200zr-t0 ├── v200zr-t0 --- fnlink单板厂商的扩展板v200zr-t0
│   ├── Kconfig.liteos_m.defconfig.shield --- 扩展板v200zr-t0默认配置 │   ├── Kconfig.liteos_m.defconfig.shield --- 扩展板v200zr-t0默认配置
│   └── Kconfig.liteos_m.shield --- 扩展板v200zr-t0配置信息 │   └── Kconfig.liteos_m.shield --- 扩展板v200zr-t0配置信息
├── v200zr-t1 ├── v200zr-t1
│   ├── Kconfig.liteos_m.defconfig.shield │   ├── Kconfig.liteos_m.defconfig.shield
│   └── Kconfig.liteos_m.shield │   └── Kconfig.liteos_m.shield
...@@ -166,7 +165,7 @@ orsource "../../device/soc/*/Kconfig.liteos_m.soc" ...@@ -166,7 +165,7 @@ orsource "../../device/soc/*/Kconfig.liteos_m.soc"
``` ```
config BOARD_v200zr config BOARD_v200zr
bool "select 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"` ,如下: `v200zr/Kconfig.liteos_m.defconfig.board`需要配置选择该单板后,默认定义 `BOARD` 的名字为 `"v200zr"` ,如下:
...@@ -174,7 +173,7 @@ config BOARD_v200zr ...@@ -174,7 +173,7 @@ config BOARD_v200zr
``` ```
if BOARD_v200zr if BOARD_v200zr
config BOARD config BOARD
string --- string后没有带提示,因此用户不可见 string --- string后没有带提示,因此用户不可见
default "v200zr" default "v200zr"
endif # BOARD_v200zr endif # BOARD_v200zr
...@@ -184,24 +183,24 @@ endif # BOARD_v200zr ...@@ -184,24 +183,24 @@ endif # BOARD_v200zr
``` ```
. .
├── bes2600 --- bes2600 SoC系列 ├── bes2600 --- bes2600 SoC系列
│   ├── Kconfig.liteos_m.defconfig.bes2600w --- bestechnic芯片厂商bes2600w SoC Series配置 │   ├── Kconfig.liteos_m.defconfig.bes2600w --- bestechnic芯片厂商bes2600w SoC Series配置
│   ├── Kconfig.liteos_m.defconfig.series --- bestechnic芯片厂商bes2600默认配置 │   ├── Kconfig.liteos_m.defconfig.series --- bestechnic芯片厂商bes2600默认配置
│   ├── Kconfig.liteos_m.series --- bestechnic芯片厂商bes2600 SoC Series配置 │   ├── Kconfig.liteos_m.series --- bestechnic芯片厂商bes2600 SoC Series配置
│   └── Kconfig.liteos_m.soc --- bestechnic芯片厂商bes2600 SoC配置 │   └── Kconfig.liteos_m.soc --- bestechnic芯片厂商bes2600 SoC配置
├── Kconfig.liteos_m.defconfig --- bestechnic芯片厂商SoC默认配置 ├── Kconfig.liteos_m.defconfig --- bestechnic芯片厂商SoC默认配置
├── Kconfig.liteos_m.series --- bestechnic芯片厂商SoC Series配置 ├── Kconfig.liteos_m.series --- bestechnic芯片厂商SoC Series配置
└── Kconfig.liteos_m.soc --- bestechnic芯片厂商 SoC配置 └── Kconfig.liteos_m.soc --- bestechnic芯片厂商 SoC配置
``` ```
`bes2600/Kconfig.liteos_m.series` 需要配置`bes2600 SoC series`,以及它的芯片架构等信息,如下: `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" bool "Bestechnic 2600 Series"
select ARM --- 选择bes2600后,默认选择ARM架构 select ARM --- 选择bes2600后,默认选择ARM架构
select SOC_COMPANY_BESTECHNIC --- 选择bes2600后,默认选择bestechnic芯片公司,驱动会依赖这个宏配置,选择配置编译对应厂商的驱动 select SOC_COMPANY_BESTECHNIC --- 选择bes2600后,默认选择bestechnic芯片公司,驱动会依赖这个宏配置,选择配置编译对应厂商的驱动
select CPU_CORTEX_M33 --- 选择bes2600后,默认选择cortex-m33 CPU select CPU_CORTEX_M33 --- 选择bes2600后,默认选择cortex-m33 CPU
help help
Enable support for Bestechnic 2600 series Enable support for Bestechnic 2600 series
``` ```
...@@ -211,9 +210,9 @@ config SOC_SERIES_BES2600 --- 提供bes2600 SoC Series选项 ...@@ -211,9 +210,9 @@ config SOC_SERIES_BES2600 --- 提供bes2600 SoC Series选项
``` ```
choice choice
prompt "Bestechnic 2600 series SoC" 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" bool "SoC BES2600w"
endchoice endchoice
...@@ -222,11 +221,11 @@ endchoice ...@@ -222,11 +221,11 @@ endchoice
`bes2600/Kconfig.liteos_m.defconfig.series` 需要提供`bes2600 SoC series`选择后的默认配置,如下: `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 string
default "bes2600" default "bes2600"
...@@ -242,7 +241,7 @@ endif ...@@ -242,7 +241,7 @@ endif
ifeq ($(RELEASE:1=y),y) ifeq ($(RELEASE:1=y),y)
CONFIG ?= $(PRODUCT_PATH)/kernel_configs/release$(tee).config CONFIG ?= $(PRODUCT_PATH)/kernel_configs/release$(tee).config
else else
CONFIG ?= $(PRODUCT_PATH)/kernel_configs/debug$(tee).config --- 配置文件保存在$(CONFIG)中,由产品最终定义 CONFIG ?= $(PRODUCT_PATH)/kernel_configs/debug$(tee).config --- 配置文件保存在$(CONFIG)中,由产品最终定义
endif endif
…… ……
...@@ -281,11 +280,11 @@ deps += [ "//device/soc/$LOSCFG_SOC_COMPANY" ] ...@@ -281,11 +280,11 @@ deps += [ "//device/soc/$LOSCFG_SOC_COMPANY" ]
`//device/board/fnlink/BUILD.gn`中,新增内容如下: `//device/board/fnlink/BUILD.gn`中,新增内容如下:
``` ```
if (ohos_kernel_type == "liteos_m") { --- 由于多内核设计,对于LiteOS-M内核适配,需要用宏来隔离 if (ohos_kernel_type == "liteos_m") { --- 由于多内核设计,对于LiteOS-M内核适配,需要用宏来隔离
import("//kernel/liteos_m/liteos.gni") --- 引入内核gn编写模板 import("//kernel/liteos_m/liteos.gni") --- 引入内核gn编写模板
module_name = get_path_info(rebase_path("."), "name") --- 动态获取当前文件目录作为模块名,防止目录名修改后,这里还需要跟着修改 module_name = get_path_info(rebase_path("."), "name") --- 动态获取当前文件目录作为模块名,防止目录名修改后,这里还需要跟着修改
module_group(module_name) { --- 采用module_group模板 module_group(module_name) { --- 采用module_group模板
modules = [ --- 添加需要编译的模块 modules = [ --- 添加需要编译的模块
] ]
} }
} }
...@@ -312,9 +311,9 @@ if (ohos_kernel_type == "liteos_m") { ...@@ -312,9 +311,9 @@ if (ohos_kernel_type == "liteos_m") {
... ...
if(!ret) { if(!ret) {
... ...
OhosSystemAdapterHooks(); --- 系统启动时候设置钩子,启动OpenHarmonyOHOS_SystemInit的之前完成打印和驱动的初始化 OhosSystemAdapterHooks(); --- 系统启动时候设置钩子,启动OpenHarmonyOHOS_SystemInit的之前完成打印和驱动的初始化
... ...
OHOS_SystemInit(); --- 启动OpenHarmony服务,以及组件初始化 OHOS_SystemInit(); --- 启动OpenHarmony服务,以及组件初始化
} }
.... ....
``` ```
...@@ -324,8 +323,8 @@ if (ohos_kernel_type == "liteos_m") { ...@@ -324,8 +323,8 @@ if (ohos_kernel_type == "liteos_m") {
``` ```
int OhosSystemAdapterHooks(void) int OhosSystemAdapterHooks(void)
{ {
init_trace_system(); --- 初始化打印函数 init_trace_system(); --- 初始化打印函数
DeviceManagerStart(); --- 调用DeviceManagerStart函数进行HDF驱动初始化,这个过程会调用单板代码中的驱动配置文件hdf.hcs以及drivers源码实现 DeviceManagerStart(); --- 调用DeviceManagerStart函数进行HDF驱动初始化,这个过程会调用单板代码中的驱动配置文件hdf.hcs以及drivers源码实现
return 0; return 0;
} }
...@@ -338,7 +337,7 @@ int OhosSystemAdapterHooks(void) ...@@ -338,7 +337,7 @@ int OhosSystemAdapterHooks(void)
1. 配置指定目录放置打包文件系统`config.json`,通过`flash_partition_dir`指定目录: 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`下放置两部分内容: 2. 在指定目录`vendor/bestechnic/display_demo/fs`下放置两部分内容:
...@@ -532,7 +531,7 @@ struct HdfDriverEntry g_GpioDriverEntry = { ...@@ -532,7 +531,7 @@ struct HdfDriverEntry g_GpioDriverEntry = {
.Init = GpioDriverInit, .Init = GpioDriverInit,
.Release = GpioDriverRelease, .Release = GpioDriverRelease,
}; };
HDF_INIT(g_GpioDriverEntry); --- 通过HDF_INIT 加载GPIO驱动 HDF_INIT(g_GpioDriverEntry); --- 通过HDF_INIT 加载GPIO驱动
``` ```
然后,在初始化的时候会获取`hcs`参数进行初始化,如下: 然后,在初始化的时候会获取`hcs`参数进行初始化,如下:
...@@ -548,7 +547,7 @@ static int32_t GpioDriverInit(struct HdfDeviceObject *device) ...@@ -548,7 +547,7 @@ static int32_t GpioDriverInit(struct HdfDeviceObject *device)
return HDF_ERR_INVALID_PARAM; return HDF_ERR_INVALID_PARAM;
} }
gpioCntlr = GpioCntlrFromDevice(device); --- gpioCntlr节点变量就可以获取具体gpio配置 gpioCntlr = GpioCntlrFromDevice(device); --- gpioCntlr节点变量就可以获取具体gpio配置
if (gpioCntlr == NULL) { if (gpioCntlr == NULL) {
... ...
``` ```
...@@ -640,7 +639,7 @@ static int32_t PanelDriverInit(struct HdfDeviceObject *object) ...@@ -640,7 +639,7 @@ static int32_t PanelDriverInit(struct HdfDeviceObject *object)
"component": "wifi_lite", "component": "wifi_lite",
…… ……
"targets": [ "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) ...@@ -651,7 +650,7 @@ static int32_t PanelDriverInit(struct HdfDeviceObject *object)
``` ```
config("include") { config("include") {
include_dirs = [ "interfaces/wifiservice" ] --- 因为wifi_lite只提供头文件,不提供wifi的具体实现,所以wifi模块暴露出适配的目录路径提供给硬件厂商来适配,厂商提供wifi协议栈源码实现。 include_dirs = [ "interfaces/wifiservice" ] --- 因为wifi_lite只提供头文件,不提供wifi的具体实现,所以wifi模块暴露出适配的目录路径提供给硬件厂商来适配,厂商提供wifi协议栈源码实现。
} }
group("wifi") { group("wifi") {
...@@ -663,7 +662,7 @@ 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; WifiErrorCode ret = ERROR_WIFI_BUSY;
...@@ -682,7 +681,7 @@ WifiErrorCode Scan(void) --- wifi_device.c中扫描wifi热点的函数 ...@@ -682,7 +681,7 @@ WifiErrorCode Scan(void) --- wifi_device.c中扫描wifi热点的函数
return ret; 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 (band == HOTSPOT_BAND_TYPE_2G) {
if (rssi >= RSSI_LEVEL_4_2_G) if (rssi >= RSSI_LEVEL_4_2_G)
...@@ -757,11 +756,11 @@ config("public") { ...@@ -757,11 +756,11 @@ config("public") {
#ifndef _PORTING_LWIPOPTS_H_ #ifndef _PORTING_LWIPOPTS_H_
#define _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_NETIF_STATUS_CALLBACK 1
#define LWIP_CHECKSUM_ON_COPY 0 #define LWIP_CHECKSUM_ON_COPY 0
#define CHECKSUM_GEN_UDP 0 --- 新增硬件适配选项 #define CHECKSUM_GEN_UDP 0 --- 新增硬件适配选项
#endif /* _PORTING_LWIPOPTS_H_ */ #endif /* _PORTING_LWIPOPTS_H_ */
...@@ -802,10 +801,10 @@ ethernetif_init(struct netif *netif) ...@@ -802,10 +801,10 @@ ethernetif_init(struct netif *netif)
"subsystem": "startup", "subsystem": "startup",
"components": [ "components": [
{ {
"component": "bootstrap_lite" --- bootstrap_lite 部件 "component": "bootstrap_lite" --- bootstrap_lite 部件
}, },
{ {
"component": "syspara_lite", --- syspara_lite 部件 "component": "syspara_lite", --- syspara_lite 部件
"features": [ "features": [
"enable_ohos_startup_syspara_lite_use_posix_file_api = true" "enable_ohos_startup_syspara_lite_use_posix_file_api = true"
] ]
...@@ -915,7 +914,7 @@ ethernetif_init(struct netif *netif) ...@@ -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) static void Init(void)
...@@ -928,7 +927,7 @@ static void Init(void) ...@@ -928,7 +927,7 @@ static void Init(void)
bootstrap.flag = FALSE; bootstrap.flag = FALSE;
SAMGR_GetInstance()->RegisterService((Service *)&bootstrap); 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`,如下: ​ 在`//base/startup/bootstrap_lite/services/source/BUILD.gn`文件中,描述了在`out/v200zr/display_demo/libs` 生成 `libbootstrap.a`,如下:
...@@ -953,7 +952,7 @@ static_library("bootstrap") { ...@@ -953,7 +952,7 @@ static_library("bootstrap") {
"burn_name": "rtos_main", "burn_name": "rtos_main",
"enable": "true", "enable": "true",
"force_link_libs": [ "force_link_libs": [
"bootstrap", --- 强制链接libbootstrap.a "bootstrap", --- 强制链接libbootstrap.a
... ...
] ]
}, },
...@@ -981,15 +980,15 @@ static_library("bootstrap") { ...@@ -981,15 +980,15 @@ static_library("bootstrap") {
typedef unsigned char u8; 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) static char Hex2Char(u8 hex)
{ {
if (hex < HEX_A) { if (hex < HEX_A) {
return hex + CHAR_NUM_OFFSET; --- 将数值0转为char的'0' return hex + CHAR_NUM_OFFSET; --- 将数值0转为char的'0'
} else { } 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) ...@@ -998,9 +997,9 @@ const char* HalGetSerial(void)
char macAddr[ETH_ALEN]; char macAddr[ETH_ALEN];
// as devboard has no production serial number, we just // as devboard has no production serial number, we just
// use wifi mac address as device serial number. // 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); extern int bwifi_get_own_mac(u8 *addr);
bwifi_get_own_mac(macAddr); --- 获取mac地址 bwifi_get_own_mac(macAddr); --- 获取mac地址
int j = 0; int j = 0;
for (int i = 0; i < ETH_ALEN; i++) { for (int i = 0; i < ETH_ALEN; i++) {
u8 lowFour, highFour; u8 lowFour, highFour;
...@@ -1010,7 +1009,7 @@ const char* HalGetSerial(void) ...@@ -1010,7 +1009,7 @@ const char* HalGetSerial(void)
lowFour = macAddr[i] & MAC_LOW_MASK; lowFour = macAddr[i] & MAC_LOW_MASK;
serialNumber[j] = Hex2Char(lowFour); serialNumber[j] = Hex2Char(lowFour);
j++; j++;
} --- 将mac地址值转化为serial number } --- 将mac地址值转化为serial number
} }
return serialNumber; return serialNumber;
} }
...@@ -1042,10 +1041,7 @@ boolean HilogProc_Impl(const HiLogContent *hilogContent, uint32 len) ...@@ -1042,10 +1041,7 @@ boolean HilogProc_Impl(const HiLogContent *hilogContent, uint32 len)
char tempOutStr[LOG_FMT_MAX_LEN] = {0}; char tempOutStr[LOG_FMT_MAX_LEN] = {0};
if (LogContentFmt(tempOutStr, sizeof(tempOutStr), hilogContent) > 0) { if (LogContentFmt(tempOutStr, sizeof(tempOutStr), hilogContent) > 0) {
printf(tempOutStr); printf(tempOutStr);
#ifdef LOG_FLUSH }
hHiviewRegisterHilogProc(HilogProc_Impl);al_trace_flush_buffer();
#endif
}
return TRUE; return TRUE;
} }
...@@ -1149,9 +1145,9 @@ giflib + libjpeg + libpng + qrcodegen + freetype... (图形第三方库) ...@@ -1149,9 +1145,9 @@ giflib + libjpeg + libpng + qrcodegen + freetype... (图形第三方库)
void RunApp() void RunApp()
{ {
#ifdef UI_TEST #ifdef UI_TEST
AnimatorDemoStart(); --- native ui demo AnimatorDemoStart(); --- native ui demo
#elif defined(ABILITY_TEST) #elif defined(ABILITY_TEST)
StartJSApp(); --- js demo StartJSApp(); --- js demo
#endif #endif
} }
...@@ -1208,8 +1204,8 @@ APP_FEATURE_INIT(AppEntry); ...@@ -1208,8 +1204,8 @@ APP_FEATURE_INIT(AppEntry);
{ {
"component": "aafwk_lite", "component": "aafwk_lite",
"features": [ "features": [
"enable_ohos_appexecfwk_feature_ability = true", --- 支持FA特性,即包含图形能力 "enable_ohos_appexecfwk_feature_ability = true", --- 支持FA特性,即包含图形能力
"config_ohos_aafwk_ams_task_size = 4096" --- 配置ams栈的大小 "config_ohos_aafwk_ams_task_size = 4096" --- 配置ams栈的大小
] ]
} }
] ]
...@@ -1242,11 +1238,11 @@ APP_FEATURE_INIT(AppEntry); ...@@ -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`测试参考资料见[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", "subsystem": "xts",
......
...@@ -21,40 +21,14 @@ ...@@ -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)上。开发者可以通过该镜像在很大程度上简化编译前的环境配置。下文将介绍具体使用步骤。 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镜像。 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构建环境。 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
```
...@@ -38,8 +38,6 @@ bash build/prebuilts_download.sh ...@@ -38,8 +38,6 @@ bash build/prebuilts_download.sh
### 获取Docker环境<a name="section615912103552"></a> ### 获取Docker环境<a name="section615912103552"></a>
**方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:**
1. 获取Docker镜像。 1. 获取Docker镜像。
``` ```
...@@ -53,28 +51,6 @@ bash build/prebuilts_download.sh ...@@ -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
```
## 使用安装包方式获取编译工具链<a name="section65647482593"></a> ## 使用安装包方式获取编译工具链<a name="section65647482593"></a>
### 安装依赖工具<a name="section83441888010"></a> ### 安装依赖工具<a name="section83441888010"></a>
......
...@@ -38,8 +38,6 @@ bash build/prebuilts_download.sh ...@@ -38,8 +38,6 @@ bash build/prebuilts_download.sh
### 获取Docker环境<a name="section615912103552"></a> ### 获取Docker环境<a name="section615912103552"></a>
**方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:**
1. 获取Docker镜像。 1. 获取Docker镜像。
``` ```
...@@ -53,28 +51,6 @@ bash build/prebuilts_download.sh ...@@ -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
```
## 使用安装包方式获取编译工具链<a name="section65647482593"></a> ## 使用安装包方式获取编译工具链<a name="section65647482593"></a>
### 安装依赖工具<a name="section83441888010"></a> ### 安装依赖工具<a name="section83441888010"></a>
......
# HiSysEvent订阅指导<a name="ZH-CN_TOPIC_0000001185655868"></a> # HiSysEvent订阅指导<a name="ZH-CN_TOPIC_0000001185655868"></a>
- [概述](#section315316685112) - [概述](#section315316685112)
- [接口说明](#section0342191810519) - [功能简介](#section123181433335224)
- [开发实例](#section123181432175110) - [约束与限制](#section123181433375224)
- [C++接口实例](#section2016116181902) - [开发指导](#section315316685113)
- [接口说明](#section0342191810519)
- [开发实例](#section123181432175110)
## 概述<a name="section315316685112"></a> ## 概述<a name="section315316685112"></a>
### 功能简介<a name="section123181433335224"></a>
HiSysEvent提供了跨进程订阅机制,开发者可以通过注册订阅接口实时获取关注的事件,例如电池模块侦听功耗相关的事件,用于分析耗电情况。 HiSysEvent提供了跨进程订阅机制,开发者可以通过注册订阅接口实时获取关注的事件,例如电池模块侦听功耗相关的事件,用于分析耗电情况。
## 接口说明<a name="section0342191810519"></a> ### 约束与限制<a name="section123181433375224"></a>
**HiSysEvent事件订阅条件约束:**
- 在订阅HiSysEvent事件之前,需要先完成HiSysEvent打点配置,具体配置方法请参考[《HiSysEvent打点配置指导》](subsys-dfx-hisysevent-write-config.md)
## 开发指导<a name="section315316685113"></a>
### 接口说明<a name="section0342191810519"></a>
**表 1** HiSysEvent订阅接口 **表 1** HiSysEvent订阅接口
<a name="table1844019587496"></a> <a name="table1844019587496"></a>
<table><thead align="left"><tr id="row1440058184916"><th class="cellrowborder" valign="top" width="48.120000000000005%" id="mcps1.2.3.1.1"><p id="p19441135844915"><a name="p19441135844915"></a><a name="p19441135844915"></a>接口名</p> <table><thead align="left"><tr id="row1440058184916"><th class="cellrowborder" valign="top" id="mcps1.2.3.1.1"><p id="p19441135844915"><a name="p19441135844915"></a><a name="p19441135844915"></a>接口名称</p>
</th> </th>
<th class="cellrowborder" valign="top" width="51.88%" id="mcps1.2.3.1.2"><p id="p13441195815491"><a name="p13441195815491"></a><a name="p13441195815491"></a>描述</p> <th class="cellrowborder" valign="top" id="mcps1.2.3.1.2"><p id="p13441195815491"><a name="p13441195815491"></a><a name="p13441195815491"></a>描述</p>
</th> </th>
</tr> </tr>
</thead> </thead>
<tbody><tr id="row16441155818499"><td class="cellrowborder" valign="top" width="48.120000000000005%" headers="mcps1.2.3.1.1 "><p id="p877916438211"><a name="p877916438211"></a><a name="p877916438211"></a>int HiSysEventManager::AddEventListener(std::shared_ptr&lt;HiSysEventSubscribeCallBackBase&gt; listener, std::vector&lt;struct ListenerRule&gt;&amp; rules)</p> <tbody><tr id="row16441155818499"><td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 "><p id="p877916438211"><a name="p877916438211"></a><a name="p877916438211"></a>int HiSysEventManager::AddEventListener(std::shared_ptr&lt;HiSysEventSubscribeCallBackBase&gt; listener, std::vector&lt;ListenerRule&gt;&amp; rules)</p>
</td> </td>
<td class="cellrowborder" valign="top" width="51.88%" headers="mcps1.2.3.1.2 "><p id="p14727325133216"><a name="p14727325133216"></a><a name="p14727325133216"></a>接口功能:注册订阅HiSysEvent系统事件侦听对象,可设置规则订阅某些事件。</p> <td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 "><p id="p14727325133216"><a name="p14727325133216"></a><a name="p14727325133216"></a>接口功能:<br>&emsp;&emsp;注册订阅HiSysEvent系统事件侦听对象,可设置规则订阅某些事件。</p>
<p id="p167271525203213"><a name="p167271525203213"></a><a name="p167271525203213"></a>输入参数:</p> <p id="p167271525203213"><a name="p167271525203213"></a><a name="p167271525203213"></a>输入参数:</p>
<a name="ul6717142214919"></a><a name="ul6717142214919"></a><ul id="ul6717142214919"><li>listener:订阅回调对象。</li><li>rules:事件订阅规则。</li></ul> <a name="ul6717142214919"></a><a name="ul6717142214919"></a><ul id="ul6717142214919"><li>listener:订阅回调对象。</li><li>rules:事件订阅规则。</li></ul>
<p id="p83591223153818"><a name="p83591223153818"></a><a name="p83591223153818"></a>返回值:</p> <p id="p83591223153818"><a name="p83591223153818"></a><a name="p83591223153818"></a>返回值:</p>
<a name="ul12105842111913"></a><a name="ul12105842111913"></a><ul id="ul12105842111913"><li>0:订阅成功,重复订阅。</li><li>1:订阅成功,初次订阅。</li><li>其他返回值:订阅失败。</li></ul> <a name="ul12105842111913"></a><a name="ul12105842111913"></a><ul id="ul12105842111913"><li>0:订阅成功,重复订阅。</li><li>1:订阅成功,初次订阅。</li><li>其他返回值:订阅失败。</li></ul>
</td> </td>
</tr> </tr>
<tr id="row910319443242"><td class="cellrowborder" valign="top" width="48.120000000000005%" headers="mcps1.2.3.1.1 "><p id="p15104154411248"><a name="p15104154411248"></a><a name="p15104154411248"></a>void HiSysEventManager::RemoveListener(std::shared_ptr&lt;HiSysEventSubscribeCallBackBase&gt; listener)</p> <tr id="row910319443242"><td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 "><p id="p15104154411248"><a name="p15104154411248"></a><a name="p15104154411248"></a>void HiSysEventManager::RemoveListener(std::shared_ptr&lt;HiSysEventSubscribeCallBackBase&gt; listener)</p>
</td> </td>
<td class="cellrowborder" valign="top" width="51.88%" headers="mcps1.2.3.1.2 "><p id="p1104194420248"><a name="p1104194420248"></a><a name="p1104194420248"></a>接口功能:移除订阅hisysevent系统事件侦听对象。</p> <td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 "><p id="p1104194420248"><a name="p1104194420248"></a><a name="p1104194420248"></a>接口功能:<br>&emsp;&emsp;移除订阅hisysevent系统事件侦听对象。</p>
<p id="p7943171095411"><a name="p7943171095411"></a><a name="p7943171095411"></a>输入参数:</p> <p id="p7943171095411"><a name="p7943171095411"></a><a name="p7943171095411"></a>输入参数:</p>
<a name="ul894321075411"></a><a name="ul894321075411"></a><ul id="ul894321075411"><li>listener:订阅回调对象。</li></ul> <a name="ul894321075411"></a><a name="ul894321075411"></a><ul id="ul894321075411"><li>listener:订阅回调对象。</li></ul>
<p id="p9744631162515"><a name="p9744631162515"></a><a name="p9744631162515"></a>返回值:无。</p> <p id="p9744631162515"><a name="p9744631162515"></a><a name="p9744631162515"></a>返回值:<br>&emsp;&emsp;无。</p>
</td> </td>
</tr> </tr>
</tbody> </tbody>
...@@ -43,110 +54,144 @@ HiSysEvent提供了跨进程订阅机制,开发者可以通过注册订阅接 ...@@ -43,110 +54,144 @@ HiSysEvent提供了跨进程订阅机制,开发者可以通过注册订阅接
**表 2** ListenerRule订阅规则对象 **表 2** ListenerRule订阅规则对象
<a name="table1144011610564"></a> <a name="table1844019587498"></a>
<table><thead align="left"><tr id="row124411716175611"><th class="cellrowborder" valign="top" width="48.11%" id="mcps1.2.3.1.1"><p id="p19441151675610"><a name="p19441151675610"></a><a name="p19441151675610"></a>属性名称</p> <table><thead align="left"><tr id="row1440058184918"><th class="cellrowborder" valign="top" id="mcps1.2.3.1.1"><p id="p19441135844917"><a name="p19441135844917"></a><a name="p19441135844917"></a>接口名称</p>
</th> </th>
<th class="cellrowborder" valign="top" width="51.89%" id="mcps1.2.3.1.2"><p id="p16441171616563"><a name="p16441171616563"></a><a name="p16441171616563"></a>描述</p> <th class="cellrowborder" valign="top" id="mcps1.2.3.1.2"><p id="p13441195815493"><a name="p13441195815493"></a><a name="p13441195815493"></a>描述</p>
</th> </th>
</tr> </tr>
</thead> </thead>
<tbody><tr id="row174411216105615"><td class="cellrowborder" valign="top" width="48.11%" headers="mcps1.2.3.1.1 "><p id="p496413536613"><a name="p496413536613"></a><a name="p496413536613"></a><span>uint32_t</span> ruleType</p> <tbody><tr id="row16441155818499"><td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 "><p id="p877916438213"><a name="p877916438213"></a><a name="p877916438213"></a>ListenerRule(const std::string&amp; tag, RuleType ruleType = RuleType::WHOLE_WORD) </p>
</td> </td>
<td class="cellrowborder" valign="top" width="51.89%" headers="mcps1.2.3.1.2 "><p id="p94416160565"><a name="p94416160565"></a><a name="p94416160565"></a>规则类型(匹配范围包括domain以及eventName):</p> <td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 "><p id="p14727325133218"><a name="p14727325133218"></a><a name="p14727325133218"></a>接口功能:<br>&emsp;&emsp;订阅规则构造函数,创建事件标签订阅规则对象。</p>
<a name="ul1652866141814"></a><a name="ul1652866141814"></a><ul id="ul1652866141814"><li>1:全字符匹配。</li><li>2:前缀匹配。</li><li>3:正则表达式匹配。</li><li>其他值:无效的匹配方式。</li></ul> <p id="p167271525203215"><a name="p167271525203215"></a><a name="p167271525203215"></a>输入参数:</p>
<a name="ul6717142214921"></a><a name="ul6717142214921"></a><ul id="ul6717142214921">
<li>tag:订阅规则的HisysEvent事件标签,字符串类型,最大长度16个字符(含),有效字符包含大小写字母及数字。</li>
<li>ruleType:订阅规则的规则类型,RuleType枚举类型(参考表3)。</li></ul>
</td> </td>
</tr> </tr>
<tr id="row64411816125614"><td class="cellrowborder" valign="top" width="48.11%" headers="mcps1.2.3.1.1 "><p id="p1258135313712"><a name="p1258135313712"></a><a name="p1258135313712"></a>std::string domain</p> <tr id="row910319443244"><td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 "><p id="p15104154411250"><a name="p15104154411250"></a><a name="p15104154411250"></a>ListenerRule(const std::string&amp; domain, const std::string&amp; eventName, RuleType ruleType = RuleType::WHOLE_WORD)</p>
</td> </td>
<td class="cellrowborder" valign="top" width="51.89%" headers="mcps1.2.3.1.2 "><a name="ul14905926102311"></a><a name="ul14905926102311"></a><ul id="ul14905926102311"><li>domain:事件所属领域,如果传入的是空字符串,则默认事件领域字段匹配成功。</li></ul> <td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 "><p id="p15104154411250"><a name="p15104154411250"></a><a name="p15104154411250"></a>接口功能:<br>&emsp;&emsp;订阅规则构造函数,创建事件领域与事件名称订阅规则对象。</p>
<p id="p7943171095413"><a name="p7943171095413"></a><a name="p7943171095413"></a>输入参数:</p>
<a name="ul894321075413"></a><a name="ul894321075413"></a><ul id="ul894321075413">
<li>domain:订阅规则的HisysEvent事件领域,字符串类型,最大长度16个字符(含),有效字符包含大写字母、数字及下划线。</li>
<li>eventName:订阅规则的HisysEvent事件名称,字符串类型,最大长度32个字符(含),有效字符包含大写字母、数字及下划线。</li>
<li>ruleType:订阅规则的规则类型,RuleType枚举类型(参考表3)。</li></ul>
</td> </td>
</tr> </tr>
<tr id="row244161615619"><td class="cellrowborder" valign="top" width="48.11%" headers="mcps1.2.3.1.1 "><p id="p227913101887"><a name="p227913101887"></a><a name="p227913101887"></a>std::string eventName</p> <tr id="row910319443246"><td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 "><p id="p15104154411252"><a name="p15104154411252"></a><a name="p15104154411252"></a>ListenerRule(const std::string&amp; domain, const std::string& eventName, const std::string&amp; tag, RuleType ruleType = RuleType::WHOLE_WORD)</p>
</td> </td>
<td class="cellrowborder" valign="top" width="51.89%" headers="mcps1.2.3.1.2 "><a name="ul248063132319"></a><a name="ul248063132319"></a><ul id="ul248063132319"><li>eventName:事件的名称,如果传入的是空字符串,则默认事件名称字段匹配成功。</li></ul> <td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 "><p id="p15104154411252"><a name="p15104154411252"></a><a name="p15104154411252"></a>接口功能:<br>&emsp;&emsp;订阅规则构造函数,创建事件领域、事件名称,事件标签订阅规则对象。</p>
<p id="p7943171095415"><a name="p7943171095415"></a><a name="p7943171095415"></a>输入参数:</p>
<a name="ul894321075415"></a><a name="ul894321075415"></a><ul id="ul894321075415">
<li>tag:订阅规则的HisysEvent事件标签,字符串类型,最大长度16个字符(含),有效字符包含大小写字母及数字。</li>
<li>domain:订阅规则的HisysEvent事件领域,字符串类型,最大长度16个字符(含),有效字符包含大写字母、数字及下划线。</li>
<li>eventName:订阅规则的HisysEvent事件名称,字符串类型,最大长度32个字符(含),有效字符包含大写字母、数字及下划线。</li>
<li>ruleType:订阅规则的规则类型,RuleType枚举类型(参考表3)。</li></ul></ul>
</td> </td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
**表 3** HiSysEventSubscribeCallBackBase订阅对象 **表 3** RuleType类型
| 枚举值 | 描述 |
| ------------ | ------------- |
| WHOLE_WORD | 全词匹配类型 |
| PREFIX | 前缀匹配类型 |
| REGULAR | 正则匹配类型 |
**表 4** HiSysEventSubscribeCallBackBase订阅对象
<a name="table1011703742711"></a> <a name="table1011703742711"></a>
<table><thead align="left"><tr id="row121187375270"><th class="cellrowborder" valign="top" width="48.25%" id="mcps1.2.3.1.1"><p id="p2118143782719"><a name="p2118143782719"></a><a name="p2118143782719"></a>接口名称</p>
<table><thead align="left"><tr id="row121187375270"><th class="cellrowborder" valign="top" id="mcps1.2.3.1.1"><p id="p2118143782719"><a name="p2118143782719"></a><a name="p2118143782719"></a>接口名称</p>
</th> </th>
<th class="cellrowborder" valign="top" width="51.74999999999999%" id="mcps1.2.3.1.2"><p id="p4118037152710"><a name="p4118037152710"></a><a name="p4118037152710"></a>描述</p> <th class="cellrowborder" valign="top" id="mcps1.2.3.1.2"><p id="p4118037152710"><a name="p4118037152710"></a><a name="p4118037152710"></a>描述</p>
</th> </th>
</tr> </tr>
</thead> </thead>
<tbody><tr id="row111823719274"><td class="cellrowborder" valign="top" width="48.25%" headers="mcps1.2.3.1.1 "><p id="p161181537112712"><a name="p161181537112712"></a><a name="p161181537112712"></a>void HiSysEventSubscribeCallBackBase::OnHandle(const std::string&amp; domain, const std::string&amp; eventName, const int eventType, const std::string&amp; eventDetail)</p> <tbody><tr id="row111823719274"><td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 "><p id="p161181537112712"><a name="p161181537112712"></a><a name="p161181537112712"></a>void HiSysEventSubscribeCallBackBase::OnHandle(const std::string&amp; domain, const std::string&amp; eventName, const int eventType, const std::string&amp; eventDetail)</p>
</td> </td>
<td class="cellrowborder" valign="top" width="51.74999999999999%" headers="mcps1.2.3.1.2 "><p id="p1772213111011"><a name="p1772213111011"></a><a name="p1772213111011"></a>接口功能:订阅事件的回调接口。</p> <td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 "><p id="p1772213111011"><a name="p1772213111011"></a><a name="p1772213111011"></a>接口功能:<br>&emsp;&emsp;订阅事件的回调接口。</p>
<p id="p182081719151016"><a name="p182081719151016"></a><a name="p182081719151016"></a>输入参数:</p> <p id="p182081719151016"><a name="p182081719151016"></a><a name="p182081719151016"></a>输入参数:</p>
<a name="ul02091819131015"></a><a name="ul02091819131015"></a><ul id="ul02091819131015"><li>domain:事件所属领域。</li><li>eventName:事件的名称。</li><li>eventType:事件类型。</li><li>eventDetail:包含事件相关信息的字符串,以json的形式体现。</li></ul> <a name="ul02091819131015"></a><a name="ul02091819131015"></a><ul id="ul02091819131015"><li>domain:事件所属领域。</li><li>eventName:事件的名称。</li><li>eventType:事件类型。</li><li>eventDetail:包含事件相关信息的字符串,以json的形式体现。</li></ul>
<p id="p18209419201010"><a name="p18209419201010"></a><a name="p18209419201010"></a>返回值:无。</p> <p id="p18209419201010"><a name="p18209419201010"></a><a name="p18209419201010"></a>返回值:<br>&emsp;&emsp;无。</p>
</td> </td>
</tr> </tr>
</tbody> </tbody>
</table> </table>
## 开发实例<a name="section123181432175110"></a> ### 开发实例<a name="section123181432175110"></a>
### C++接口实例<a name="section2016116181902"></a> 订阅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 <string>
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<HiSysEventSubscribeCallBackBase\> listener, std::vector<struct ListenerRule\>& rules\)。 ```
#include "demo_listener.h"
#include <iostream>
``` void DemoListener::OnHandle(const std::string& domain, const std::string& eventName,
// 以下是订阅domain=HIVIEWDFX的所有系统事件的应用例子 const int eventType, const std::string& eventDetail)
#include "hisysevent_manager.h" {
#include <iostream> std::cout << eventDetail << std::endl;
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<HiSysEventToolListener>();
struct ListenerRule rule;
rule.ruleType = 1; // 1: default type
rule.domain = "HIVIEWDFX";
std::vector<struct ListenerRule> sysRules;
sysRules.push_back(rule);
HiSysEventManager::AddEventListener(toolListener, sysRules);
```
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<DemoListener>();
``` // 事件标签规则订阅,规则类型为默认的全词匹配类型
ListenerRule tagRule("dfx");
// 事件标签规则订阅,规则类型为正则匹配类型
ListenerRule regRule("dfx.*", RuleType::REGULAR);
// 事件领域及事件名称规则订阅,规则类型为前缀匹配类型
ListenerRule domainNameRule("HIVIEWDFX", "APP_USAGE", RuleType::PREFIX);
std::vector<ListenerRule> 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", ]
```
# HiSysEvent查询指导<a name="ZH-CN_TOPIC_0000001231455461"></a> # HiSysEvent查询指导<a name="ZH-CN_TOPIC_0000001231455461"></a>
- [概述](#section279684125212) - [概述](#section279684125212)
- [接口说明](#section03869128521) - [开发指导](#section315316761113)
- [开发实例](#section14286111855212) - [接口说明](#section03869128521)
- [C++接口实例](#section162045551743) - [开发实例](#section14286111855212)
## 概述<a name="section279684125212"></a> ## 概述<a name="section279684125212"></a>
HiSysEvent提供了查询接口,支持开发者设置条件查询HiSysEvent事件,例如功耗部件可以通过该接口获取所需的系统事件进行业务分析。 HiSysEvent提供了查询接口,支持开发者设置条件查询HiSysEvent事件,例如功耗部件可以通过该接口获取所需的系统事件进行业务分析。
## 接口说明<a name="section03869128521"></a> ## 开发指导<a name="section315316761113"></a>
### 接口说明<a name="section03869128521"></a>
**表 1** HiSysEvent查询接口 **表 1** HiSysEvent查询接口
...@@ -115,11 +116,9 @@ HiSysEvent提供了查询接口,支持开发者设置条件查询HiSysEvent事 ...@@ -115,11 +116,9 @@ HiSysEvent提供了查询接口,支持开发者设置条件查询HiSysEvent事
</tbody> </tbody>
</table> </table>
## 开发实例<a name="section14286111855212"></a> ### 开发实例<a name="section14286111855212"></a>
### C++接口实例<a name="section162045551743"></a>
本实例介绍如何查询所有系统事件 C++接口实例
1. 源代码开发: 1. 源代码开发:
......
# HiSysEvent工具使用指导<a name="ZH-CN_TOPIC_0000001231614021"></a> # HiSysEvent工具使用指导<a name="ZH-CN_TOPIC_0000001231614021"></a>
- [概述](#section1886702718521) - [概述](#section1886702718521)
- [使用指导](#section1210623418527) - [实时订阅HiSysEvent事件相关命令](#section1210623418527)
- [查询历史HiSysEvent事件相关命令](#section1210623418539)
## 概述<a name="section1886702718521"></a> ## 概述<a name="section1886702718521"></a>
目前系统预制了HiSysEvent小工具,可以通过命令行参数,设置查询条件,查询满足要求的HiSysEvent系统事件,支撑开发者在开发过程中是否打点成功,以及故障定位时系统所发生的事件等研发场景 目前在系统的/system/bin目录下预置了hisysevent工具,开发者可以通过此工具实时订阅HiSysEvent事件及查询历史HiSysEvent事件
## 使用指导<a name="section1210623418527"></a> ## 实时订阅HiSysEvent事件相关命令<a name="section1210623418527"></a>
1. HiSysEvent工具的参数 - 实时订阅HiSysEvent事件的基础命令
工具预置在/system/bin目录下,命令可以在任意目录执行。 ```
hisysevent -r
```
选项说明:
| 选项名称 | 功能说明 |
| -------- | --------- |
| -r&nbsp; | 以缺省设置实时订阅HiSysEvent事件,在此种订阅方式下有任何实时HiSysEvent事件产生,都会在控制台上打印此HiSysEvent事件 |
- 打开调试模式:
``` ```
hisysevent [-r | -l [-s <time> -e <time> -m <count>]] hisysevent -r -d
-r get real hisysevent log.
-l -s <begin time> -e <end time> -m <max hisysevent count>
get history hisysevent log, begin time should not be earlier than end time.
``` ```
2. 查询实时HiSysEvent事件的命令: 选项说明:
| 选项名称 | 功能说明 |
| -------- | --------- |
| -d | 在调试模式下实时订阅HiSysEvent事件 |
- 通过事件标签方式实时订阅HiSysEvent事件:
``` ```
hisysevent -r hisysevnet -r -t <tag> [-c [WHOLE_WORD|PREFIX|REGULAR]]
``` ```
当实时HiSysEvent事件过来的时候,会在控制台上打印一条HiSysEvent事件。 选项说明:
3. 查询历史HiSysEvent事件的命令: | 选项名称 | 功能说明 |
| -------- | --------- |
| -t&nbsp; | 设置实时订阅的HiSysEvent事件标签,用来过滤订阅的HiSysEvent事件 |
| -c&nbsp; | 设置实时订阅的HiSysEvent事件标签匹配规则,有“WHOLE_WORD”、“PREFIX”、“REGULAR”三种匹配规则|
- 通过事件领域及事件名称的方式实时订阅HiSysEvent事件:
``` ```
hisysevent -l -s <begin time> -e <end time> -m <max hisysevent count> hisysevent -r -o <domain> -n <eventName> [-c [WHOLE_WORD|PREFIX|REGULAR]]
``` ```
其中-s和-e分别指定了事件生成的开始时间和结束时间,如果没有-s或者-e,代表查询时间无下限/无上限。 | 选项名称 | 功能说明 |
| -------- | --------- |
| -o | 设置实时订阅的HiSysEvent事件领域,用来过滤订阅的HiSysEvent事件 |
| -n | 设置实时订阅的HiSysEvent事件名称,用来过滤订阅的HiSysEvent事件|
| -c | 设置实时订阅的HiSysEvent事件领域及事件名称的匹配规则,有“WHOLE_WORD”、“PREFIX”、“REGULAR”三种匹配规则|
>![](../public_sys-resources/icon-note.gif) **说明:**
>当同时通过-t、-o及-n指定了相关订阅规则参数设置,则判断设置的事件标签是否为空,若不为空,则使用事件标签规则进行订阅,否则使用事件领域及事件名称订阅规则进行订阅。
-m参数制定了本次查询最多返回的时间条数。 ## 查询历史HiSysEvent事件相关命令<a name="section1210623418539"></a>
- 查询历史HiSysEvent事件的基础命令:
```
hisysevent -l
```
选项说明:
| 选项名称 | 功能说明 |
| -------- | --------- |
| -l | 以缺省设置查询历史HiSysEvent事件,此次查询会返回最近不多于1000条的HiSysEvent事件 |
- 通过设置开始/结束时间,过滤查询历史HiSysEvent事件的结果的命令:
```
hisysevent -l -s <begin time> -e <end time>
```
选项说明:
| 选项名称 | 功能说明 |
| -------- | --------- |
| -s | 设置查询历史HiSysEvent事件的开始时间,此次查询只会返回不早于该时间点的HiSysEvent事件 |
| -e | 设置查询历史HiSysEvent事件的结束时间,此次查询只会返回不晚于该时间点的HiSysEvent事件 |
- 通过设置最大数量值,限制查询历史HiSysEvent事件的数量:
```
hisysevent -l -m <max hisysevent count>
```
选项说明:
| 选项名称 | 功能说明 |
| -------- | --------- |
| -m | 设置查询历史HiSysEvent事件的数量,有效值范围[0,1000],此次查询返回的HiSysEvent事件数目不会多于此值。 |
# HiSysEvent打点配置指导<a name="ZH-CN_TOPIC_0000001080478132"></a>
- [概述](#section315316685115)
- [基本概念](#section123181432175143)
- [约束与限制](#section123181432175114)
- [编写yaml文件](#section123181432175113)
- [yaml文件编写规则](#section123181432175133)
- [yaml文件编写样例](#section123181432175123)
- [验证yaml文件](#section123181432175115)
- [配置yaml文件路径](#section123181432175135)
- [编译yaml文件](#section123181432175137)
- [打点及查询定义的事件](#section123181432175139)
## 概述<a name="section315316685115"></a>
组件若有HiSysEvent事件的打点需求,则需要先定义yaml文件并在bundle.js文件中[配置yaml文件的路径](#section123181432175135)。OpenHarmony编译框架在编译过程中则会通过python编译脚本解析校验bundle.js文件指定的所有yaml文件。在解析校验之后,编译框架会将这些yaml文件中配置的信息汇总转换成名为hisysevent.def的json文件。最后,将此json文件打包到系统指定路径下,用作HiSysEvent事件落盘的判断依据。
### 基本概念<a name="section123181432175143"></a>
在配置HiSysEvent打点之前,开发者应了解以下基本概念:
- 事件领域
用于标识事件所属的领域,在yaml文件中以domain为键值指定,可参考yaml文件样例中的[domain](#section123181432175123)
- 事件名称
用于指定事件领域包含的所有事件,可参考yaml文件样例中的[EVENT_NAMEA/EVENT_NAMEB](#section123181432175123)
- 参数
用于定义某个事件名称包含的所有键值,可参考yaml文件样例中的[__BASE/NAME1/NAME2](#section123181432175123)
### 约束与限制<a name="section123181432175114"></a>
**定义事件领域、事件名称及参数的约束与限制:**
- 每个yaml文件只能有一个事件领域,且不能与其他yaml文件中定义的事件领域重名。
- 每个事件领域可定义零个或多个事件名称,同一个事件领域内部的事件名称不能重名。
- 每个事件名称可定义多个参数,同一个事件名称内部的参数不能重名,每个事件名称**有且只有**一个名称为__BASE的参数,此参数字段组成如表1,他自定义参数,具体字段组成如表2。
**表 1** __BASE参数字段说明
<a name="table1844019587513"></a>
<table><thead align="left"><tr id="row1440058186118"><th class="cellrowborder" valign="top" id="mcps1.2.3.1.1"><p id="p19441135865020"><a name="p19441135845020"></a><a name="p19441135865020"></a>字段名称</p>
</th>
<th class="cellrowborder" valign="top" id="mcps1.2.3.1.2"><p id="p13441195865593"><a name="p13441195865593"></a><a name="p13441195865593"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row16441155868499">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p877916438213"><a name="p877916438613"></a><a name="p877916438613"></a>type</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727325136218"><a name="p14727325136218"></a><a name="p14727325136218"></a>字段说明:<br>&emsp;&emsp;必选字段,用来标识该事件名称的类型。</p>
<p id="p167271525203615"><a name="p167271525203615"></a><a name="p167271525203615"></a>取值范围:</p>
<a name="ul6717142214621"></a><a name="ul6717142214621"></a>
<ul id="ul6717142214621">
<li>FAULT:错误类型。</li>
<li>STATISTIC:统计类型。</li>
<li>SECURITY:安全性。</li>
<li>BEHAVIOR:用户行为。</li>
</ul>
</td>
</tr>
<tr id="row16441155818699">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p877916438616"><a name="p877916438616"></a><a name="p877916438616"></a>level</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727325153218"><a name="p14727325153218"></a><a name="p14727325153218"></a>字段作用:<br>&emsp;&emsp;必选字段,用来标识该事件名称的级别。</p>
<p id="p167271525213215"><a name="p167271525213215"></a><a name="p167271525213215"></a>取值范围:</p>
<a name="ul6717142215021"></a><a name="ul6717142215021"></a>
<ul id="ul6717142215021">
<li>CRITICAL:严重。</li>
<li>MINOR:一般。</li>
</ul>
</td>
</tr>
<tr id="row16441155818519">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p877916458213"><a name="p877916458213"></a><a name="p877916458213"></a>tag</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727327733218"><a name="p14727327733218"></a><a name="p14727327733218"></a>字段作用:<br>&emsp;&emsp;可选字段,用来标识该事件名称的标签。</p>
<p id="p167271395203215"><a name="p167271395203215"></a><a name="p167271395203215"></a>定义规则:</p>
<a name="ul6717143414921"></a><a name="ul6717143414921"></a>
<ul id="ul6717143414921">
<li>最多可同时定义5个标签,标签之间使用空格来分隔。</li>
<li>单个标签最多包含16个字符,字符范围[a-zA-Z0-9]。</li>
</ul>
</td>
</tr>
<tr id="row16441155817799">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p877916477213"><a name="p877916477213"></a><a name="p877916477213"></a>desc</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727725133218"><a name="p14727725133218"></a><a name="p14727725133218"></a>字段作用:<br>&emsp;&emsp;必选字段,用来对该事件名称进行描述。</p>
<p id="p167277525203215"><a name="p167277525203215"></a><a name="p167277525203215"></a>定义规则:</p>
<a name="ul6777142214921"></a><a name="ul6777142214921"></a>
<ul id="ul6777142214921">
<li>至少包含3个字符,最多包含128个字符,字符范围[a-zA-Z0-9 _]</li>
</ul>
</td>
</tr>
</tbody>
</table>
**表 2** 自定义参数字段说明
<a name="table1844019587523"></a>
<table><thead align="left"><tr id="row1440060185118"><th class="cellrowborder" valign="top" id="mcps1.2.3.1.1"><p id="p19442235845020"><a name="p19442235845020"></a><a name="p19442235845020"></a>字段名称</p>
</th>
<th class="cellrowborder" valign="top" id="mcps1.2.3.1.2"><p id="p13331195815593"><a name="p13331195815593"></a><a name="p13331195815593"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row16441232818499">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p8779163453213"><a name="p8779163453213"></a><a name="p8779163453213"></a>type</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727325235218"><a name="p14727325235218"></a><a name="p14727325235218"></a>字段说明:<br>&emsp;&emsp;必选字段,用来标识该参数的类型。</p>
<p id="p167271372203215"><a name="p167271372203215"></a><a name="p167271372203215"></a>取值范围:</p>
<a name="ul6717342214921"></a><a name="ul6717342214921"></a>
<ul id="ul6717134514921">
<li>BOOL</li>
<li>INT8</li>
<li>UINT8</li>
<li>INT16</li>
<li>UINT16</li>
<li>INT32</li>
<li>UINT32</li>
<li>INT64</li>
<li>UINT64</li>
<li>FLOAT</li>
<li>DOUBLE</li>
<li>STRING</li>
</ul>
</td>
</tr>
<tr id="row16326155818499">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p877567438213"><a name="p877567438213"></a><a name="p877567438213"></a>arrsize</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727324893218"><a name="p14727324893218"></a><a name="p14727324893218"></a>字段作用:<br>&emsp;&emsp;可选字段,用来标识数组类型参数的长度。</p>
<p id="p1672715498703215"><a name="p1672715498703215"></a><a name="p1672715498703215"></a>取值范围:<br>&emsp;&emsp; 1~100</p>
</ul>
</td>
</tr>
<tr id="row16556155818499">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p845916438213"><a name="p845916438213"></a><a name="p845916438213"></a>desc</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727343133218"><a name="p14727343133218"></a><a name="p14727343133218"></a>字段作用:<br>&emsp;&emsp;必选字段,用来对该参数进行描述。</p>
<p id="p167271524323215"><a name="p167271524323215"></a><a name="p167271524323215"></a>定义规则:</p>
<a name="ul6717142111921"></a><a name="ul6717142111921"></a>
<ul id="ul6717156714921">
<li>至少包含3个字符,最多包含128个字符,字符范围[a-zA-Z0-9 _]</li>
</ul>
</td>
</tr>
</tbody>
</table>
## 编写yaml文件<a name="section123181432175113"></a>
### yaml文件编写规则<a name="section123181432175133"></a>
- 事件领域命名规则:
- 字母开头,且只能由大写字母/数字/下划线组成;
- 字符串长度取值范围为1~16。
- 事件名称命名规则:
- 字母开头,且只能由大写字母/数字/下划线组成;
- 字符串长度取值范围1~32;
- 单个事件领域内部事件名称的不能超过4096个。
- 参数命名规则:
- 字母开头,且只能由大写字母/数字/下划线组成;
- 字符串长度取值范围1~32;
- 单个事件名称内包含的参数的个数不能超过128个。
### yaml文件编写样例<a name="section123181432175123"></a>
- yaml文件样例指定的事件领域名称为MODULEA,该事件领域包含两个事件,名称分别是EVENT_NAMEA和EVENT_NAMEB。
- EVENT_NAMEA被定义成错误类型的严重事件,该事件包含类型为字符串类型的NAME1参数、字符串类型的NAME2参数及无符号短整型类型的NAME3参数,可以通过事件领域MODULEA和事件名称EVENT_NAMEA对其进行[实时订阅](subsys-dfx-hisysevent-read.md)
- EVENT_NAMEB被定义成统计类型的一般事件,EVENT_NAMEB包含类型为无符号短整型类型的NAME1参数及整型类型的NAME2参数。因为EVENT_NAMEB在__BASE参数中定义了名称为tag1和tag2的两个事件标签,所以不仅可以通过事件领域MODULEA和事件名称EVENT_NAMEB对其进行[实时订阅](subsys-dfx-hisysevent-read.md),,所以还可以通过事件标签对该事件进行[实时订阅](subsys-dfx-hisysevent-read.md)
```
##########################################
# the hisysevent definition for module a #
##########################################
domain: MODULEA
EVENT_NAMEA:
__BASE: {type: FAULT, level: CRITICAL, desc: event name a}
NAME1: {type: STRING, desc: name1}
NAME2: {type: STRING, desc: name2}
NAME3: {type: UINT16, desc: name3}
EVENT_NAMEB:
__BASE: {type: STATISTIC, level: MINOR, tag: tag1 tag2, desc: event name b}
NAME1: {type: UINT16, desc: name1}
NAME2: {type: INT32, desc: name2}
```
## 验证yaml文件<a name="section123181432175115"></a>
### 配置yaml文件路径<a name="section123181432175135"></a>
在bundle.js文件中通过```hisysevent_config```属性完成yaml文件的路径指定:
```
{
"name": "@ohos/moduel_a",
"description": "module a",
"version": "3.1",
"license": "Apache License 2.0",
"publishAs": "code-segment",
"segment": {
"destPath": "moduel_a_path"
},
"dirs": {},
"scripts": {},
"component": {
"name": "hisysevent_native",
"subsystem": "hiviewdfx",
"adapted_system_type": [
"standard"
],
"rom": "",
"ram": "",
"hisysevent_config": [
"//moduel_a_path/yaml_file1.yaml",
"//moduel_a_path/yaml_file2.yaml"
],
"deps": {
"components": [
"hilog_native",
"hitrace_native",
"ipc",
"safwk",
"samgr_standard",
"utils_base"
],
"third_party": []
},
"build": {
}
}
}
```
>![](../public_sys-resources/icon-note.gif) **说明:**
>yaml文件可根据实际需求置于组件工程的任意目录下,只要在bundle.js文件指定即可。
### 编译yaml文件<a name="section123181432175137"></a>
- 全量编译:
- 全量编译整个系统,会将所有组件配置的yaml文件中的配置进行汇总,正常完成系统编译后,指定目录下就会生成hisysevent.def文件。
```
cd 工程根目录的绝对路径
./build --product-name <product name>
```
- 全量编译生成的hisysevent.def文件可以通过以下命令获取:
```
cd 工程根目录的绝对路径
find out -name hisysevent.def -type f
```
- 单文件编译:
也可以只编译单个组件的yaml文件,命令如下:
```
cd 工程根目录的绝对路径
./build/ohos/hisysevent/gen_def_from_all_yaml.py --yaml-list <yaml file list> --def-path <file store directory>
```
**表 3** 单文件编译参数说明
<a name="table1844019587534"></a>
<table><thead align="left"><tr id="row1440056575118"><th class="cellrowborder" valign="top" id="mcps1.2.3.1.1"><p id="p19432435845020"><a name="p19432435845020"></a><a name="p19432435845020"></a>选项名称</p>
</th>
<th class="cellrowborder" valign="top" id="mcps1.2.3.1.2"><p id="p13441196715593"><a name="p13441196715593"></a><a name="p13441196715593"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row16441155854499">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p877916558213"><a name="p877916558213"></a><a name="p877916558213"></a>--yaml-list</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727325133218"><a name="p14727325133218"></a><a name="p14727325133218"></a>指定需要编译的yaml文件路径列表,多个yaml文件路径之间用空格分隔。</p>
</td><tr id="row16441155832499">
<td class="cellrowborder" width="60%" valign="top" headers="mcps1.2.3.1.1 ">
<p id="p877916421213"><a name="p877916421213"></a><a name="p877916421213"></a>--def-path</p>
</td>
<td class="cellrowborder" valign="top" headers="mcps1.2.3.1.2 ">
<p id="p14727323533218"><a name="p14727323533218"></a><a name="p14727323533218"></a>指定编译生成的hisysevent.def文件的生成路径。</p>
</td>
</tr>
</tbody>
</table>
### 打点及查询定义的事件<a name="section123181432175139"></a>
1. 通过[hdc_std工具](subsys-toolchain-hdc-guide.md)将hisysevent.def文件推送到至设备的//system/etc/hiview/目录下;
2. 触发yaml文件自定义的HiSysEvent事件完成打点,通过[hisysevent -l](subsys-dfx-hisysevent-tool.md)命令查询历史HiSysEvent事件,确认触发的自定义HiSysEvent事件是否打点成功。
# HiSysEvent打点指导<a name="ZH-CN_TOPIC_0000001231373947"></a> # HiSysEvent打点指导<a name="ZH-CN_TOPIC_0000001231373947"></a>
- [概述](#section77571101789) - [概述](#section77571101789)
- [接口说明](#section13480315886) - [功能简介](#section123133332175224)
- [开发实例](#section112771171317) - [约束与限制](#section123181432175224)
- [开发指导](#section314416685113)
- [接口说明](#section13480315886)
- [开发实例](#section112771171317)
## 概述<a name="section77571101789"></a> ## 概述<a name="section77571101789"></a>
### 功能简介<a name="section123133332175224"></a>
HiSysEvent提供OpenHarmony打点接口,通过在关键路径打点记录系统在运行过程中的重要信息,辅助开发者定位问题,此外还支持开发者将数据上传到云进行大数据质量度量。 HiSysEvent提供OpenHarmony打点接口,通过在关键路径打点记录系统在运行过程中的重要信息,辅助开发者定位问题,此外还支持开发者将数据上传到云进行大数据质量度量。
## 接口说明<a name="section13480315886"></a> ### 约束与限制<a name="section123181432175224"></a>
**HiSysEvent事件打点条件约束:**
- 在进行HiSysEvent事件打点之前,需要先完成HiSysEvent打点配置,具体配置方法请参考[《HiSysEvent打点配置指导》](subsys-dfx-hisysevent-write-config.md)
## 开发指导<a name="section314416685113"></a>
### 接口说明<a name="section13480315886"></a>
C++打点接口如下: C++打点接口如下:
...@@ -258,7 +271,7 @@ HiSysEvent类,具体的API详见接口文档 。 ...@@ -258,7 +271,7 @@ HiSysEvent类,具体的API详见接口文档 。
</tbody> </tbody>
</table> </table>
## 开发实例<a name="section112771171317"></a> ### 开发实例<a name="section112771171317"></a>
C++接口实例 C++接口实例
...@@ -281,5 +294,3 @@ C++接口实例 ...@@ -281,5 +294,3 @@ C++接口实例
``` ```
external_deps = [ "hisysevent_native:libhisysevent" ] external_deps = [ "hisysevent_native:libhisysevent" ]
``` ```
# HiSysEvent开发指导<a name="ZH-CN_TOPIC_0000001195021448"></a> # HiSysEvent开发指导<a name="ZH-CN_TOPIC_0000001195021448"></a>
- **[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-read.md)**
- **[HiSysEvent工具使用指导](subsys-dfx-hisysevent-tool.md)**
- **[HiSysEvent查询指导](subsys-dfx-hisysevent-select.md)**
- **[HiSysEvent工具使用指导](subsys-dfx-hisysevent-tool.md)**
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册