提交 6b1e250c 编写于 作者: H honghecun 提交者: Gitee

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

......@@ -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)的编译。
......
......@@ -8,8 +8,13 @@
- [JavaScript-based Web-like Development Paradigm](ui/ui-arkui-js.md)
- [TypeScript-based Declarative Development Paradigm](ui/ui-arkui-ts.md)
- [Agent-Powered Scheduled Reminders ](background-agent-scheduled-reminder/Readme-EN.md)
- [Background Task Management ](background-task-management/Readme-EN.md)
- [Media](media/Readme-EN.md)
- [Security](security/Readme-EN.md)
- [IPC & RPC](connectivity/ipc-rpc.md)
- [Data Management](database/Readme-EN.md)
- [USB Service](usb/Readme-EN.md)
- [DFX](dfx/Readme-EN.md)
- [Development References](reference/Readme-EN.md)
- [JavaScript-based Web-like Development Paradigm](reference/arkui-js/Readme-EN.md)
......
# Agent-Powered Scheduled Reminders
- [Overview](background-agent-scheduled-reminder-overview.md)
- [Development Guidelines](background-agent-scheduled-reminder-guide.md)
# Overview<a name="EN-US_TOPIC_0000001139084594"></a>
Your application can call the **ReminderRequest** class to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background, even when your application is frozen or exits.
# Background Task Management
- [Background Task Management Overview](background-task-overview.md)
- [Background Task Management Development](background-task-dev-guide.md)
\ No newline at end of file
# 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.)
# Distributed Data Service
# Data Management
- [Distributed Data Service Overview](database-mdds-overview.md)
- [Distributed Data Service Development](database-mdds-guidelines.md)
- Distributed Data Service
- [Distributed Data Service Overview](database-mdds-overview.md)
- [Distributed Data Service Development](database-mdds-guidelines.md)
- Relational Database Overview
- [RDB Overview](database-relational-overview.md)
- [RDB Development](database-relational-guidelines.md)
- Lightweight Data Store
- [Lightweight Data Store Overview](database-preference-overview.md)
- [Lightweight Data Store Development](database-preference-guidelines.md)
\ No newline at end of file
# Lightweight Data Store Development<a name="EN-US_TOPIC_0000001230830543"></a>
## When to Use<a name="section13841104521714"></a>
The lightweight data store is ideal for storing lightweight and frequently used data, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Storage** APIs.
## Available APIs<a name="section15173156141712"></a>
The lightweight data store provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value pairs. Keys are of the string type, and values can be of the number, string, or Boolean type.
**Creating a Storage Instance**
Create a **Storage** instance for data operations. A **Storage** instance is created after data is read from a specified file and loaded to the instance.
**Table 1** API for creating a **Storage** instance
<a name="table17310132152415"></a>
<table><thead align="left"><tr id="row93118212413"><th class="cellrowborder" valign="top" width="17.69%" id="mcps1.2.4.1.1"><p id="p031118214242"><a name="p031118214242"></a><a name="p031118214242"></a>Package Name</p>
</th>
<th class="cellrowborder" valign="top" width="28.249999999999996%" id="mcps1.2.4.1.2"><p id="p19311326245"><a name="p19311326245"></a><a name="p19311326245"></a>Method</p>
</th>
<th class="cellrowborder" valign="top" width="54.059999999999995%" id="mcps1.2.4.1.3"><p id="p1131118252418"><a name="p1131118252418"></a><a name="p1131118252418"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row38631245202910"><td class="cellrowborder" valign="top" width="17.69%" headers="mcps1.2.4.1.1 "><p id="p8365103153013"><a name="p8365103153013"></a><a name="p8365103153013"></a>ohos.data.storage</p>
</td>
<td class="cellrowborder" valign="top" width="28.249999999999996%" headers="mcps1.2.4.1.2 "><p id="p1937481213019"><a name="p1937481213019"></a><a name="p1937481213019"></a>getStorage(path: string): Promise&lt;Storage&gt;;</p>
</td>
<td class="cellrowborder" valign="top" width="54.059999999999995%" headers="mcps1.2.4.1.3 "><p id="p4311132162417"><a name="p4311132162417"></a><a name="p4311132162417"></a>Obtains the <strong id="b193911821194211"><a name="b193911821194211"></a><a name="b193911821194211"></a>Storage</strong> singleton corresponding to a file for data operations.</p>
</td>
</tr>
</tbody>
</table>
**Writing Data**
Call the **put\(\)** method to add or modify data in a **Storage** instance.
**Table 2** API for writing data
<a name="table52021841142013"></a>
<table><thead align="left"><tr id="row2202741122013"><th class="cellrowborder" valign="top" width="19.79%" id="mcps1.2.4.1.1"><p id="p12161443377"><a name="p12161443377"></a><a name="p12161443377"></a>Class</p>
</th>
<th class="cellrowborder" valign="top" width="37%" id="mcps1.2.4.1.2"><p id="p172028414205"><a name="p172028414205"></a><a name="p172028414205"></a>Method</p>
</th>
<th class="cellrowborder" valign="top" width="43.21%" id="mcps1.2.4.1.3"><p id="p162020415205"><a name="p162020415205"></a><a name="p162020415205"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row8203194115202"><td class="cellrowborder" valign="top" width="19.79%" headers="mcps1.2.4.1.1 "><p id="p31644311712"><a name="p31644311712"></a><a name="p31644311712"></a>Storage</p>
</td>
<td class="cellrowborder" valign="top" width="37%" headers="mcps1.2.4.1.2 "><p id="p105961650131617"><a name="p105961650131617"></a><a name="p105961650131617"></a>put(key: string, value: ValueType): Promise&lt;void&gt;;</p>
</td>
<td class="cellrowborder" valign="top" width="43.21%" headers="mcps1.2.4.1.3 "><p id="p127261044489"><a name="p127261044489"></a><a name="p127261044489"></a>Writes data of the number, string, and Boolean types.</p>
</td>
</tr>
</tbody>
</table>
**Reading Data**
Call the **get\(\)** method to read data from a **Storage** instance.
**Table 3** API for reading data
<a name="table182143189350"></a>
<table><thead align="left"><tr id="row173241118123511"><th class="cellrowborder" valign="top" width="18.04%" id="mcps1.2.4.1.1"><p id="p94819229584"><a name="p94819229584"></a><a name="p94819229584"></a>Class</p>
</th>
<th class="cellrowborder" valign="top" width="37.830000000000005%" id="mcps1.2.4.1.2"><p id="p18324181853514"><a name="p18324181853514"></a><a name="p18324181853514"></a>Method</p>
</th>
<th class="cellrowborder" valign="top" width="44.13%" id="mcps1.2.4.1.3"><p id="p11324131814355"><a name="p11324131814355"></a><a name="p11324131814355"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row18325141813350"><td class="cellrowborder" valign="top" width="18.04%" headers="mcps1.2.4.1.1 "><p id="p1448113223583"><a name="p1448113223583"></a><a name="p1448113223583"></a>Storage</p>
</td>
<td class="cellrowborder" valign="top" width="37.830000000000005%" headers="mcps1.2.4.1.2 "><p id="p1335031410172"><a name="p1335031410172"></a><a name="p1335031410172"></a>get(key: string, defValue: ValueType): Promise&lt;ValueType&gt;;</p>
</td>
<td class="cellrowborder" valign="top" width="44.13%" headers="mcps1.2.4.1.3 "><p id="p11862123993920"><a name="p11862123993920"></a><a name="p11862123993920"></a>Reads data of the number, string, and Boolean types.</p>
</td>
</tr>
</tbody>
</table>
**Storing Data Persistently**
Call the **flush\(\)** method to write the cached data back to its text file for persistent storage.
**Table 4** API for data persistence
<a name="table1290414100219"></a>
<table><thead align="left"><tr id="row690412101627"><th class="cellrowborder" valign="top" width="18.04%" id="mcps1.2.4.1.1"><p id="p1390414101929"><a name="p1390414101929"></a><a name="p1390414101929"></a>Class</p>
</th>
<th class="cellrowborder" valign="top" width="37.830000000000005%" id="mcps1.2.4.1.2"><p id="p59045104215"><a name="p59045104215"></a><a name="p59045104215"></a>Method</p>
</th>
<th class="cellrowborder" valign="top" width="44.13%" id="mcps1.2.4.1.3"><p id="p1190416106210"><a name="p1190416106210"></a><a name="p1190416106210"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row99041710923"><td class="cellrowborder" valign="top" width="18.04%" headers="mcps1.2.4.1.1 "><p id="p7904101018217"><a name="p7904101018217"></a><a name="p7904101018217"></a>Storage</p>
</td>
<td class="cellrowborder" valign="top" width="37.830000000000005%" headers="mcps1.2.4.1.2 "><p id="p1290418101218"><a name="p1290418101218"></a><a name="p1290418101218"></a>flush(): Promise&lt;void&gt;;</p>
</td>
<td class="cellrowborder" valign="top" width="44.13%" headers="mcps1.2.4.1.3 "><p id="p1234935810316"><a name="p1234935810316"></a><a name="p1234935810316"></a>Writes data in the <strong id="b263252724411"><a name="b263252724411"></a><a name="b263252724411"></a>Storage</strong> instance back to its file through an asynchronous thread.</p>
</td>
</tr>
</tbody>
</table>
**Observing Data Changes**
Specify **StorageObserver** as the callback to subscribe to data changes. When the value of the subscribed key is changed and the **flush\(\)** method is executed, **StorageObserver** will be invoked.
**Table 5** APIs for subscribing to data changes
<a name="table6483954112110"></a>
<table><thead align="left"><tr id="row124847540217"><th class="cellrowborder" valign="top" width="17.849999999999998%" id="mcps1.2.4.1.1"><p id="p1210134212816"><a name="p1210134212816"></a><a name="p1210134212816"></a>Class</p>
</th>
<th class="cellrowborder" valign="top" width="42.34%" id="mcps1.2.4.1.2"><p id="p1848445472111"><a name="p1848445472111"></a><a name="p1848445472111"></a>Method</p>
</th>
<th class="cellrowborder" valign="top" width="39.81%" id="mcps1.2.4.1.3"><p id="p1848475414213"><a name="p1848475414213"></a><a name="p1848475414213"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row2048513546212"><td class="cellrowborder" valign="top" width="17.849999999999998%" headers="mcps1.2.4.1.1 "><p id="p17210342586"><a name="p17210342586"></a><a name="p17210342586"></a>Storage</p>
</td>
<td class="cellrowborder" valign="top" width="42.34%" headers="mcps1.2.4.1.2 "><p id="p124859540219"><a name="p124859540219"></a><a name="p124859540219"></a>on(type: 'change', callback: Callback&lt;StorageObserver&gt;): void;</p>
</td>
<td class="cellrowborder" valign="top" width="39.81%" headers="mcps1.2.4.1.3 "><p id="p1148505452114"><a name="p1148505452114"></a><a name="p1148505452114"></a>Subscribes to data changes.</p>
</td>
</tr>
<tr id="row24851554182111"><td class="cellrowborder" valign="top" width="17.849999999999998%" headers="mcps1.2.4.1.1 "><p id="p914241031014"><a name="p914241031014"></a><a name="p914241031014"></a>Storage</p>
</td>
<td class="cellrowborder" valign="top" width="42.34%" headers="mcps1.2.4.1.2 "><p id="p9929202151011"><a name="p9929202151011"></a><a name="p9929202151011"></a>off(type: 'change', callback: Callback&lt;StorageObserver&gt;): void;</p>
</td>
<td class="cellrowborder" valign="top" width="39.81%" headers="mcps1.2.4.1.3 "><p id="p54853548219"><a name="p54853548219"></a><a name="p54853548219"></a>Unsubscribes from data changes.</p>
</td>
</tr>
</tbody>
</table>
**Deleting Data**
Use the following APIs to delete a **Storage** instance or data file.
**Table 6** APIs for deleting data
<a name="table2445155152418"></a>
<table><thead align="left"><tr id="row164451856244"><th class="cellrowborder" valign="top" width="17.72%" id="mcps1.2.4.1.1"><p id="p8182648181513"><a name="p8182648181513"></a><a name="p8182648181513"></a>Package Name</p>
</th>
<th class="cellrowborder" valign="top" width="43.980000000000004%" id="mcps1.2.4.1.2"><p id="p184461952245"><a name="p184461952245"></a><a name="p184461952245"></a>Method</p>
</th>
<th class="cellrowborder" valign="top" width="38.3%" id="mcps1.2.4.1.3"><p id="p11446652246"><a name="p11446652246"></a><a name="p11446652246"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row1644616517249"><td class="cellrowborder" valign="top" width="17.72%" headers="mcps1.2.4.1.1 "><p id="p318244815153"><a name="p318244815153"></a><a name="p318244815153"></a>ohos.data.storage</p>
</td>
<td class="cellrowborder" valign="top" width="43.980000000000004%" headers="mcps1.2.4.1.2 "><p id="p194461457246"><a name="p194461457246"></a><a name="p194461457246"></a>deleteStorage(path: string): Promise&lt;void&gt;;</p>
</td>
<td class="cellrowborder" valign="top" width="38.3%" headers="mcps1.2.4.1.3 "><p id="p19291149141220"><a name="p19291149141220"></a><a name="p19291149141220"></a>Deletes a <strong id="b16577722115210"><a name="b16577722115210"></a><a name="b16577722115210"></a>Storage</strong> instance from the cache and deletes its file from the device.</p>
</td>
</tr>
<tr id="row64461551242"><td class="cellrowborder" valign="top" width="17.72%" headers="mcps1.2.4.1.1 "><p id="p1918314488153"><a name="p1918314488153"></a><a name="p1918314488153"></a>ohos.data.storage</p>
</td>
<td class="cellrowborder" valign="top" width="43.980000000000004%" headers="mcps1.2.4.1.2 "><p id="p134467513248"><a name="p134467513248"></a><a name="p134467513248"></a>removeStorageFromCache(path: string): Promise&lt;void&gt;;</p>
</td>
<td class="cellrowborder" valign="top" width="38.3%" headers="mcps1.2.4.1.3 "><p id="p164461159247"><a name="p164461159247"></a><a name="p164461159247"></a>Deletes a <strong id="b12971117115417"><a name="b12971117115417"></a><a name="b12971117115417"></a>Storage</strong> instance from the cache to release memory.</p>
</td>
</tr>
</tbody>
</table>
## How to Develop<a name="section146940394256"></a>
1. Import **@ohos.data.storage** and related modules to the development environment.
```
import dataStorage from '@ohos.data.storage'
import featureAbility from '@ohos.ability.featureAbility' // Used to obtain the file storage path.
```
2. Create a **Storage** instance.
Read the specified file and load its data to the **Storage** instance for data operations.
```
var context = featureAbility.getContext()
var path = await context.getFilesDir()
let promise = dataStorage.getStorage(path + '/mystore')
```
1. Write data.
Use the **put\(\)** method of the **Storage** class to write data to the cached **Storage** instance.
```
promise.then((storage) => {
let getPromise = storage.put('startup', 'auto') // Save data to the Storage instance.
getPromise.then(() => {
console.info("Put the value of startup successfully.")
}).catch((err) => {
console.info("Put the value of startup failed with err: " + err)
})
}).catch((err) => {
console.info("Get the storage failed")
})
```
1. Read data.
Use the **get\(\)** method of the **Storage** class to read data.
```
promise.then((storage) => {
let getPromise = storage.get('startup', 'default')
getPromise.then((value) => {
console.info("The value of startup is " + value)
}).catch((err) => {
console.info("Get the value of startup failed with err: " + err)
})
}).catch((err) => {
console.info("Get the storage failed")
})
```
1. Store data persistently.
Use the **flush** or **flushSync** method to flush data in the **Storage** instance to its file.
```
storage.flush();
```
2. Observe data changes.
Specify **StorageObserver** as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush\(\)** method is executed, **StorageObserver** will be invoked. Unregister the **StorageObserver** when it is no longer required.
```
promise.then((storage) => {
var observer = function (key) {
console.info("The key of " + key + " changed.")
}
storage.on('change', observer)
storage.putSync('startup', 'auto') // Modify data in the Storage instance.
storage.flushSync() // Trigger the StorageObserver callback.
storage.off(...change..., observer) // Unsubscribe from the data changes.
}).catch((err) => {
console.info("Get the storage failed")
})
```
1. Delete the specified file.
Use the **deleteStorage** method to delete the **Storage** singleton of the specified file from the memory, and delete the specified file, its backup file, and damaged files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored.
```
let promise = dataStorage.deleteStorage(path + '/mystore')
promise.then(() => {
console.info("Deleted successfully.")
}).catch((err) => {
console.info("Deleted failed with err: " + err)
})
```
# Lightweight Data Store Overview<a name="EN-US_TOPIC_0000001230752103"></a>
Lightweight data store is applicable to access and persistence operations on the data in key-value pairs. When an application accesses a lightweight **Storage** instance, data in the **Storage** instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files.
## Basic Concepts<a name="section1055404171115"></a>
- **Key-Value data structure**
A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified.
- **Non-relational database**
A database not in compliance with the atomicity, consistency, isolation, and durability \(ACID\) database management properties of relational data transactions. The data in a non-relational database is independent.
## Working Principles<a name="section682631371115"></a>
1. When an application loads data from a specified **Storage** file to a **Storage** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Storage** instance in the memory, till the application removes the instance from the memory or deletes the **Storage** file.
2. When obtaining a **Storage** instance, the application can read data from or write data to the instance. The data in the **Storage** instance can be flushed to its **Storage** file by calling the **flush** or **flushSync** method.
**Figure 1** How lightweight data store works<a name="fig1657785713509"></a>
![](figures/en-us_image_0000001199139454.png)
## Constraints<a name="section17243172883219"></a>
- **Storage** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Storage** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner.
- The key in the key-value pairs is of the string type. It cannot be empty or exceed 80 characters.
- If the value in the key-value pairs is of the string type, it can be empty or contain a maximum of 8192 characters.
# RDB Overview<a name="EN-US_TOPIC_0000001231030607"></a>
The relational database \(RDB\) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements.
## Basic Concepts<a name="section1063573420813"></a>
- **RDB**
A type of database based on the relational model of data. The RDB stores data in rows and columns. An RDB is also called RDB store.
- **Predicate**
A representation of the property or feature of a data entity, or the relationship between data entities. It is mainly used to define operation conditions.
- **Result set**
A set of query results used to access the data. You can access the required data in a result set in flexible modes.
- **SQLite database**
A lightweight open-source relational database management system that complies with Atomicity, Consistency, Isolation, and Durability \(ACID\).
## Working Principles<a name="section4810552814"></a>
The RDB provides a common operation interface for external systems. It uses the SQLite as the underlying persistent storage engine, which supports all SQLite database features.
**Figure 1** How RDB works<a name="fig1826214361535"></a>
![](figures/how-rdb-works.png "how-rdb-works")
## Default Settings<a name="section176091243121218"></a>
- The default database logging mode is write-ahead logging \(WAL\).
- The default database flush mode is Full mode.
- The default shared memory used by the OpenHarmony database is 2 MB.
## Constraints<a name="section929813398308"></a>
- A maximum of four connection pools can be connected to an RDB to manage read and write operations.
- To ensure data accuracy, the RDB supports only one write operation at a time.
# Media
- [Audio](audio.md)
- Audio
- [Audio Overview](audio-overview.md)
- [Audio Playback Development](audio-playback.md)
......
......@@ -2,127 +2,178 @@
## When to Use
You use audio playback APIs to convert audio data into audible analog signals, play the audio signals using output devices, and manage playback tasks.
You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks.
**Figure 1** Playback status
![](figures/playback-status.png "playback-status")
## Available APIs
**Table 1** APIs for audio playback
| API| Description|
| -------- | -------- |
| media.createAudioPlayer() | Creates an **AudioPlayer** instance.|
| AudioPlayer | Provides audio playback features. For details, see the table below.|
**Table 2** AudioPlayer methods
| Method| Description|
| -------- | -------- |
| release() | Releases audio resources.|
| play() | Starts audio playback.|
| pause() | Pauses playback.|
| stop() | Stops playback.|
| reset()<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)
......
......@@ -9,13 +9,14 @@
- Event Notification
- [CommonEvent Module](js-apis-commonEvent.md)
- [Notification Module](js-apis-notification.md)
- [Reminder Agent](js-apis-reminderAgent.md)
- Resource Management
- [Resource Manager](js-apis-resource-manager.md)
- [Internationalization \(intl\) ](js-apis-intl.md)
- [Internationalization \(i18n\) ](js-apis-i18n.md)
- Media
- [Audio Management](js-apis-audio.md)
- [Media Playback and Recording](js-apis-media.md)
- [Media](js-apis-media.md)
- Security
- [User Authentication](js-apis-useriam-userauth.md)
- Data Management
......@@ -63,6 +64,9 @@
- Language Base Class Library
- [Obtaining Process Information](js-apis-process.md)
- [URL String Parsing](js-apis-url.md)
- [URI String Parsing](js-apis-uri.md)
- [Util](js-apis-util.md)
- [XML Parsing and Generation](js-apis-xml.md)
- [XML-to-JavaScript Conversion](js-apis-convertxml.md)
- [Worker Startup](js-apis-worker.md)
# Context Module
## Applicable Devices
| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device|
| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ |
| Context.getOrCreateLocalDir(callback: AsyncCallback\<string>) | Yes| Yes| Yes| Yes| No| No|
| Context.getOrCreateLocalDir() | Yes| Yes| Yes| Yes| No| No|
| Context.verifyPermission(permission: string, options: PermissionOptions, callback: AsyncCallback\<number>) | Yes| Yes| Yes| Yes| No| No|
| Context.verifyPermission(permission: string, callback: AsyncCallback\<number>) | Yes| Yes| Yes| Yes| No| No|
| Context.verifyPermission(permission: string, options?: PermissionOptions) | Yes| Yes| Yes| Yes| No| No|
| Context.requestPermissionsFromUser(permissions: Array\<string>, requestCode: number, resultCallback: AsyncCallback\<PermissionRequestResult>) | Yes| Yes| Yes| Yes| No| No|
| Context.getApplicationInfo(callback: AsyncCallback\<ApplicationInfo>) | Yes| Yes| Yes| Yes| No| No|
| Context.getApplicationInfo() | Yes| Yes| Yes| Yes| No| No|
| Context.getBundleName(callback: AsyncCallback\<string>) | Yes| Yes| Yes| Yes| No| No|
| Context.getBundleName() | Yes| Yes| Yes| Yes| No| No|
| Context.getProcessInfo(callback: AsyncCallback\<ProcessInfo>) | Yes| Yes| Yes| Yes| No| No|
| Context.getProcessInfo() | Yes| Yes| Yes| Yes| No| No|
| Context.getElementName(callback: AsyncCallback\<ElementName>) | Yes| Yes| Yes| Yes| No| No|
| Context.getElementName() | Yes| Yes| Yes| Yes| No| No|
| Context.getProcessName(callback: AsyncCallback\<string>) | Yes| Yes| Yes| Yes| No| No|
| Context.getProcessName() | Yes| Yes| Yes| Yes| No| No|
| Context.getCallingBundle(callback: AsyncCallback\<string>) | Yes| Yes| Yes| Yes| No| No|
| Context.getCallingBundle() | Yes| Yes| Yes| Yes| No| No|
## Modules to Import
```js
......
# 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.|
# Brightness<a name="EN-US_TOPIC_0000001152548786"></a>
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import<a name="s56d19203690d4782bfc74069abb6bd71"></a>
......@@ -9,6 +9,10 @@
import brightness from '@ohos.brightness';
```
## System Capabilities
SystemCapability.PowerManager.DisplayPowerManager
## brightness.setValue<a name="section1853612361618"></a>
setValue\(value: number\)
......
......@@ -3,17 +3,6 @@
**Note:**
The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Applicable Devices
| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable|
| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- |
| CommonEvent.publish(event: string, callback: AsyncCallback\<void>) | Yes| Yes| Yes| Yes| No|
| CommonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\<void>) | Yes| Yes| Yes| Yes| No|
| CommonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\<CommonEventSubscriber>) | Yes| Yes| Yes| Yes| No|
| CommonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Yes| Yes| Yes| Yes| No|
| CommonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\<CommonEventData>) | Yes| Yes| Yes| Yes| No|
| CommonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\<void>) | Yes| Yes| Yes| Yes| No|
## Required Permissions
| Common Event Macro| Common Event Name| Subscriber Permissions|
......
此差异已折叠。
### DataAbilityHelper Module (JavaScript SDK APIs)
#### Applicable Devices
| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device|
| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ |
| DataAbilityHelper.openFile(uri: string, mode: string, callback: AsyncCallback\<number>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.openFile(uri: string, mode: string) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.on(type: 'dataChange', uri: string, callback: AsyncCallback\<void>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.off(type: 'dataChange', uri: string, callback?: AsyncCallback\<void>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array\<string>>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.getFileTypes(uri: string, mimeTypeFilter: string) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.getType(uri: string, callback: AsyncCallback\<string>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.getType(uri: string) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.normalizeUri(uri: string, callback: AsyncCallback\<string>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.normalizeUri(uri: string) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.denormalizeUri(uri: string, callback: AsyncCallback\<string>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.denormalizeUri(uri: string) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.notifyChange(uri: string, callback: AsyncCallback\<void>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.notifyChange(uri: string) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\<number>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.insert(uri: string, valuesBucket: rdb.ValuesBucket) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.batchInsert(uri: string, valuesBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback\<number>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.batchInsert(uri: string, valuesBuckets: Array<rdb.ValuesBucket>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.delete(uri: string, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<number>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.query(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\<ResultSet>) | Yes| Yes| Yes| Yes| No| No|
| DataAbilityHelper.query(uri: string, columns: Array\<string>, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No|
# DataAbilityHelper Module (JavaScript SDK APIs)
#### Modules to Import
......
# 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.|
# FeatureAbility Module (JavaScript)
#### Applicable Devices
| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device|
| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ |
| FeatureAbility.startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\<number>): void | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.startAbility(parameter: StartAbilityParameter): Promise\<number> | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.acquireDataAbilityHelper(uri: string): DataAbilityHelper | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\<AbilityResult>): void | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.startAbilityForResult(parameter: StartAbilityParameter): Promise\<AbilityResult> | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\<void>): void | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.terminateSelfWithResult(parameter: AbilityResult): Promise\<void> | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.hasWindowFocus(callback: AsyncCallback\<boolean>): void | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.hasWindowFocus(): Promise\<boolean> | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.getWant(callback: AsyncCallback\<Want>) | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.getWant(): void | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.getContext(): Context | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.terminateSelf(callback: AsyncCallback\<void>): void | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.terminateSelf(): Promise\<void> | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.connectAbility(request: Want, options:ConnectOptions): number | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.disconnectAbility(connection: number, callback:AsyncCallback\<void>): void | Yes| Yes| Yes| Yes| No| No|
| FeatureAbility.disconnectAbility(connection: number): Promise\<void> | Yes| Yes| Yes| Yes| No| No|
#### Constraints
APIs of the **FeatureAbility** module can be called only by Page abilities.
......
# FormBindingData
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```
import formBindingData from '@ohos.application.formBindingData';
```
## Required Permissions
None
## formBindingData.createFormBindingData
createFormBindingData(obj?: Object | string): FormBindingData
Creates a **FormBindingData** object.
- Parameters
| Name| Type| Mandatory| Description|
| ------ | -------------- | ---- | ------------------------------------------------------------ |
| obj | Object or string| No| Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.|
- Return value
| Type| Description|
| ----------------------------------- | --------------------------------------- |
| [FormBindingData](#formbindingdata) | **FormBindingData** object created based on the passed data.|
- Example
```
let obj = {"temperature": "21°"};
let formBindingDataObj = formBindingData.createFormBindingData(obj);
```
## FormBindingData
Describes a **FormBindingData** object.
| Name| Type| Description|
| ---- | -------------- | ------------------------------------------------------------ |
| obj | Object or string| Data to be displayed on the JS service widget. The value can be an object containing multiple key-value pairs or a string in JSON format.|
# FormExtension
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Provides **FormExtension** APIs.
## Modules to Import
```
import FormExtension from '@ohos.application.FormExtension';
```
## Required Permissions
None
## Attributes
| Name| Type| Readable| Writable| Description|
| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- |
| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes| No| Context of the **FormExtension**. This class is inherited from **ExtensionContext**.|
## onCreate
onCreate(want: Want): formBindingData.FormBindingData
Called to notify the widget provider that a **Form** instance (widget) has been created.
- Parameters
| Name| Type| Mandatory| Description|
| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ |
| want | [Want](js-apis-featureAbility.md#want) | Yes| Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.|
- Return value
| Type| Description|
| ------------------------------------------------------------ | ----------------------------------------------------------- |
| [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.|
- Example
```
onCreate(want) {
console.log('FormExtension onCreate, want:' + want.abilityName);
let dataObj1 = {
temperature:"11c",
"time":"11:00"
};
let obj1 = formBindingData.createFormBindingData(dataObj1);
return obj1;
}
```
## onCastToNormal
onCastToNormal(formId: string): void
Called to notify the widget provider that a temporary widget has been converted to a normal one.
- Parameters
| Name| Type| Mandatory| Description|
| ------ | ------ | ---- | ------------------------ |
| formId | string | Yes| ID of the widget that requests to be converted to a normal one.|
- Example
```
onCastToNormal(formId) {
console.log('FormExtension onCastToNormal, formId:' + formId);
}
```
## onUpdate
onUpdate(formId: string): void
Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-formextensioncontext.md) class to update the widget data.
- Parameters
| Name| Type| Mandatory| Description|
| ------ | ------ | ---- | ------------------ |
| formId | string | Yes| ID of the widget that requests to be updated.|
- Example
```
onUpdate(formId) {
console.log('FormExtension onUpdate, formId:' + formId);
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
this.context.updateForm(formId, obj2)
.then((data)=>{
console.log('FormExtension context updateForm, data:' + data);
}).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);});
}
```
## onVisibilityChange
onVisibilityChange(newStatus: { [key: string]: number }): void
Called to notify the widget provider of the change of visibility.
- Parameters
| Name| Type| Mandatory| Description|
| --------- | ------------------------- | ---- | ---------------------------- |
| newStatus | { [key: string]: number } | Yes| ID and visibility status of the widget to be changed.|
- Example
```
onVisibilityChange(newStatus) {
console.log('FormExtension onVisibilityChange, newStatus:' + newStatus);
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
for (let key in newStatus) {
console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]);
this.context.updateForm(key, obj2)
.then((data)=>{
console.log('FormExtension context updateForm, data:' + data);
}).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);});
}
}
```
## onEvent
onEvent(formId: string, message: string): void
Called to instruct the widget provider to receive and process the widget event.
- Parameters
| Name| Type| Mandatory| Description|
| ------- | ------ | ---- | ---------------------- |
| formId | string | Yes| ID of the widget that requests the event.|
| message | string | Yes| Event message.|
- Example
```
onEvent(formId, message) {
console.log('FormExtension onEvent, formId:' + formId + ", message:" + message);
}
```
## onDestroy
onDestroy(formId: string): void
Called to notify the widget provider that a **Form** instance (widget) has been destroyed.
- Parameters
| Name| Type| Mandatory| Description|
| ------ | ------ | ---- | ------------------ |
| formId | string | Yes| ID of the widget to be destroyed.|
- Example
```
onDestroy(formId) {
console.log('FormExtension onDestroy, formId:' + formId);
}
```
# FormExtensionContext
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Implements the context that provides the capabilities and APIs of **FormExtension**. This class is inherited from **ExtensionContext**.
## updateForm
updateForm(formId: string, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\<void>): void
Updates a widget. This method uses a callback to return the result.
- Parameters
| Name| Type| Mandatory| Description|
| --------------- | ------------------------------------------------------------ | ---- | -------------------------------------- |
| formId | string | Yes| ID of the widget that requests to be updated.|
| formBindingData | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes| New data of the widget.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result indicating whether the method is successfully called.|
- Example
```
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
this.context.updateForm(formId, obj2, (data)=>{
console.log('FormExtension context updateForm, data:' + data);
});
```
## updateForm
updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise\<void>
Updates a widget. This method uses a promise to return the result.
- Parameters
| Name| Type| Mandatory| Description|
| --------------- | ------------------------------------------------------------ | ---- | ------------------ |
| formId | string | Yes| ID of the widget that requests to be updated.|
| formBindingData | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes| New data of the widget.|
- Return value
| Type| Description|
| -------------- | --------------------------------- |
| Promise\<void> | Promise returned with the result indicating whether the method is successfully called.|
- Example
```
let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"});
this.context.updateForm(formId, obj2)
.then((data)=>{
console.log('FormExtension context updateForm, data:' + data);
}).catch((error) => {
console.error('Operation updateForm failed. Cause: ' + error);});
```
# Notification Module
## Applicable Devices
| API | Phone | Tablet | Smart TV | Wearable |
| ------------------------------------------------------------ | ---- | ---- | ------ | -------- |
| Notification.publish(request: NotificationRequest, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.publish(request: NotificationRequest) | Yes | Yes | Yes | Yes |
| Notification.cancel(id: number, label: string, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.cancel(id:number, label?:string) | Yes | Yes | Yes | Yes |
| Notification.cancel(id: number, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.cancelAll(callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.cancelAll() | Yes | Yes | Yes | Yes |
| Notification.addSlot(slot: NotificationSlot, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.addSlot(slot: NotificationSlot) | Yes | Yes | Yes | Yes |
| Notification.addSlot(type: SlotType, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.addSlot(type: SlotType) | Yes | Yes | Yes | Yes |
| Notification.addSlots(slots: Array\<NotificationSlot\>, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.addSlots(slots: Array\<NotificationSlot\>) | Yes | Yes | Yes | Yes |
| Notification.getSlot(slotType: SlotType, callback: AsyncCallback\<NotificationSlot\>) | Yes | Yes | Yes | Yes |
| Notification.getSlot(slotType: SlotType) | Yes | Yes | Yes | Yes |
| Notification.getSlots(callback: AsyncCallback<Array\<NotificationSlot\>>) | Yes | Yes | Yes | Yes |
| Notification.getSlots() | Yes | Yes | Yes | Yes |
| Notification.removeSlot(slotType: SlotType, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.removeSlot(slotType: SlotType) | Yes | Yes | Yes | Yes |
| Notification.removeAllSlots(callback: AsyncCallback\<void\>): void | Yes | Yes | Yes | Yes |
| Notification.removeAllSlots(): Promise\<void\> | Yes | Yes | Yes | Yes |
| Notification.subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo) | Yes | Yes | Yes | Yes |
| Notification.unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.unsubscribe(subscriber: NotificationSubscriber) | Yes | Yes | Yes | Yes |
| Notification.enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.enableNotification(bundle: BundleOption, enable: boolean) | Yes | Yes | Yes | Yes |
| Notification.isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\<boolean\>) | Yes | Yes | Yes | Yes |
| Notification.isNotificationEnabled(bundle: BundleOption) | Yes | Yes | Yes | Yes |
| Notification.isNotificationEnabled(callback: AsyncCallback\<boolean\>) | Yes | Yes | Yes | Yes |
| Notification.isNotificationEnabled() | Yes | Yes | Yes | Yes |
| Notification.displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.displayBadge(bundle: BundleOption, enable: boolean) | Yes | Yes | Yes | Yes |
| Notification.isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\<boolean\>) | Yes | Yes | Yes | Yes |
| Notification.isBadgeDisplayed(bundle: BundleOption) | Yes | Yes | Yes | Yes |
| Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot) | Yes | Yes | Yes | Yes |
| Notification.getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback<Array\<NotificationSlot\>>) | Yes | Yes | Yes | Yes |
| Notification.getSlotsByBundle(bundle: BundleOption) | Yes | Yes | Yes | Yes |
| Notification.getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\<number\>) | Yes | Yes | Yes | Yes |
| Notification.getSlotNumByBundle(bundle: BundleOption) | Yes | Yes | Yes | Yes |
| Notification.remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.remove(bundle: BundleOption, notificationKey: NotificationKey) | Yes | Yes | Yes | Yes |
| Notification.remove(hashCode: string, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.remove(hashCode: string) | Yes | Yes | Yes | Yes |
| Notification.removeAll(bundle: BundleOption, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.removeAll(callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.removeAll(bundle?: BundleOption) | Yes | Yes | Yes | Yes |
| Notification.getAllActiveNotifications(callback: AsyncCallback<Array\<NotificationRequest\>>) | Yes | Yes | Yes | Yes |
| Notification.getAllActiveNotifications() | Yes | Yes | Yes | Yes |
| Notification.getActiveNotificationCount(callback: AsyncCallback\<number\>) | Yes | Yes | Yes | Yes |
| Notification.getActiveNotificationCount() | Yes | Yes | Yes | Yes |
| Notification.getActiveNotifications(callback: AsyncCallback<Array\<NotificationRequest\>>) | Yes | Yes | Yes | Yes |
| Notification.getActiveNotifications() | Yes | Yes | Yes | Yes |
| Notification.cancelGroup(groupName: string, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.cancelGroup(groupName: string) | Yes | Yes | Yes | Yes |
| Notification.removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.removeGroupByBundle(bundle: BundleOption, groupName: string) | Yes | Yes | Yes | Yes |
| Notification.setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| Notification.setDoNotDisturbDate(date: DoNotDisturbDate) | Yes | Yes | Yes | Yes |
| Notification.getDoNotDisturbDate(callback: AsyncCallback\<DoNotDisturbDate\>) | Yes | Yes | Yes | Yes |
| Notification.getDoNotDisturbDate() | Yes | Yes | Yes | Yes |
| Notification.supportDoNotDisturbMode(callback: AsyncCallback\<boolean\>) | Yes | Yes | Yes | Yes |
| Notification.supportDoNotDisturbMode() | Yes | Yes | Yes | Yes |
| WantAgent.getWantAgent(info: WantAgentInfo, callback: AsyncCallback\<WantAgent\>) | Yes | Yes | Yes | Yes |
| WantAgent.getWantAgent(info: WantAgentInfo): Promise\<WantAgent\> | Yes | Yes | Yes | Yes |
| WantAgent.getBundleName(agent: WantAgent, callback: AsyncCallback\<string\>) | Yes | Yes | Yes | Yes |
| WantAgent.getBundleName(agent: WantAgent): Promise\<string\> | Yes | Yes | Yes | Yes |
| WantAgent.getUid(agent: WantAgent, callback: AsyncCallback\<number\>) | Yes | Yes | Yes | Yes |
| WantAgent.getUid(agent: WantAgent): Promise\<number\> | Yes | Yes | Yes | Yes |
| WantAgent.getWant(agent: WantAgent, callback: AsyncCallback\<Want\>) | Yes | Yes | Yes | Yes |
| WantAgent.getWant(agent: WantAgent): Promise\<Want\> | Yes | Yes | Yes | Yes |
| WantAgent.cancel(agent: WantAgent, callback: AsyncCallback\<void\>) | Yes | Yes | Yes | Yes |
| WantAgent.cancel(agent: WantAgent): Promise\<void\> | Yes | Yes | Yes | Yes |
| WantAgent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\<CompleteData\>) | Yes | Yes | Yes | Yes |
| WantAgent.equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\<boolean\>) | Yes | Yes | Yes | Yes |
| WantAgent.equal(agent: WantAgent, otherAgent: WantAgent): Promise\<boolean\> | Yes | Yes | Yes | Yes |
## Required Permissions
......
# ParticleAbility Module
## Applicable Devices
| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device|
| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ |
| particleAbility.startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\<void>: void | Yes| Yes| Yes| Yes| No| No|
| particleAbility.startAbility(parameter: StartAbilityParameter): Promise\<number> | Yes| Yes| Yes| Yes| No| No|
| particleAbility.terminateSelf(callback: AsyncCallback\<void>): void | Yes| Yes| Yes| Yes| No| No|
| particleAbility.terminateSelf(): Promise\<void> | Yes| Yes| Yes| Yes| No| No|
| particleAbility.acquireDataAbilityHelper(uri: string): DataAbilityHelper | Yes| Yes| Yes| Yes| No| No|
| particleAbility.connectAbility(request: Want, options:ConnectOptions): number | Yes| Yes| Yes| Yes| No| No|
| particleAbility.disconnectAbility(connection: number, callback:AsyncCallback\<void>): void | Yes| Yes| Yes| Yes| No| No|
| particleAbility.disconnectAbility(connection: number): Promise\<void> | Yes| Yes| Yes| Yes| No| No|
## Constraints
The ParticleAbility module is used to perform operations on abilities of the Data and Service types.
......
# Resource Manager<a name="EN-US_TOPIC_0000001200042191"></a>
# Resource Manager<a name="EN-US_TOPIC_0000001192428610"></a>
>![](../../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<a name="s56d19203690d4782bfc74069abb6bd71"></a>
```
......@@ -362,8 +362,6 @@ Enumerates screen density types.
Provides the device configuration.
### Attributes<a name="section254242964810"></a>
<a name="table1459620431636"></a>
<table><thead align="left"><tr id="row25971143435"><th class="cellrowborder" valign="top" width="15.870000000000001%" id="mcps1.1.6.1.1"><p id="p1559716434320"><a name="p1559716434320"></a><a name="p1559716434320"></a>Name</p>
</th>
......@@ -406,8 +404,6 @@ Provides the device configuration.
Provides the device capability.
### Attributes<a name="section2201153419440"></a>
<a name="table16201103444414"></a>
<table><thead align="left"><tr id="row620123444415"><th class="cellrowborder" valign="top" width="15.870000000000001%" id="mcps1.1.6.1.1"><p id="p1620163494418"><a name="p1620163494418"></a><a name="p1620163494418"></a>Name</p>
</th>
......@@ -450,6 +446,10 @@ Provides the device capability.
Provides the capability of accessing application resources.
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>- The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm.
>- Resource files are defined in the **resources** directory of the project. You can obtain the resource ID from **$r\(resource address\).id**, for example, **$r\(?app.string.test?\).id**.
### getString<a name="section9779153419548"></a>
getString\(resId: number, callback: AsyncCallback<string\>\): void
......@@ -494,7 +494,7 @@ Obtains the string corresponding to the specified resource ID. This method uses
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getString(0x1000000, (error, value) => {
mgr.getString($r('app.string.test').id, (error, value) => {
if (error != null) {
console.log(value);
} else {
......@@ -557,7 +557,7 @@ Obtains the string corresponding to the specified resource ID. This method uses
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getString(0x1000000).then(value => {
mgr.getString($r('app.string.test').id).then(value => {
console.log(value);
}).catch(error => {
console.log("getstring promise " + error);
......@@ -610,7 +610,7 @@ Obtains the array of strings corresponding to the specified resource ID. This me
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getStringArray(0x1000000, (error, value) => {
mgr.getStringArray($r('app.strarray.test').id, (error, value) => {
if (error != null) {
console.log(value);
} else {
......@@ -663,7 +663,7 @@ Obtains the array of strings corresponding to the specified resource ID. This me
</thead>
<tbody><tr id="row119261820145419"><td class="cellrowborder" valign="top" width="20.05%" headers="mcps1.1.3.1.1 "><p id="p179309445393"><a name="p179309445393"></a><a name="p179309445393"></a>Promise&lt;Array&lt;string&gt;&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="79.95%" headers="mcps1.1.3.1.2 "><p id="p139301144153915"><a name="p139301144153915"></a><a name="p139301144153915"></a>Array of character strings corresponding to the specified resource ID.</p>
<td class="cellrowborder" valign="top" width="79.95%" headers="mcps1.1.3.1.2 "><p id="p139301144153915"><a name="p139301144153915"></a><a name="p139301144153915"></a>Array of strings corresponding to the specified resource ID.</p>
</td>
</tr>
</tbody>
......@@ -673,7 +673,7 @@ Obtains the array of strings corresponding to the specified resource ID. This me
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getStringArray(0x1000000).then(value => {
mgr.getStringArray($r('app.strarray.test').id).then(value => {
console.log(value);
}).catch(error => {
console.log("getstring promise " + error);
......@@ -712,7 +712,7 @@ Obtains the content of the media file corresponding to the specified resource ID
</tr>
<tr id="row1971112524019"><td class="cellrowborder" valign="top" width="7.901402961808262%" headers="mcps1.1.5.1.1 "><p id="p27111125204017"><a name="p27111125204017"></a><a name="p27111125204017"></a>callback</p>
</td>
<td class="cellrowborder" valign="top" width="25.565081839438818%" headers="mcps1.1.5.1.2 "><p id="p1371152514409"><a name="p1371152514409"></a><a name="p1371152514409"></a>AsyncCallback&lt;Array&lt;Uint8Array&gt;&gt;</p>
<td class="cellrowborder" valign="top" width="25.565081839438818%" headers="mcps1.1.5.1.2 "><p id="p1371152514409"><a name="p1371152514409"></a><a name="p1371152514409"></a>AsyncCallback&lt;Uint8Array&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="6.819953234606392%" headers="mcps1.1.5.1.3 "><p id="p13711625124019"><a name="p13711625124019"></a><a name="p13711625124019"></a>Yes</p>
</td>
......@@ -726,7 +726,7 @@ Obtains the content of the media file corresponding to the specified resource ID
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getMedia(0x1000000, (error, value) => {
mgr.getMedia($r('app.media.test').id, (error, value) => {
if (error != null) {
console.log(value);
} else {
......@@ -777,7 +777,7 @@ Obtains the content of the media file corresponding to the specified resource ID
</th>
</tr>
</thead>
<tbody><tr id="row9713142554012"><td class="cellrowborder" valign="top" width="23.02%" headers="mcps1.1.3.1.1 "><p id="p1071352554019"><a name="p1071352554019"></a><a name="p1071352554019"></a>Promise&lt;Array&lt;Uint8Array&gt;&gt;</p>
<tbody><tr id="row9713142554012"><td class="cellrowborder" valign="top" width="23.02%" headers="mcps1.1.3.1.1 "><p id="p1071352554019"><a name="p1071352554019"></a><a name="p1071352554019"></a>Promise&lt;Uint8Array&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="76.98%" headers="mcps1.1.3.1.2 "><p id="p8713192517405"><a name="p8713192517405"></a><a name="p8713192517405"></a>Promise used to return the content of the obtained media file.</p>
</td>
......@@ -789,7 +789,7 @@ Obtains the content of the media file corresponding to the specified resource ID
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getMedia(0x1000000).then(value => {
mgr.getMedia($r('app.media.test').id).then(value => {
console.log(value);
}).catch(error => {
console.log("getstring promise " + error);
......@@ -842,7 +842,7 @@ Obtains the Base64 code of the image corresponding to the specified resource ID.
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getMediaBase64(0x1000000, (error, value) => {
mgr.getMediaBase64($r('app.media.test').id, (error, value) => {
if (error != null) {
console.log(value);
} else {
......@@ -905,7 +905,7 @@ Obtains the Base64 code of the image corresponding to the specified resource ID.
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getMediaBase64(0x1000000).then(value => {
mgr.getMediaBase64($r('app.media.test').id).then(value => {
console.log(value);
}).catch(error => {
console.log("getstring promise " + error);
......@@ -1131,7 +1131,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getPluralString(0x1000000, 1, (error, value) => {
mgr.getPluralString($r("app.plural.test").id, 1, (error, value) => {
if (error != null) {
console.log(value);
} else {
......@@ -1203,7 +1203,7 @@ Obtains the specified number of singular-plural strings corresponding to the spe
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getPluralString(0x1000000, 1).then(value => {
mgr.getPluralString($r("app.plural.test").id, 1).then(value => {
console.log(value);
}).catch(error => {
console.log("getstring promise " + error);
......@@ -1212,3 +1212,118 @@ Obtains the specified number of singular-plural strings corresponding to the spe
```
### getRawFile<sup>8+</sup><a name="section95073471466"></a>
getRawFile\(path: string, callback: AsyncCallback<Uint8Array\>\): void
Obtains the content of rawfile in the specified path. This method uses an asynchronous callback to return the result.
- Parameters
<a name="table15072471264"></a>
<table><thead align="left"><tr id="row1550784715616"><th class="cellrowborder" valign="top" width="7.901402961808262%" id="mcps1.1.5.1.1"><p id="p1650720473611"><a name="p1650720473611"></a><a name="p1650720473611"></a>Name</p>
</th>
<th class="cellrowborder" valign="top" width="25.565081839438818%" id="mcps1.1.5.1.2"><p id="p1850710478614"><a name="p1850710478614"></a><a name="p1850710478614"></a>Type</p>
</th>
<th class="cellrowborder" valign="top" width="6.819953234606392%" id="mcps1.1.5.1.3"><p id="p7508247962"><a name="p7508247962"></a><a name="p7508247962"></a>Mandatory</p>
</th>
<th class="cellrowborder" valign="top" width="59.713561964146535%" id="mcps1.1.5.1.4"><p id="p1250816471565"><a name="p1250816471565"></a><a name="p1250816471565"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row205084473617"><td class="cellrowborder" valign="top" width="7.901402961808262%" headers="mcps1.1.5.1.1 "><p id="p12508144716615"><a name="p12508144716615"></a><a name="p12508144716615"></a>path</p>
</td>
<td class="cellrowborder" valign="top" width="25.565081839438818%" headers="mcps1.1.5.1.2 "><p id="p45085471768"><a name="p45085471768"></a><a name="p45085471768"></a>string</p>
</td>
<td class="cellrowborder" valign="top" width="6.819953234606392%" headers="mcps1.1.5.1.3 "><p id="p1150834716613"><a name="p1150834716613"></a><a name="p1150834716613"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="59.713561964146535%" headers="mcps1.1.5.1.4 "><p id="p950814719617"><a name="p950814719617"></a><a name="p950814719617"></a>Path of the rawfile.</p>
</td>
</tr>
<tr id="row145082471163"><td class="cellrowborder" valign="top" width="7.901402961808262%" headers="mcps1.1.5.1.1 "><p id="p145081347867"><a name="p145081347867"></a><a name="p145081347867"></a>callback</p>
</td>
<td class="cellrowborder" valign="top" width="25.565081839438818%" headers="mcps1.1.5.1.2 "><p id="p550814471615"><a name="p550814471615"></a><a name="p550814471615"></a>AsyncCallback&lt;Uint8Array&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="6.819953234606392%" headers="mcps1.1.5.1.3 "><p id="p1450884713612"><a name="p1450884713612"></a><a name="p1450884713612"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="59.713561964146535%" headers="mcps1.1.5.1.4 "><p id="p150864719611"><a name="p150864719611"></a><a name="p150864719611"></a> Asynchronous callback used to return the rawfile content, in byte arrays.</p>
</td>
</tr>
</tbody>
</table>
- Example
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getRawFile("test.xml", (error, value) => {
if (error != null) {
console.log(value);
} else {
console.log(value);
}
});
});
```
### getRawFile<sup>8+</sup><a name="section53115315102"></a>
getRawFile\(path: string\): Promise<Uint8Array\>
Obtains the content of the rawfile in the specified path. This method uses a promise to return the result.
- Parameters
<a name="table73111831141015"></a>
<table><thead align="left"><tr id="row1311143131013"><th class="cellrowborder" valign="top" width="14.82%" id="mcps1.1.5.1.1"><p id="p1631163171011"><a name="p1631163171011"></a><a name="p1631163171011"></a>Name</p>
</th>
<th class="cellrowborder" valign="top" width="14.729999999999999%" id="mcps1.1.5.1.2"><p id="p431193191013"><a name="p431193191013"></a><a name="p431193191013"></a>Type</p>
</th>
<th class="cellrowborder" valign="top" width="9.16%" id="mcps1.1.5.1.3"><p id="p131114317106"><a name="p131114317106"></a><a name="p131114317106"></a>Mandatory</p>
</th>
<th class="cellrowborder" valign="top" width="61.29%" id="mcps1.1.5.1.4"><p id="p1531211312104"><a name="p1531211312104"></a><a name="p1531211312104"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row1331263131011"><td class="cellrowborder" valign="top" width="14.82%" headers="mcps1.1.5.1.1 "><p id="p1531223111011"><a name="p1531223111011"></a><a name="p1531223111011"></a>path</p>
</td>
<td class="cellrowborder" valign="top" width="14.729999999999999%" headers="mcps1.1.5.1.2 "><p id="p173121931151016"><a name="p173121931151016"></a><a name="p173121931151016"></a>string</p>
</td>
<td class="cellrowborder" valign="top" width="9.16%" headers="mcps1.1.5.1.3 "><p id="p12312173118102"><a name="p12312173118102"></a><a name="p12312173118102"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="61.29%" headers="mcps1.1.5.1.4 "><p id="p13312163141013"><a name="p13312163141013"></a><a name="p13312163141013"></a>Path of the rawfile.</p>
</td>
</tr>
</tbody>
</table>
- Return values
<a name="table6312113112103"></a>
<table><thead align="left"><tr id="row12312231101015"><th class="cellrowborder" valign="top" width="34.339999999999996%" id="mcps1.1.3.1.1"><p id="p19312173112109"><a name="p19312173112109"></a><a name="p19312173112109"></a>Type</p>
</th>
<th class="cellrowborder" valign="top" width="65.66%" id="mcps1.1.3.1.2"><p id="p1431223161016"><a name="p1431223161016"></a><a name="p1431223161016"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row12312431151011"><td class="cellrowborder" valign="top" width="34.339999999999996%" headers="mcps1.1.3.1.1 "><p id="p14312113119102"><a name="p14312113119102"></a><a name="p14312113119102"></a>Promise&lt;Uint8Array&gt;</p>
</td>
<td class="cellrowborder" valign="top" width="65.66%" headers="mcps1.1.3.1.2 "><p id="p43128317109"><a name="p43128317109"></a><a name="p43128317109"></a> Promise used to return the rawfile content, in byte arrays.</p>
</td>
</tr>
</tbody>
</table>
- Example
```
resourceManager.getResourceManager((error, mgr) => {
mgr.getRawFile("test.xml").then(value => {
console.log(value);
}).catch(error => {
console.log("getrawfile promise " + error);
});
});
```
# Running Lock<a name="EN-US_TOPIC_0000001133776274"></a>
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE:**
>The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import<a name="s56d19203690d4782bfc74069abb6bd71"></a>
......@@ -9,9 +9,10 @@
import runninglock from '@ohos.runningLock';
```
## Required Permissions<a name="section11257113618419"></a>
## System Capabilities
SystemCapability.PowerManager.PowerManager
To request or use a running lock, you must declare the **ohos.permission.RUNNING\_LOCK** permission.
## RunningLockType<a name="section7299123218370"></a>
......
# 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.|
此差异已折叠。
......@@ -3,30 +3,6 @@
>![](../../public_sys-resources/icon-note.gif) **NOTE:**
>The APIs of this module are supported since API version 7.
## Applicable Devices<a name="section16881239114912"></a>
<a name="table857714145377"></a>
<table><thead align="left"><tr id="row55778146373"><th class="cellrowborder" valign="top" width="25%" id="mcps1.1.5.1.1"><p id="p7577141417376"><a name="p7577141417376"></a><a name="p7577141417376"></a>Phone</p>
</th>
<th class="cellrowborder" valign="top" width="25%" id="mcps1.1.5.1.2"><p id="p487719816463"><a name="p487719816463"></a><a name="p487719816463"></a>Tablet</p>
</th>
<th class="cellrowborder" valign="top" width="25%" id="mcps1.1.5.1.3"><p id="p135771614203720"><a name="p135771614203720"></a><a name="p135771614203720"></a>Smart TV</p>
</th>
<th class="cellrowborder" valign="top" width="25%" id="mcps1.1.5.1.4"><p id="p25772014133712"><a name="p25772014133712"></a><a name="p25772014133712"></a>Wearable</p>
</th>
</tr>
</thead>
<tbody><tr id="row8578151423715"><td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.1 "><p id="p65782014203718"><a name="p65782014203718"></a><a name="p65782014203718"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.2 "><p id="p148771182469"><a name="p148771182469"></a><a name="p148771182469"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.3 "><p id="p45783141377"><a name="p45783141377"></a><a name="p45783141377"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.4 "><p id="p11578161443718"><a name="p11578161443718"></a><a name="p11578161443718"></a>Yes</p>
</td>
</tr>
</tbody>
</table>
## Modules to Import<a name="s56d19203690d4782bfc74069abb6bd71"></a>
......
此差异已折叠。
......@@ -3,30 +3,6 @@
>**NOTE:**
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Applicable Devices<a name="section16881239114912"></a>
<a name="table857714145377"></a>
<table><thead align="left"><tr id="row55778146373"><th class="cellrowborder" valign="top" width="25%" id="mcps1.1.5.1.1"><p id="p7577141417376"><a name="p7577141417376"></a><a name="p7577141417376"></a>Phone</p>
</th>
<th class="cellrowborder" valign="top" width="25%" id="mcps1.1.5.1.2"><p id="p487719816463"><a name="p487719816463"></a><a name="p487719816463"></a>Tablet</p>
</th>
<th class="cellrowborder" valign="top" width="25%" id="mcps1.1.5.1.3"><p id="p135771614203720"><a name="p135771614203720"></a><a name="p135771614203720"></a>Smart TV</p>
</th>
<th class="cellrowborder" valign="top" width="25%" id="mcps1.1.5.1.4"><p id="p25772014133712"><a name="p25772014133712"></a><a name="p25772014133712"></a>Wearable</p>
</th>
</tr>
</thead>
<tbody><tr id="row8578151423715"><td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.1 "><p id="p65782014203718"><a name="p65782014203718"></a><a name="p65782014203718"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.2 "><p id="p148771182469"><a name="p148771182469"></a><a name="p148771182469"></a>Yes</p>
</td>
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.3 "><p id="p45783141377"><a name="p45783141377"></a><a name="p45783141377"></a>No</p>
</td>
<td class="cellrowborder" valign="top" width="25%" headers="mcps1.1.5.1.4 "><p id="p11578161443718"><a name="p11578161443718"></a><a name="p11578161443718"></a>No</p>
</td>
</tr>
</tbody>
</table>
## Modules to Import<a name="s56d19203690d4782bfc74069abb6bd71"></a>
......
......@@ -9,6 +9,10 @@
import window from '@ohos.window';
```
## System Capabilities
SystemCapability.WindowManager.WindowManager.Core
## Required Permissions<a name="section11257113618419"></a>
ohos.permission.SYSTEM\_FLOAT\_WINDOW
......@@ -638,7 +642,7 @@ Obtains the mode of this window.
```
window.getAbilityWindowMode((err, data) => {
if (err) {
console.error(''Failed to obtain the window mode. Cause:' + JSON.stringify(err));
console.error('Failed to obtain the window mode. Cause:' + JSON.stringify(err));
return;
}
console.info('Window mode obtained. Data:' + JSON.stringify(data))
......
此差异已折叠。
此差异已折叠。
# 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.
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册