提交 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
### 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
......
### 0.0.6 (2022/02/10)
1、更新hb。
2、增加安装ruby。
### 0.0.5 (2021/06/21)
1、更新llvm版本从10.0.1-53907更新到10.0.1-62608,支撑ipcamera_hispark_taurus_linux编译。
......
### 0.0.5 (2021/06/21)
1\. Updated hb.
2\. Added the installation of ruby.
### 0.0.5 (2021/06/21)
1\. Updated LLVM from 10.0.1-53907 to 10.0.1-62608. Introduced support for ipcamera\_hispark\_taurus\_linux.
......
......@@ -43,16 +43,17 @@ RUN apt-get update -y \
&& apt-get install gcc-arm-linux-gnueabi -y \
&& apt-get install build-essential \
&& apt-get install locales \
&& apt-get install ruby -y \
&& locale-gen "en_US.UTF-8" \
&& rm -rf /bin/sh /usr/bin/python /usr/bin/python3 \
&& ln -s /bin/bash /bin/sh \
&& ln -s /usr/bin/python3.8 /usr/bin/python3 \
&& ln -s /usr/bin/python3.8 /usr/bin/python \
&& pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple setuptools \
&& pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple kconfiglib \
&& pip3 install --trusted-host mirrors.aliyun.com -i http://mirrors.aliyun.com/pypi/simple pycryptodome \
&& pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple ecdsa \
&& python3 -m pip install --user ohos-build \
&& pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple setuptools \
&& pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple kconfiglib \
&& pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple pycryptodome \
&& pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple ecdsa \
&& pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple ohos-build \
&& mkdir -p /home/tools \
&& wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/clang/10.0.1-62608/linux/llvm.tar.gz \
&& wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/hc-gen/0.65/linux/hc-gen-0.65-linux.tar \
......
......@@ -8,21 +8,19 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通
| Docker镜像仓库 | 标签 | 说明 |
| :----------------------------------------------------------- | :------ | :----------------------------------------------------------- |
| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.5` | 已经预安装HarmonyOSOpenHarmony版本的编译环境,支持轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB)的版本构建。 |
| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.6` | 已经预安装OpenHarmony版本的编译环境,支持轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB)的版本构建。 |
### 使用方式及步骤
开发者在配置好开发环境后,可以通过以下步骤来使用我们提供的Docker环境,支持Ubuntu/Windows平台,下文将以Ubuntu系统为例进行使用介绍。
#### 方式一:从**HuaweiCloud SWR**上直接获取Docker镜像进行构建:
开发者在配置好开发环境后,可以通过以下步骤来使用我们提供的Docker环境。详情请参见[Docker编译环境](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/gettools-acquire.md)
1. 获取Docker镜像
```
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6
```
2. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境
```
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6
```
3. 通过如下命令启动不同平台的编译
```
......@@ -31,25 +29,3 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通
在显示的页面中通过键盘上下键选择需要编译的平台,通过回车确定选择。
hb build -f #执行编译。
```
#### 方式二:通过Dockerfile 构建本地Docker镜像进行构建
1. 获取Dockerfile脚本文件,用来构建本地Docker镜像
```
git clone https://gitee.com/openharmony/docs.git
```
2. 进入Dockerfile代码目录路径执行Docker镜像构建命令
```
cd docs/docker
./build.sh
```
4. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境
```
docker run -it -v $(pwd):/home/openharmony openharmony-docker:0.0.5
```
5. 通过如下命令启动不同平台的编译
```
hb set #设置工作目录。
. #输入源码所在目录,点(.)表示当前目录。
在显示的页面中通过键盘上下键选择需要编译的平台,通过回车确定选择。
hb build -f #执行编译。
```
......@@ -8,21 +8,19 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua
| Docker Image Repository | Tag | Description |
| :----------------------------------------------------------- | :------ | :----------------------------------------------------------- |
| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.5` | The HarmonyOSOpenHarmony build environment has been pre-installed. This repository applies to Mini-System Devices (reference memory ≥ 128 KB) and Small-System Devices (reference memory ≥ 1 MB). |
| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.6` | The OpenHarmony build environment has been pre-installed. This repository applies to Mini-System Devices (reference memory ≥ 128 KB) and Small-System Devices (reference memory ≥ 1 MB). |
### Usage
After configuring the development environments, perform the steps below to access the Docker environment. The following steps use Ubuntu as an example (Windows is also supported).
#### **Method 1: Obtaining the Docker image from HuaweiCloud SWR**:
After configuring the development environments, perform the steps below to access the Docker environment.
1. Obtain the Docker image.
```
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6
```
2. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment:
```
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6
```
3. Run the following script to start building for different platforms.
```
......@@ -31,25 +29,3 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua
Press the Up or Down key to select the platform to build on, then press Enter.
hb build -f # Start building.
```
#### **Method 2: Using the Dockerfile to Build a Local Docker Image**
1. Obtain the Dockerfile script for a local Docker image.
```
git clone https://gitee.com/openharmony/docs.git
```
2. Go to the directory of the Dockerfile code and run the following command to build the Docker image:
```
cd docs/docker
./build.sh
```
4. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment:
```
docker run -it -v $(pwd):/home/openharmony openharmony-docker:0.0.5
```
5. Run the following script to start building for different platforms.
```
hb set # Set the working directory.
. # Enter the directory where the source code is stored. If the code is stored in the current directory, enter a period (.).
Press the Up or Down key to select the platform to build on, then press Enter.
hb build -f # Start building.
```
......@@ -13,4 +13,4 @@
# See the License for the specific language governing permissions and
# limitations under the License.
docker build -t openharmony-docker:0.0.5 .
docker build -t openharmony-docker:0.0.6 .
......@@ -6,8 +6,6 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua
### Setting Up the Docker Environment for Standard-System Devices (reference memory ≥ 128 MB)
##### **Method 1: Obtaining the Docker image from HuaweiCloud SWR**:
1. Obtain the Docker image.
```
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7
......@@ -17,22 +15,6 @@ docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-dock
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7
```
##### **Method 2: Using the Dockerfile to Build a Local Docker Image**
1. Obtain the Dockerfile script for a local Docker image.
```
git clone https://gitee.com/openharmony/docs.git
```
2. Go to the directory of the Dockerfile code and run the following command to build the Docker image:
```
cd docs/docker/standard
./build.sh
```
3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment:
```
docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7
```
### Building for Standard-System Devices (reference memory ≥ 128 MB)
Run the following script to start building for Standard-System Devices (reference memory ≥ 128 MB)
......
......@@ -2,12 +2,10 @@
本文为标准系统类设备Docker使用指导,[点此查看](https://gitee.com/openharmony/docs/blob/master/docker/README.md)小型和轻量系统类设备使用指导。
OpenHarmony的Docker镜像托管在HuaweiCloud SWR上。开发者可以通过该镜像在很大程度上简化编译前的环境配置。开发者在配置好开发环境后,通过以下步骤来使用Docker环境。本Docker支持Ubuntu/Windows平台,下文将以Ubuntu系统为例进行使用介绍。
OpenHarmony的Docker镜像托管在HuaweiCloud SWR上。开发者可以通过该镜像在很大程度上简化编译前的环境配置。开发者在配置好开发环境后,通过以下步骤来使用Docker环境。
### 搭建Docker环境-标准系统类设备(参考内存≥128MB)
##### 方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建:
1. 获取Docker镜像。
```
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7
......@@ -17,22 +15,6 @@ docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-dock
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7
```
##### 方式二:通过Dockerfile 构建本地Docker镜像进行构建
1. 获取Dockerfile脚本文件,用来构建本地Docker镜像。
```
git clone https://gitee.com/openharmony/docs.git
```
2. 进入Dockerfile代码目录路径执行Docker镜像构建命令。
```
cd docs/docker/standard
./build.sh
```
3. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。
```
docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7
```
### 编译源码-标准系统类设备(参考内存≥128MB)
通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。
......
# 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 @@
## When to Use
You use audio playback APIs to convert audio data into audible analog signals, play the audio signals using output devices, and manage playback tasks.
You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks.
**Figure 1** Playback status
![](figures/playback-status.png "playback-status")
## Available APIs
**Table 1** APIs for audio playback
| API| Description|
| -------- | -------- |
| media.createAudioPlayer() | Creates an **AudioPlayer** instance.|
| AudioPlayer | Provides audio playback features. For details, see the table below.|
**Table 2** AudioPlayer methods
| Method| Description|
| -------- | -------- |
| release() | Releases audio resources.|
| play() | Starts audio playback.|
| pause() | Pauses playback.|
| stop() | Stops playback.|
| reset()<sup>7+</sup> | Resets the audio source to be played.|
| setVolume(vol:&nbsp;number) | Sets playback volume.|
| seek(timeMs:&nbsp;number) | Changes the playback position.|
| src:string | Defines the URI of an audio file to play.|
| state:AudioState | Defines the playback state.|
| currentTime:number | Defines the current playback position.|
| duration:number | Defines the playback duration. The value **-1** is returned if the data source does not support playback position change, for example, in the real-time streaming media scenario.|
| loop:boolean | Defines whether to loop audio playback.|
| on('play',&nbsp;function&nbsp;callback) | Subscribes to the playback start event.|
| on('pause',&nbsp;function&nbsp;callback) | Subscribes to the playback pause event.|
| on('stop',&nbsp;function&nbsp;callback) | Subscribes to the playback stop event.|
| on('reset',&nbsp;function&nbsp;callback) | Subscribes to the playback reset event.|
| on('finish',function&nbsp;callback) | Subscribes to the playback end event.|
| on('error',&nbsp;function&nbsp;callback) | Subscribes to the playback error event.|
| on('dataload',&nbsp;function&nbsp;callback) | Subscribes to the data loading event.|
| on('volumeChange',&nbsp;function&nbsp;callback) | Subscribes to the volume change event.|
| on('timeUpdate',&nbsp;function&nbsp;callback) | Subscribes to the progress change event.|
1. Create an audio player.
```
import media from '@ohos.multimedia.media';
var player = media.createAudioPlayer();
```
2. Set the subscription events.
```
player.on('play', (err, action) => {
if (err) {
console.error('Error returned in the play() callback.');
return;
}
console.info('Current player duration: '+ player.duration);
console.info('Current player time: ' + player.currentTime);
console.info('Current player status: '+player.state);
console.info('Pause MP3');
player.pause();
});
player.on('pause', (err, action) => {
if (err) {
console.error('Error returned in the pause() callback.');
![en-us_image_20220117](figures/en-us_image_20220117.jpg)
## How to Develop
For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md).
### Full-Process Scenario
The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting resources, and releasing resources.
For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_Attributes).
```js
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
// The playback page is ready. You can click the Play button to start the playback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
// The Play button is changed to the pausable state.
});
audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success');
// The Play button is changed to the playable state.
});
audioPlayer.on('stop', () => { // Set the 'stop' event callback.
console.info('audio stop success');
// The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state.
});
audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success');
// You can reconfigure the src attribute to play another audio file.
});
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail');
return;
}
console.info('Current player status: ' + player.state);
console.info('Current player time: ' + player.currentTime);
player.seek(30000); // Seek for 30 seconds.
});
player.on('stop', (err, action) => {
if (err) {
console.error('Error returned in the stop() callback.');
return;
}
console.info('stop callback invoked. State:' + player.state);
player.reset();
});
player.on('dataLoad', (err, action) => {
if (err) {
console.error('Error returned in the dataLoad() callback.');
return;
}
console.info('dataLoad callback invoked. Current time: ' + player.currentTime);
console.info('Duration of the source:' + player.duration);
player.play();
});
player.on('reset', (err, action) => {
if (err) {
console.error('Error returned in the reset() callback.');
return;
}
console.info('reset callback invoked.');
player.release();
});
player.on('finish', (err, action) => {
if (err) {
console.error('Error returned in the finish() callback.');
return;
}
console.info('finish callback invoked.');
});
player.on('timeUpdate', (seekTime, action) => {
console.info('Seek time: ' + seekTime);
console.info('Current player time: ' + player.currentTime);
var newTime = player.currentTime;
if(newTime == 30000) {
console.info('Seek succeeded. New time: ' + newTime);
} else {
console.error('Seek failed: ', + newTime);
console.info('audio seek success, and seek time is ' + seekDoneTime);
// The playback progress bar is updated to the seek position.
});
audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success');
// Display the updated volume.
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
});
audioPlayer.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
});
}
function printfDescription(obj) {
for (let item in obj) {
let property = obj[item];
console.info('audio key is ' + item);
console.info('audio value is ' + property);
}
}
// 1. Create an audioPlayer instance.
let audioPlayer = media.createAudioPlayer();
SetCallBack(audioPlayer); // Set the event callbacks.
// 2. Set the URI of the audio file.
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback.
// 3. Play the audio.
audioPlayer.play(); // The play() method can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered.
// 4. Seek to the playback position.
audioPlayer.seek(30000); // Trigger the 'timeUpdate' event callback, and seek to 30000 ms for playback.
// 5. Set the volume.
audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
// 6. Pause the playback.
audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
// 7. Obtain the track information.
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') {
for (let i = 0; i < arrlist.length; i++) {
printfDescription(arrlist[i]);
}
player.stop();
});
player.on('error', (err) => {
console.error('Player error: ${err.message}');
});
```
3. Start playback.
```
var audioSourceMp3 = 'file://test.mp3';
player.src = audioSourceMp3;
player.loop = true;
```
} else {
console.log(`audio getTrackDescription fail, error:${error.message}`);
}
});
// 8. Stop playback.
audioPlayer.stop(); // Trigger the 'stop' event callback.
// 9. Reset the playback resources.
audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
// 10. Release the resource.
audioPlayer.release(); // Release the AudioPlayer resource.
audioPlayer = undefined;
```
### Normal Playback Scenario
```js
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback.
```
### Switching to the Next Song
```js
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback.
/* Send the instruction to switch to the next song after a period of time. */
audioPlayer.reset();
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/next.mp3';
```
### Looping a Song
```js
function SetCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success');
audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback.
});
audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success');
});
audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance.
SetCallBack(audioPlayer); // Set the event callbacks.
/* Set the URI of the audio file selected by the user. */
audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback.
audioPlayer.loop = true; // Set the loop playback attribute.
```
......@@ -6,11 +6,11 @@
After the OpenHarmony SDK is configured, you can get started to develop your app by **importing a sample project**.
1. On the DevEco Studio welcome page, select **Configure** or click the ![](figures/en-us_image_0000001118018452.png) icon, and choose **Settings** \> **Version Control** \> **Git**. Then click **Test** to check whether the Git tool has been installed.
- If the tool has been installed, import a sample by referring to [2](#li5947194711181).
- If the tool has been installed, import a sample by following the instructions in Step 2.
![](figures/en-us_image_0000001118018088.png)
- If the tool hasn't been installed, click **Download and Install**. DevEco Studio will automatically download and install it. Then import a sample by referring to [2](#li5947194711181).
- If the tool hasn't been installed, click **Download and Install**. DevEco Studio will automatically download and install it. Then import a sample by following the instructions in Step 2.
![](figures/en-us_image_0000001164498191.png)
......
......@@ -15,7 +15,7 @@
- [Internationalization \(i18n\) ](js-apis-i18n.md)
- Media
- [Audio Management](js-apis-audio.md)
- [Media Playback and Recording](js-apis-media.md)
- [Media](js-apis-media.md)
- Security
- [User Authentication](js-apis-useriam-userauth.md)
- Data Management
......
# 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.
| :----- | :------------ | :--------------- |
| CHANNEL_1 | 0x1 << 0 | Channel count 1. |
| CHANNEL_2 | 0x1 << 1 | Channel count 2. |
| CHANNEL_3 | 0x1 << 2 | Channel count 3. |
| CHANNEL_4 | 0x1 << 3 | Channel count 4. |
| CHANNEL_5 | 0x1 << 4 | Channel count 5. |
| CHANNEL_6 | 0x1 << 5 | Channel count 6. |
| CHANNEL_7 | 0x1 << 6 | Channel count 7. |
| CHANNEL_8 | 0x1 << 7 | Channel count 8. |
## AudioSamplingRate<sup>8+</sup><a name="audiosamplingrate"></a>
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.|
# 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);
}
```
此差异已折叠。
# OpenHarmony Java Secure Coding Guide
# Java Secure Coding Guide
This document provides secure coding suggestions for Java-based development.
......@@ -1786,7 +1786,7 @@ public void xsltTrans(String src, String dst, String xslt) {
}
```
A security policy can be added to **TransformerFactory**. Java has a built-in blocklist for XSLT. Here some [insecure methods are disabled by setting **http://javax.xml.XMLConstants/feature/secure-processing** to **true**.](http://javax.xml.xmlconstants/feature/secure-processing属性设置为true开启防护,可以禁用一些不安全的方法。)
A security policy can be added to **TransformerFactory**. Java has a built-in blocklist for XSLT. Here some insecure methods are disabled by setting **http://javax.xml.XMLConstants/feature/secure-processing** to **true**.
## Try best to simplify the regular expression (regex) to prevent regular expression denial of service (ReDoS) attacks
......
# 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.
......
此差异已折叠。
......@@ -8,6 +8,8 @@
- [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md)
- [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md)
### Code Style
Develop, review, and test code following the OpenHarmony coding standards. Make sure code is written in the same style.
......@@ -17,6 +19,8 @@ Develop, review, and test code following the OpenHarmony coding standards. Make
- [JavaScript Coding Style Guide](OpenHarmony-JavaScript-coding-style-guide.md)
- [Python Coding Style Guide](https://pep8.org/)
- [C&C++ Secure Coding Guide](OpenHarmony-c-cpp-secure-coding-guide.md)
- [HDF Driver Coding Guide](OpenHarmony-Java-secure-coding-guide.md)
- [32- and 64-Bit Portability Coding Guide](OpenHarmony-64bits-coding-guide.md)
- [Java Secure Coding Guide](OpenHarmony-Java-secure-coding-guide.md)
- [Logging Guide](OpenHarmony-Log-guide.md)
......@@ -28,6 +32,6 @@ For details, see [Contribution Process](contribution-process.md).
- [Security Issue Handling and Release Processes](https://gitee.com/openharmony/security/blob/master/en/security-process/README.md)
- [OpenHarmony Security and Disclosure Statement](https://gitee.com/openharmony/security/blob/master/en/security-process/security-disclosure.md)
- [OpenHarmony Security Vulnerability Notice](https://gitee.com/openharmony/security/blob/master/en/security-process/security-disclosure.md)
......@@ -30,7 +30,7 @@ OpenHarmony provides the following two types of Docker environments for you to q
</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>
<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>
</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>
......@@ -60,6 +60,7 @@ OpenHarmony provides the following two types of Docker environments for you to q
## Preparations<a name="section7337134183512"></a>
Before using the Docker environment, perform the following operations:
......@@ -77,12 +78,10 @@ The Docker image of OpenHarmony is hosted on [HUAWEI CLOUD SWR](https://console
### Setting Up the Docker Environment for Mini-System Devices \(reference memory ≥ 128 KB\) and Small-System Devices \(reference memory ≥ 1 MB\)<a name="section319412277287"></a>
**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR**
1. Obtain the Docker image.
```
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6
```
2. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment:
......@@ -90,43 +89,13 @@ The Docker image of OpenHarmony is hosted on [HUAWEI CLOUD SWR](https://console
Run the following command in Ubuntu:
```
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
```
Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\):
```
docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
```
**Method 2: Using the Dockerfile to Build a Local Docker Image**
1. Obtain the Dockerfile script for a local Docker image.
```
git clone https://gitee.com/openharmony/docs.git
```
2. Go to the directory of the Dockerfile code and run the following command to build the Docker image:
```
cd docs/docker
./build.sh
```
3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment:
Run the following command in Ubuntu:
```
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6
```
Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\):
```
docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5
docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6
```
......@@ -164,8 +133,6 @@ hb set
### Setting Up the Docker Environment for Standard-System Devices \(reference memory ≥ 128 MB\)<a name="section13585262391"></a>
**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR**
1. Obtain the Docker image.
```
......@@ -179,28 +146,6 @@ hb set
```
**Method 2: Using the Dockerfile to Build a Local Docker Image**
1. Obtain the Dockerfile script for a local Docker image.
```
git clone https://gitee.com/openharmony/docs.git
```
2. Go to the directory of the Dockerfile code and run the following command to build the Docker image:
```
cd docs/docker/standard
./build.sh
```
3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment:
```
docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7
```
### Building for Standard-System Devices \(reference memory ≥ 128 MB\)<a name="section193711513406"></a>
Run the following script to start building for standard-system devices \(reference memory ≥ 128 MB\).
......@@ -209,7 +154,7 @@ Run the following script to start building for standard-system devices \(referen
./build.sh --product-name {product_name} --ccache
```
**product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300 and RK3568.
**product\_name** indicates the platform supported by the current distribution, for example, Hi3516DV300 and rk3568.
Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory.
......
......@@ -61,8 +61,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2.
## Obtaining the Docker Environment<a name="section181431248132513"></a>
**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR**
1. Obtain the Docker image.
```
......@@ -76,28 +74,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2.
```
**Method 2: Using the Dockerfile to Build a Local Docker Image**
1. Obtain the Dockerfile script for a local Docker image.
```
git clone https://gitee.com/openharmony/docs.git
```
2. Go to the directory of the Dockerfile code and run the following command to build the Docker image:
```
cd docs/docker/standard
./build.sh
```
3. Go to the root directory of source code and run the following command to access the Docker build environment:
```
docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7
```
## Building Source Code<a name="section92391739152318"></a>
1. Run the following script to start building for standard-system devices \(reference memory ≥ 128 MB\).
......@@ -106,7 +82,7 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2.
./build.sh --product-name {product_name} --ccache
```
**product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300, rk3568.
**product\_name** indicates the platform supported by the current distribution, for example, Hi3516DV300, rk3568.
Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory.
......
......@@ -68,7 +68,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
Table 5 API for deleting data
| Class| API| Description|
| ---- | ---- | ---- |
| RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data. <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
......
# 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
- Audio playback and recording
- Video playback and recording
- Photographing and recording \(with cameras\)
## Architecture<a name="section11660541594"></a>
**Figure 1** Common architecture of the multimedia subsystem<a name="fig13371156141412"></a>
![](figures/en-us_image_0000001163462711.png)
## System Architecture<a name="section11660541594"></a>
**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)
**Figure 3** Multimedia service flow for the small system<a name="fig1334042801419"></a>
![](figures/multimedia-service-flow-for-the-small-system.png "multimedia-service-flow-for-the-small-system")
- **Media**: provides playback and recording APIs for applications, and invokes the Gstreamer, Histreamer, or other engines through cross-process calling or direct calling.
- For the mini system, the media component invokes Histreamer to support audio playback.
- For the small system, the media component invokes recorder_lite to support audio/video recording and invokes player_lite by default to support audio/video playback. If the system variable **debug.media_service.histreamer** is set to **1**, the component invokes Histreamer to support audio/video playback. For details, see [syspara Module](https://device.harmonyos.com/en/docs/documentation/guide/subsys-boot-syspara-0000001063362360) or [syspara_lite](https://gitee.com/openharmony/startup_syspara_lite).
- For the standard system, the media component invokes Gstreamer to support audio/video playback and recording.
- **Audio**: supports audio input and output, policy management, and audio focus management.
- **Camera**: provides camera operation APIs for preview, photographing, and video recording.
- **Image**: supports encoding and decoding of common image formats.
- **MediaLibrary**: supports local and distributed media data access management.
- **Histreamer**: a lightweight media engine that supports file/network streaming media input, audio/video decoding and playback, audio/video encoding and recording, and plugin extension.
- **Gstreamer**: an open-source GStreamer engine that supports streaming media, audio and video playback, and recording.
## Directory Structure<a name="section161941989596"></a>
......@@ -59,6 +60,13 @@ The structure of the repository directory is as follows:
│ ├── figures # Architecture and process figures of the playback and recording module for the standard system
│ ├── frameworks # Playback and recording framework implementation for the standard system
│ └── interfaces # Playback and recording module APIs for the standard system
├── histreamer # Histreamer engine
│ └── engine # Media engine
│ ├── player # Encapsulated player
│ ├── foundation # Basic tools
│ ├── pipeline # Pipeline framework
│ └── plugin # Plugin framework
│ └── plugins # Platform software plugins
└── utils # Subsystem utility module
└── lite # Utility module for the small system
├── figures # Architecture and process figures of the utility module for the small system
......@@ -94,9 +102,10 @@ Load the kernel and related drivers before installing the repository. For detail
[multimedia\_utils\_lite](https://gitee.com/openharmony/multimedia_utils_lite)
[multimedia\_histreamer](https://gitee.com/openharmony/multimedia_histreamer)
[multimedia\_camera\_standard](https://gitee.com/openharmony/multimedia_camera_standard)
[multimedia\_audio\_standard](https://gitee.com/openharmony/multimedia_audio_standard)
[multimedia\_media\_standard](https://gitee.com/openharmony/multimedia_media_standard)
# 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 3.x Releases
- [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md)
- [OpenHarmony v3.0.1 LTS (2022-01-12)](OpenHarmony-v3.0.1-LTS.md)
- [OpenHarmony v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md)
## OpenHarmony 2.x Releases
- [OpenHarmony v2.2 beta2 (2021-08-04)](OpenHarmony-v2.2-beta2.md)
- [OpenHarmony 2.0 Canary (2021-06-02)](OpenHarmony-2-0-canary.md)
- [OpenHarmony 2.0 Canary (2021-06-02)](OpenHarmony-2-0-Canary.md)
## OpenHarmony 1.x Releases
- [OpenHarmony v1.1.3 LTS (2021-09-30)](OpenHarmony-v1-1-3-LTS.md)
- [OpenHarmony v1.1.2 LTS (2021-08-04)](OpenHarmony-v1.1.2-LTS.md)
......
......@@ -34,7 +34,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager';
import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay';
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspend delay will time out.");
console.info("Request suspension delay will time out.");
});
var id = delayInfo.requestId;console.info("requestId is: " + id);
```
......@@ -61,7 +61,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager';
let myReason = 'test requestSuspendDelay';
// 申请延迟挂起
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspend delay will time out.");
console.info("Request suspension delay will time out.");
});
// 打印延迟挂起信息
var id = delayInfo.requestId;
......
......@@ -20,6 +20,7 @@
- [媒体服务](js-apis-media.md)
- 安全
- [用户认证](js-apis-useriam-userauth.md)
- [访问控制](js-apis-security-accessToken.md)
- 数据管理
- [轻量级存储](js-apis-data-storage.md)
- [分布式数据管理](js-apis-distributed-data.md)
......@@ -31,6 +32,7 @@
- [文件管理](js-apis-fileio.md)
- [Statfs](js-apis-statfs.md)
- [目录环境](js-apis-environment.md)
- [公共文件访问与管理](js-apis-filemanager.md)
- 账号管理
- [分布式帐号管理](js-apis-distributed-account.md)
- [应用帐号管理](js-apis-appAccount.md)
......@@ -75,4 +77,18 @@
- [xml解析与生成](js-apis-xml.md)
- [xml转换JavaScript](js-apis-convertxml.md)
- [启动一个worker](js-apis-worker.md)
- [线性容器ArrayList](js-apis-arraylist.md)
- [线性容器Deque](js-apis-deque.md)
- [线性容器List](js-apis-list.md)
- [线性容器LinkedList](js-apis-linkedlist.md)
- [线性容器Queue](js-apis-queue.md)
- [线性容器Stack](js-apis-stack.md)
- [线性容器Vector](js-apis-vector.md)
- [非线性容器HashSet](js-apis-hashset.md)
- [非线性容器HashMap](js-apis-hashmap.md)
- [非线性容器PlainArray](js-apis-plainarray.md)
- [非线性容器TreeMap](js-apis-treemap.md)
- [非线性容器TreeSet](js-apis-treeset.md)
- [非线性容器LightWeightMap](js-apis-lightweightmap.md)
- [非线性容器LightWeightSet](js-apis-lightweightset.md)
# 线性容器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';
```
## 权限
## getAudioManager
getAudioManager(): AudioManager
......@@ -115,6 +110,7 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err)=>{
if (err) {
console.error('Failed to set the volume. ${err.message}');
......@@ -146,6 +142,7 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise&lt;void&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(()=>
console.log('Promise returned to indicate a successful volume setting.');
)
......@@ -167,6 +164,7 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;): v
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
console.error('Failed to obtain the volume. ${err.message}');
......@@ -197,6 +195,7 @@ getVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) =>
console.log('Promise returned to indicate that the volume is obtained.' + value);
)
......@@ -218,6 +217,7 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;)
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
console.error('Failed to obtain the minimum volume. ${err.message}');
......@@ -248,6 +248,7 @@ getMinVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) =>
console.log('Promised returned to indicate that the minimum volume is obtained.' + value);
)
......@@ -269,6 +270,7 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback&lt;number&gt;)
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
console.error('Failed to obtain the maximum volume. ${err.message}');
......@@ -299,6 +301,7 @@ getMaxVolume(volumeType: AudioVolumeType): Promise&lt;number&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data)=>
console.log('Promised returned to indicate that the maximum volume is obtained.');
)
......@@ -321,6 +324,7 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback&lt;void
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => {
if (err) {
console.error('Failed to mute the stream. ${err.message}');
......@@ -353,6 +357,7 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise&lt;void&gt;
```
var audioManager = audio.getAudioManager();
audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() =>
console.log('Promise returned to indicate that the stream is muted.');
)
......@@ -375,6 +380,7 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): voi
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
console.error('Failed to obtain the mute status. ${err.message}');
......@@ -406,6 +412,7 @@ isMute(volumeType: AudioVolumeType): Promise&lt;boolean&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) =>
console.log('Promise returned to indicate that the mute status of the stream is obtained.' + value);
)
......@@ -427,6 +434,7 @@ isActive(volumeType: AudioVolumeType, callback: AsyncCallback&lt;boolean&gt;): v
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => {
if (err) {
console.error('Failed to obtain the active status of the stream. ${err.message}');
......@@ -457,6 +465,7 @@ isActive(volumeType: AudioVolumeType): Promise&lt;boolean&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) =>
console.log('Promise returned to indicate that the active status of the stream is obtained.' + value);
)
......@@ -478,6 +487,7 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback&lt;void&gt;): void
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => {
if (err) {
console.error('Failed to set the ringer mode.​ ${err.message}');
......@@ -508,6 +518,7 @@ setRingerMode(mode: AudioRingMode): Promise&lt;void&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() =>
console.log('Promise returned to indicate a successful setting of the ringer mode.');
)
......@@ -529,6 +540,7 @@ getRingerMode(callback: AsyncCallback&lt;AudioRingMode&gt;): void
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getRingerMode((err, value) => {
if (err) {
console.error('Failed to obtain the ringer mode.​ ${err.message}');
......@@ -554,6 +566,7 @@ getRingerMode(): Promise&lt;AudioRingMode&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getRingerMode().then((value) =>
console.log('Promise returned to indicate that the ringer mode is obtained.' + value);
)
......@@ -576,6 +589,7 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback&lt;void&gt
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => {
if (err) {
console.error('Failed to set the audio parameter. ${err.message}');
......@@ -607,6 +621,7 @@ setAudioParameter(key: string, value: string): Promise&lt;void&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setAudioParameter('PBits per sample', '8 bit').then(() =>
console.log('Promise returned to indicate a successful setting of the audio parameter.');
)
......@@ -628,6 +643,7 @@ getAudioParameter(key: string, callback: AsyncCallback&lt;string&gt;): void
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getAudioParameter('PBits per sample', (err, value) => {
if (err) {
console.error('Failed to obtain the value of the audio parameter. ${err.message}');
......@@ -658,6 +674,7 @@ getAudioParameter(key: string): Promise&lt;string&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getAudioParameter('PBits per sample').then((value) =>
console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value);
)
......@@ -678,6 +695,7 @@ getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback&lt;AudioDeviceDescrip
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{
if (err) {
console.error('Failed to obtain the device list. ${err.message}');
......@@ -708,6 +726,7 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data)=>
console.log('Promise returned to indicate that the device list is obtained.');
)
......@@ -730,6 +749,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean, callback: AsyncCallback
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true, (err)=> {
if (err) {
console.error('Failed to set the active status of the device. ${err.message}');
......@@ -762,6 +782,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean): Promise&lt;void&gt;
```
var audioManager = audio.getAudioManager();
audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true).then(()=>
console.log('Promise returned to indicate that the device is set to the active status.');
)
......@@ -783,6 +804,7 @@ isDeviceActive(deviceType: DeviceType, callback: AsyncCallback&lt;boolean&gt;):
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.isDeviceActive(audio.DeviceType.SPEAKER, (err, value) => {
if (err) {
console.error('Failed to obtain the active status of the device. ${err.message}');
......@@ -814,6 +836,7 @@ isDeviceActive(deviceType: DeviceType): Promise&lt;boolean&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.isDeviceActive(audio.DeviceType.SPEAKER).then((value) =>
console.log('Promise returned to indicate that the active status of the device is obtained.' + value);
)
......@@ -835,6 +858,7 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback&lt;void&gt;): void
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setMicrophoneMute(true, (err) => {
if (err) {
console.error('Failed to mute the microphone. ${err.message}');
......@@ -865,6 +889,7 @@ setMicrophoneMute(mute: boolean): Promise&lt;void&gt;
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.setMicrophoneMute(true).then(() =>
console.log('Promise returned to indicate that the microphone is muted.');
)
......@@ -885,6 +910,7 @@ isMicrophoneMute(callback: AsyncCallback&lt;boolean&gt;): void
**示例:**
```
var audioManager = audio.getAudioManager();
audioManager.isMicrophoneMute((err, value) => {
if (err) {
console.error('Failed to obtain the mute status of the microphone. ${err.message}');
......@@ -910,6 +936,7 @@ isMicrophoneMute(): Promise&lt;boolean&gt;
```
var audioManager = audio.getAudioManager();
audioManager.isMicrophoneMute().then((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
```
let myReason = 'test requestSuspendDelay';
let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => {
console.info("Request suspend delay will time out.");
console.info("Request suspension delay will time out.");
})
```
......
......@@ -10,6 +10,9 @@
import batteryInfo from '@ohos.batteryInfo';
```
## 系统能力
SystemCapability.PowerManager.BatteryManager
## 属性
......
......@@ -10,6 +10,9 @@
import brightness from '@ohos.brightness';
```
## 系统能力
SystemCapability.PowerManager.DisplayPowerManager
## brightness.setValue
......
......@@ -7,14 +7,9 @@
## 导入模块
```
import convertxml from '@ohos.convertxml'
import convertxml from '@ohos.convertxml';
```
## 权限
## ConvertXML
......@@ -48,7 +43,7 @@ convert(xml: string, options?: ConvertOptions) : Object
' <todo>Work</todo>' +
' <todo>Play</todo>' +
'</note>';
var conv= new convertxml.ConvertXML();
var conv = new convertxml.ConvertXML();
var result1 = conv.convert(xml, {trim: false, ignoreDeclaration: false});
console.log(result1)
```
......@@ -63,7 +58,7 @@ convert(xml: string, options?: ConvertOptions) : Object
| ignoreInstruction | boolean | 否 | 是否忽略xml的写入处理指令,默认false。 |
| ignoreAttributes | boolean | 否 | 是否跨多行打印属性并缩进属性,默认false。 |
| ignoreComment | boolean | 否 | 是否忽略元素的注释信息,默认false。 |
| ignoreCdata | boolean | 否 | 是否忽略元素的CData信息,默认false。 |
| ignoreCDATA | boolean | 否 | 是否忽略元素的CDATA信息,默认false。 |
| ignoreDoctype | boolean | 否 | 是否忽略元素的Doctype信息,默认false。 |
| ignoreText | boolean | 否 | 是否忽略元素的文本信息,默认false。 |
| declarationKey | string | 否 | 用于输出对象中declaration的属性键的名称,默认_declaration。 |
......
此差异已折叠。
# 目录环境能力
> ![icon-note.gif](D:/docs/zh-cn/application-dev/reference/apis/public_sys-resources/icon-note.gif) **说明:**
> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
## 导入模块
```
```js
import environment from '@ohos.environment';
```
## 系统能力
## 权限列表
SystemCapability.FileManagement.File.Environment
## environment.getStorageDataDir
......@@ -28,7 +27,7 @@ getStorageDataDir():Promise&lt;string&gt;
- 示例:
```
```js
environment.getStorageDataDir().then(function(path){
// do something
}).catch(function(error){
......@@ -50,7 +49,7 @@ getStorageDataDir(callback:AsyncCallback&lt;string&gt;):void
- 示例:
```
```js
environment.getStorageDataDir(function(error, path){
// do something
});
......@@ -70,7 +69,7 @@ getUserDataDir():Promise&lt;string&gt;
- 示例:
```
```js
environment.getUserDataDir().then(function(path){
// do something
}).catch(function(error){
......@@ -92,7 +91,7 @@ getUserDataDir(callback:AsyncCallback&lt;string&gt;): void
- 示例:
```
```js
environment.getUserDataDir(function(error, path){
// do something
});
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
......@@ -11,6 +11,11 @@ import reminderAgent from'@ohos.reminderAgent';
```
## 系统能力
SystemCapability.Notification.ReminderAgent
## 权限
ohos.permission.PUBLISH_AGENT_REMINDER
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册