diff --git a/README.md b/README.md index fc832338276d73545d58daf37d0b01719fc473e0..b25f5b980ff7abba3df8236d4a69fa2838af0089 100644 --- a/README.md +++ b/README.md @@ -14,15 +14,17 @@ This repository stores device and application development documents provided by ### Latest Versions -master: the latest version. + - master: the latest version. -OpenHarmony 3.1 Beta. [Learn more](en/release-notes/OpenHarmony-v3.1-beta.md) + - OpenHarmony 3.1 Beta. [Learn more](en/release-notes/OpenHarmony-v3.1-beta.md) -OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md) + - OpenHarmony 3.0 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0-LTS.md) -OpenHarmony v2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md) + This version is upgraded to OpenHarmony 3.0.1 LTS. [Learn more](en/release-notes/OpenHarmony-v3.0.1-LTS.md) -OpenHarmony 2.0 Canary. [Learn more](en/release-notes/OpenHarmony-2-0-canary.md) + - OpenHarmony v2.2 Beta2. [Learn more](en/release-notes/OpenHarmony-v2.2-beta2.md) + + - OpenHarmony 2.0 Canary. [Learn more](en/release-notes/OpenHarmony-2-0-Canary.md) ### Historical Stable Versions diff --git a/docker/CHANGELOG.md b/docker/CHANGELOG.md index f09cd81c10aef593f40a0934cdc2c5aea715fbd8..9d86d5e86b9b80169494662a960e3f61d37cd825 100644 --- a/docker/CHANGELOG.md +++ b/docker/CHANGELOG.md @@ -1,3 +1,11 @@ +### 0.0.6 (2022/02/10) + +1、更新hb。 + +2、增加安装ruby。 + + + ### 0.0.5 (2021/06/21) 1、更新llvm版本从10.0.1-53907更新到10.0.1-62608,支撑ipcamera_hispark_taurus_linux编译。 diff --git a/docker/CHANGELOG_en.md b/docker/CHANGELOG_en.md index 03fcdf51fa898f88dc522dfaef873105348e62b9..a6adf956e2727dace6583fd2760e481aa470e4df 100644 --- a/docker/CHANGELOG_en.md +++ b/docker/CHANGELOG_en.md @@ -1,3 +1,11 @@ +### 0.0.5 (2021/06/21) + +1\. Updated hb. + +2\. Added the installation of ruby. + + + ### 0.0.5 (2021/06/21) 1\. Updated LLVM from 10.0.1-53907 to 10.0.1-62608. Introduced support for ipcamera\_hispark\_taurus\_linux. diff --git a/docker/Dockerfile b/docker/Dockerfile index 3c9d9c5116dbff8cde10c1c8fe099aee03cfe149..20fffa28a04fee731fcb3dee5feb90e0b26a2439 100755 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -43,16 +43,17 @@ RUN apt-get update -y \ && apt-get install gcc-arm-linux-gnueabi -y \ && apt-get install build-essential \ && apt-get install locales \ + && apt-get install ruby -y \ && locale-gen "en_US.UTF-8" \ && rm -rf /bin/sh /usr/bin/python /usr/bin/python3 \ && ln -s /bin/bash /bin/sh \ && ln -s /usr/bin/python3.8 /usr/bin/python3 \ && ln -s /usr/bin/python3.8 /usr/bin/python \ - && pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple setuptools \ - && pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple kconfiglib \ - && pip3 install --trusted-host mirrors.aliyun.com -i http://mirrors.aliyun.com/pypi/simple pycryptodome \ - && pip3 install --trusted-host mirrors.aliyun.com -i https://mirrors.aliyun.com/pypi/simple ecdsa \ - && python3 -m pip install --user ohos-build \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple setuptools \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple kconfiglib \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple pycryptodome \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple ecdsa \ + && pip3 install --trusted-host https://repo.huaweicloud.com -i https://repo.huaweicloud.com/repository/pypi/simple ohos-build \ && mkdir -p /home/tools \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/clang/10.0.1-62608/linux/llvm.tar.gz \ && wget -P /home/tools https://repo.huaweicloud.com/harmonyos/compiler/hc-gen/0.65/linux/hc-gen-0.65-linux.tar \ diff --git a/docker/README.md b/docker/README.md index 44d9fe07e7bdd915691306115b8e7b8a0e84ba51..f19f4f1b592baf4a4505095507a8c9851b823a43 100755 --- a/docker/README.md +++ b/docker/README.md @@ -8,21 +8,19 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通 | Docker镜像仓库 | 标签 | 说明 | | :----------------------------------------------------------- | :------ | :----------------------------------------------------------- | -| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.5` | 已经预安装HarmonyOSOpenHarmony版本的编译环境,支持轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB)的版本构建。 | +| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.6` | 已经预安装OpenHarmony版本的编译环境,支持轻量系统类设备(参考内存≥128KB)和小型系统类设备(参考内存≥1MB)的版本构建。 | ### 使用方式及步骤 - 开发者在配置好开发环境后,可以通过以下步骤来使用我们提供的Docker环境,支持Ubuntu/Windows平台,下文将以Ubuntu系统为例进行使用介绍。 - -#### 方式一:从**HuaweiCloud SWR**上直接获取Docker镜像进行构建: + 开发者在配置好开发环境后,可以通过以下步骤来使用我们提供的Docker环境。详情请参见[Docker编译环境](https://gitee.com/openharmony/docs/blob/master/zh-cn/device-dev/get-code/gettools-acquire.md)。 1. 获取Docker镜像 ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 2. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境 ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 3. 通过如下命令启动不同平台的编译 ``` @@ -31,25 +29,3 @@ OpenHarmony的Docker镜像托管在**HuaweiCloud SWR**上,开发者可以通 在显示的页面中通过键盘上下键选择需要编译的平台,通过回车确定选择。 hb build -f #执行编译。 ``` - - #### 方式二:通过Dockerfile 构建本地Docker镜像进行构建 -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像 - ``` - git clone https://gitee.com/openharmony/docs.git - ``` -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令 - ``` - cd docs/docker - ./build.sh - ``` -4. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境 - ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker:0.0.5 - ``` -5. 通过如下命令启动不同平台的编译 - ``` - hb set #设置工作目录。 - . #输入源码所在目录,点(.)表示当前目录。 - 在显示的页面中通过键盘上下键选择需要编译的平台,通过回车确定选择。 - hb build -f #执行编译。 - ``` diff --git a/docker/README_en.md b/docker/README_en.md index 4c11f5eac495fbb74e56f606660d66ac7123b553..708213426c4690b2c14b7eb395f04376b5254b06 100644 --- a/docker/README_en.md +++ b/docker/README_en.md @@ -8,21 +8,19 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua | Docker Image Repository | Tag | Description | | :----------------------------------------------------------- | :------ | :----------------------------------------------------------- | -| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.5` | The HarmonyOSOpenHarmony build environment has been pre-installed. This repository applies to Mini-System Devices (reference memory ≥ 128 KB) and Small-System Devices (reference memory ≥ 1 MB). | +| `swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker` | `0.0.6` | The OpenHarmony build environment has been pre-installed. This repository applies to Mini-System Devices (reference memory ≥ 128 KB) and Small-System Devices (reference memory ≥ 1 MB). | ### Usage - After configuring the development environments, perform the steps below to access the Docker environment. The following steps use Ubuntu as an example (Windows is also supported). - -#### **Method 1: Obtaining the Docker image from HuaweiCloud SWR**: + After configuring the development environments, perform the steps below to access the Docker environment. 1. Obtain the Docker image. ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 2. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 3. Run the following script to start building for different platforms. ``` @@ -31,25 +29,3 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua Press the Up or Down key to select the platform to build on, then press Enter. hb build -f # Start building. ``` - - #### **Method 2: Using the Dockerfile to Build a Local Docker Image** -1. Obtain the Dockerfile script for a local Docker image. - ``` - git clone https://gitee.com/openharmony/docs.git - ``` -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: - ``` - cd docs/docker - ./build.sh - ``` -4. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: - ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker:0.0.5 - ``` -5. Run the following script to start building for different platforms. - ``` - hb set # Set the working directory. - . # Enter the directory where the source code is stored. If the code is stored in the current directory, enter a period (.). - Press the Up or Down key to select the platform to build on, then press Enter. - hb build -f # Start building. - ``` diff --git a/docker/build.sh b/docker/build.sh index e1f08d1ee475ebdda7a361522233d99aca979dd5..b67f8cf68aab99806f7c2907231393206b2dbd79 100755 --- a/docker/build.sh +++ b/docker/build.sh @@ -13,4 +13,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -docker build -t openharmony-docker:0.0.5 . +docker build -t openharmony-docker:0.0.6 . diff --git a/docker/standard/Readme-en.md b/docker/standard/Readme-en.md index b74720651bb24cd48774b6eaaf2884e21f414006..fcc5cf4339bbe2b0310f35a0e070fae848d6decf 100755 --- a/docker/standard/Readme-en.md +++ b/docker/standard/Readme-en.md @@ -6,8 +6,6 @@ The Docker image of OpenHarmony is hosted on [HUAWEI Cloud SWR](https://auth.hua ### Setting Up the Docker Environment for Standard-System Devices (reference memory ≥ 128 MB) -##### **Method 1: Obtaining the Docker image from HuaweiCloud SWR**: - 1. Obtain the Docker image. ``` docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 @@ -17,22 +15,6 @@ docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-dock docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` -##### **Method 2: Using the Dockerfile to Build a Local Docker Image** - -1. Obtain the Dockerfile script for a local Docker image. -``` -git clone https://gitee.com/openharmony/docs.git -``` -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: -``` -cd docs/docker/standard -./build.sh -``` -3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: -``` -docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 -``` - ### Building for Standard-System Devices (reference memory ≥ 128 MB) Run the following script to start building for Standard-System Devices (reference memory ≥ 128 MB) diff --git a/docker/standard/Readme.md b/docker/standard/Readme.md index 2bdb472014805d6ee68af247b3dcffd152fad671..7f239102756b60e154265c3d7e767db2694469a6 100755 --- a/docker/standard/Readme.md +++ b/docker/standard/Readme.md @@ -2,12 +2,10 @@ 本文为标准系统类设备Docker使用指导,[点此查看](https://gitee.com/openharmony/docs/blob/master/docker/README.md)小型和轻量系统类设备使用指导。 -OpenHarmony的Docker镜像托管在HuaweiCloud SWR上。开发者可以通过该镜像在很大程度上简化编译前的环境配置。开发者在配置好开发环境后,通过以下步骤来使用Docker环境。本Docker支持Ubuntu/Windows平台,下文将以Ubuntu系统为例进行使用介绍。 +OpenHarmony的Docker镜像托管在HuaweiCloud SWR上。开发者可以通过该镜像在很大程度上简化编译前的环境配置。开发者在配置好开发环境后,通过以下步骤来使用Docker环境。 ### 搭建Docker环境-标准系统类设备(参考内存≥128MB) -##### 方式一:从HuaweiCloud SWR上直接获取Docker镜像进行构建: - 1. 获取Docker镜像。 ``` docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 @@ -17,22 +15,6 @@ docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-dock docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker-standard:0.0.7 ``` -##### 方式二:通过Dockerfile 构建本地Docker镜像进行构建 - -1. 获取Dockerfile脚本文件,用来构建本地Docker镜像。 -``` -git clone https://gitee.com/openharmony/docs.git -``` -2. 进入Dockerfile代码目录路径执行Docker镜像构建命令。 -``` -cd docs/docker/standard -./build.sh -``` -3. 进入OpenHarmony代码根目录执行如下命令,从而进入Docker构建环境。 -``` -docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 -``` - ### 编译源码-标准系统类设备(参考内存≥128MB) 通过如下编译脚本启动标准系统类设备(参考内存≥128MB)的编译。 diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index b79d932947d6eeabe8cdb745573bc8fdc0e68f6b..3dd6e0f4b477be46113fe12b88bf4780abbc19ad 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -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) diff --git a/en/application-dev/background-agent-scheduled-reminder/Readme-EN.md b/en/application-dev/background-agent-scheduled-reminder/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..7f4083e641ecf002e40313deaed5a9616ad32913 --- /dev/null +++ b/en/application-dev/background-agent-scheduled-reminder/Readme-EN.md @@ -0,0 +1,4 @@ +# Agent-Powered Scheduled Reminders + +- [Overview](background-agent-scheduled-reminder-overview.md) +- [Development Guidelines](background-agent-scheduled-reminder-guide.md) diff --git a/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md b/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..dedcdc819a68c2bf70b47106adadcfa3a3e74402 --- /dev/null +++ b/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-guide.md @@ -0,0 +1,683 @@ +# Development Guidelines + +## When to Use + +You can set your application to 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. + +## Available APIs + +**reminderAgent** encapsulates the methods for publishing and canceling reminders. + +**Table 1** Major APIs in reminderAgent + + + + + + + + + + + + + + + + + + + + + + + + + +

API

+

Description

+

function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void;

+

function publishReminder(reminderReq: ReminderRequest): Promise<number>;

+

Publishes a scheduled reminder.

+

The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system.

+

function cancelReminder(reminderId: number, callback: AsyncCallback<void>): void;

+

function cancelReminder(reminderId: number): Promise<void>;

+

Cancels a specified reminder. (The value of reminderId is obtained from the return value of publishReminder.)

+

function getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void;

+

function getValidReminders(): Promise<Array<ReminderRequest>>;

+

Obtains all valid reminders set by the current application.

+

function cancelAllReminders(callback: AsyncCallback<void>): void;

+

function cancelAllReminders(): Promise<void>;

+

Cancels all reminders set by the current application.

+

function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void;

+

function addNotificationSlot(slot: NotificationSlot): Promise<void>;

+

Registers a NotificationSlot instance to be used by the reminder.

+

function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void;

+

function removeNotificationSlot(slotType: notification.SlotType): Promise<void>;

+

Removes a NotificationSlot instance of a specified type.

+
+ +**ActionButtonType** enumerates types of buttons displayed in a reminder notification. + +**Table 2** ActionButtonType enumeration + + + + + + + + + + +

Name

+

Description

+

ACTION_BUTTON_TYPE_CLOSE

+

Close button, which can be tapped to stop the reminder alert tone, close the reminder notification, and cancel the reminder snoozing.

+
+ +**ReminderType** enumerates the reminder types. + +**Table 3** ReminderType enumeration + + + + + + + + + + + + + + + + +

Name

+

Description

+

REMINDER_TYPE_TIMER

+

Countdown reminder.

+

REMINDER_TYPE_CALENDAR

+

Calendar reminder.

+

REMINDER_TYPE_ALARM

+

Alarm reminder.

+
+ +**ActionButton** defines a button displayed in the reminder notification. + +**Table 4** ActionButton instance + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

title

+

string

+

Yes

+

Text on the button.

+

type

+

ActionButtonType

+

Yes

+

Button type.

+
+ +**WantAgent** sets the package and ability that are redirected to when the reminder notification is clicked. + +**Table 5** WantAgent instance + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

pkgName

+

string

+

Yes

+

Name of the package redirected to when the reminder notification is clicked.

+

abilityName

+

string

+

Yes

+

Name of the ability redirected to when the reminder notification is clicked.

+
+ +**MaxScreenWantAgent** sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. + +**Table 6** MaxScreenWantAgent instance + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

pkgName

+

string

+

Yes

+

Name of the package that is automatically started when the reminder arrives and the device is not in use.

+

abilityName

+

string

+

Yes

+

Name of the ability that is automatically started when the reminder arrives and the device is not in use.

+
+ +**ReminderRequest** defines the reminder to publish. + +**Table 7** ReminderRequest instance + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reminderType

+

ReminderType

+

Yes

+

Type of the reminder.

+

actionButton

+

[ActionButton?, ActionButton?]

+

No

+

Action button displayed in the reminder notification.

+

wantAgent

+

WantAgent

+

No

+

Information about the ability that is redirected to when the notification is clicked.

+

maxScreenWantAgent

+

MaxScreenWantAgent

+

No

+

Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.

+

ringDuration

+

number

+

No

+

Ring duration.

+

snoozeTimes

+

number

+

No

+

Number of reminder snooze times.

+

timeInterval

+

number

+

No

+

Reminder snooze interval.

+

title

+

string

+

No

+

Reminder title.

+

content

+

string

+

No

+

Reminder content.

+

expiredContent

+

string

+

No

+

Extended content to be displayed when the reminder expires.

+

snoozeContent

+

string

+

No

+

Extended content to be displayed when the reminder is snoozing.

+

notificationId

+

number

+

No

+

Notification ID used by the reminder. For details, see the API reference of the NotificationRequest.setNotificationId(int id) method.

+

slotType

+

SlotType

+

No

+

Type of the slot used by the reminder

+
+ +**ReminderRequestCalendar** extends **ReminderRequest** and defines a reminder for a calendar event. + +The earliest reminder time must be later than the current time. + +**Table 8** ReminderRequestCalendar instance + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

dateTime

+

LocalDateTime

+

Yes

+

Reminder time.

+

repeatMonths

+

Array<number>

+

No

+

Months in which the reminder repeats.

+

repeatDays

+

Array<number>

+

No

+

Date on which the reminder repeats.

+
+ +**ReminderRequestAlarm** extends **ReminderRequest** and defines a reminder for the alarm clock. + +**Table 9** ReminderRequestAlarm instance + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

hour

+

number

+

Yes

+

Hour portion of the reminder time.

+

minute

+

number

+

Yes

+

Minute portion of the reminder time.

+

daysOfWeek

+

Array<number>

+

No

+

Days of a week when the reminder repeats.

+
+ +**ReminderRequestTimer** extends **ReminderRequest** and defines a reminder for a scheduled timer. + +**Table 10** ReminderRequestTimer instance + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

triggerTimeInSeconds

+

number

+

Yes

+

Number of seconds in the countdown timer.

+
+ +**LocalDateTime** defines a **LocalDateTime** instance. + +**Table 11** LocalDateTime instance + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

year

+

number

+

Yes

+

Year.

+

month

+

number

+

Yes

+

Month.

+

day

+

number

+

Yes

+

Date.

+

hour

+

number

+

Yes

+

Hour.

+

minute

+

number

+

Yes

+

Minute.

+

second

+

number

+

No

+

Second.

+
+ +## How to Develop + +>![](../public_sys-resources/icon-note.gif) **NOTE:** +>To publish a reminder, your application needs to apply for the **ohos.permission.PUBLISH\_AGENT\_REMINDER** permission. + +Publish a 10-second countdown reminder. + +1. Define a countdown timer instance. + + ``` + import reminderAgent from '@ohos.reminderAgent'; + import notification from '@ohos.notification'; + export default { + timer: { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 10, + actionButton: [ + { + title: "close", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + } + ], + wantAgent: { + pkgName: "com.huawei.phone", + abilityName: "com.huawei.phone.MainAbility" + }, + maxScreenWantAgent: { + pkgName: "com.huawei.phone", + abilityName: "com.huawei.phone.MainAbility" + }, + title: "this is title", + content: "this is content", + expiredContent: "this reminder has expired", + notificationId: 100, + slotType: notification.SlotType.SOCIAL_COMMUNICATION + } + } + ``` + +2. Publish the reminder. + + ``` + startTimer() { + reminderAgent.publishReminder(this.timer, (err, reminderId) =>{ + this.printInfo(JSON.stringify(err)); + this.printInfo("reminderId:" + reminderId); + }); + } + ``` + + HTML page code: + + ``` +
+ +
+ ``` + + +Sample code for defining a calendar reminder instance: + +``` +calendar: { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime: { + year: 2050, + month: 7, + day: 30, + hour: 11, + minute: 14, + second: 30 + }, + repeatMonths: [0], + repeatDays: [0], + actionButton: [ + { + title: "close", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + }, + { + title: "snooze", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE + }, + ], + wantAgent: { + pkgName: "com.huawei.phone", + abilityName: "com.huawei.phone.MainAbility" + }, + maxScreenWantAgent: { + pkgName: "com.huawei.phone", + abilityName: "com.huawei.phone.MainAbility" + }, + ringDuration: 5, + snoozeTimes: 2, + timeInterval: 5, + title: "this is title", + content: "this is content", + expiredContent: "this reminder has expired", + snoozeContent: "remind later", + notificationId: 100, + slotType: notification.SlotType.SOCIAL_COMMUNICATION +} +``` + +Sample code for defining an alarm reminder instance: + +``` +alarm: { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 11, + minute: 14, + daysOfWeek: [0], + actionButton: [ + { + title: "close", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_CLOSE + }, + { + title: "snooze", + type: reminderAgent.ActionButtonType.ACTION_BUTTON_TYPE_SNOOZE + }, + ], + wantAgent: { + pkgName: "com.huawei.phone", + abilityName: "com.huawei.phone.MainAbility" + }, + maxScreenWantAgent: { + pkgName: "com.huawei.phone", + abilityName: "com.huawei.phone.MainAbility" + }, + ringDuration: 5, + snoozeTimes: 2, + timeInterval: 5, + title: "this is title", + content: "this is content", + expiredContent: "this reminder has expired", + snoozeContent: "remind later", + notificationId: 100, + slotType: notification.SlotType.SOCIAL_COMMUNICATION +} +``` + diff --git a/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-overview.md b/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..32f0b858f30ce9f6dcec7c979f7c196ecc42e42c --- /dev/null +++ b/en/application-dev/background-agent-scheduled-reminder/background-agent-scheduled-reminder-overview.md @@ -0,0 +1,4 @@ +# Overview + +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. + diff --git a/en/application-dev/background-task-management/Readme-EN.md b/en/application-dev/background-task-management/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..d645314bfff65a72f1c6ff7efdb678e1b11753b4 --- /dev/null +++ b/en/application-dev/background-task-management/Readme-EN.md @@ -0,0 +1,4 @@ +# 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 diff --git a/en/application-dev/background-task-management/background-task-dev-guide.md b/en/application-dev/background-task-management/background-task-dev-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..aeab15fa9cc2ab9831147299d0c6b2ed803e88ca --- /dev/null +++ b/en/application-dev/background-task-management/background-task-dev-guide.md @@ -0,0 +1,79 @@ +# Background Task Management Development + +## When to Use + +If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task or continuous task for delayed suspension based on the service type. + + +## Available APIs + +``` +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +``` + +**Table 1** Main APIs of backgroundTaskManager + +| API| Description| +| -------- | -------- | +| function requestSuspendDelay(reason: string, callback: Callback<void>): **DelaySuspendInfo**; | Requests delayed suspension after the application switches to the background.
The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| +| function getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void;
function getRemainingDelayTime(requestId: number): Promise<number>; | Obtains the remaining duration before the application is suspended. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)
Two asynchronous methods are provided: callback and promise.| +| function cancelSuspendDelay(requestId: number): void; | Cancels the suspension delay. (The value of **requestId** is obtained from the return value of **requestSuspendDelay**.)| + +**Table 2** Parameters in DelaySuspendInfo + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| requestId | number | Yes| ID of the suspension delay request.| +| actualDelayTime | number | Yes| Actual suspension delay duration of the application, in milliseconds.| + + +## How to Develop + +1. Request a suspension delay. + ``` + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + let myReason = 'test requestSuspendDelay'; + let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); + }); + var id = delayInfo.requestId;console.info("requestId is: " + id); + ``` + +2. Obtain the remaining duration before the application is suspended. + ``` + backgroundTaskManager.getRemainingDelayTime(id).then( res => { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); + }).catch( err => { + console.log('promise => Operation failed. Cause: ' + err.data); + }); + ``` + +3. Cancel the suspension delay. + ``` + backgroundTaskManager.cancelSuspendDelay(id); + ``` + + +## Development Examples + +``` +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +let myReason = 'test requestSuspendDelay'; +// Request a suspension delay. +let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); +}); +// Print the suspension delay information. +var id = delayInfo.requestId; +var time = delayInfo.actualDelayTime; +console.info("The requestId is: " + id); +console.info("The actualDelayTime is: " + time); +// Obtain the remaining duration before the application is suspended. +backgroundTaskManager.getRemainingDelayTime(id).then( res => { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); +}).catch( err => { + console.log('promise => Operation failed. Cause: ' + err.data); +}); +// Cancel the suspension delay. +backgroundTaskManager.cancelSuspendDelay(id); +``` diff --git a/en/application-dev/background-task-management/background-task-overview.md b/en/application-dev/background-task-management/background-task-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..3483ae70d0e05a4613f7efa031494401f867a88a --- /dev/null +++ b/en/application-dev/background-task-management/background-task-overview.md @@ -0,0 +1,35 @@ +# Background Task Management Overview + +On an OS that allows for user interaction, resources gravitate to service processes that interact with users. In other words, apart from processes that support system running, service processes that can be perceived by users have the highest priority. Therefore, background task management is applicable to service processes that cannot be perceived by users. + + +## Background Task Types + +Background tasks described in this document refer to the services that need to be continued when the respective applications or service modules are running in the background (not visible to the users). For more targeted management of background applications and service modules, OpenHarmony classifies applications and service modules into the following types: + +1. No background task: An application or service module does not need further processing when switched to the background. + +2. Transient task: If an application or service module has an urgent, short task that must continue in the background until it is completed, such as data compression, the application or service module can request a transient task for delayed suspension. + +3. Continuous task: If an application or service module has a user-initiated, perceivable task that needs to run in an extended period of time in the background, it can request a continuous task so that it will not be suspended. Examples of continuous tasks include music playback, navigation, upload and download, device connection, and VoIP. + + +## Transient Tasks + +As mentioned above, applications and service modules with transient tasks have their suspension delayed so that their running is not affected by background lifecycle management within the specified time frame. + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> Applications and service modules can request transient tasks only for temporary tasks. The time quota is 3 minutes per time and 10 minutes per day. The system allocates the time frame based on the application scenario and system status. + + +### Restrictions on Using Transient Tasks + +Adhere to the following constraints and rules when using transient tasks: + +- **When to request**: An application can request a transient task only when it is running in the foreground or before it is suspended in the background. Otherwise, the application may be suspended, resulting in request failure. By default, an application has 6–12 seconds of running time (subject to the application scenario) before it is suspended in the background. + +- **Timeout**: The system notifies the application of the suspension delay timeout by using a callback. The application must then cancel the delayed suspension or apply for delayed suspension again. Otherwise, the application will be forcibly suspended. + +- **When to cancel**: The requesting application shall cancel the request when the transient task is complete. If the request is forcibly canceled by the system, the time frame allowed for the application to run in the background will be affected. + +- **Quota mechanism**: To prevent abuse of the keepalive, each application has a certain quota every day (dynamically adjusted based on user habits). After using up the quota, an application cannot request transient tasks. Therefore, applications should cancel their request immediately after the transient tasks are complete, to avoid quota consumption. (Note: The quota refers to the requested duration and does not include the time when the application runs in the background.) diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-caution.gif b/en/application-dev/background-task-management/public_sys-resources/icon-caution.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-caution.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-danger.gif b/en/application-dev/background-task-management/public_sys-resources/icon-danger.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-danger.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-note.gif b/en/application-dev/background-task-management/public_sys-resources/icon-note.gif new file mode 100644 index 0000000000000000000000000000000000000000..6314297e45c1de184204098efd4814d6dc8b1cda Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-note.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-notice.gif b/en/application-dev/background-task-management/public_sys-resources/icon-notice.gif new file mode 100644 index 0000000000000000000000000000000000000000..86024f61b691400bea99e5b1f506d9d9aef36e27 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-notice.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-tip.gif b/en/application-dev/background-task-management/public_sys-resources/icon-tip.gif new file mode 100644 index 0000000000000000000000000000000000000000..93aa72053b510e456b149f36a0972703ea9999b7 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-tip.gif differ diff --git a/en/application-dev/background-task-management/public_sys-resources/icon-warning.gif b/en/application-dev/background-task-management/public_sys-resources/icon-warning.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/background-task-management/public_sys-resources/icon-warning.gif differ diff --git a/en/application-dev/database/Readme-EN.md b/en/application-dev/database/Readme-EN.md index 9e68a292b434f94c7711e79aa8452e911590c998..2555d715a720db4389f502176f9c84226717fcce 100644 --- a/en/application-dev/database/Readme-EN.md +++ b/en/application-dev/database/Readme-EN.md @@ -1,4 +1,11 @@ -# 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 diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..856257581cb3e9fb7e34f7a3aee01d470bfcf794 --- /dev/null +++ b/en/application-dev/database/database-preference-guidelines.md @@ -0,0 +1,272 @@ +# Lightweight Data Store Development + +## When to Use + +The lightweight data store is ideal for storing lightweight and frequently used data, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Storage** APIs. + +## Available APIs + +The lightweight data store provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value pairs. Keys are of the string type, and values can be of the 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 + + + + + + + + + + + + +

Package Name

+

Method

+

Description

+

ohos.data.storage

+

getStorage(path: string): Promise<Storage>;

+

Obtains the Storage singleton corresponding to a file for data operations.

+
+ +**Writing Data** + +Call the **put\(\)** method to add or modify data in a **Storage** instance. + +**Table 2** API for writing data + + + + + + + + + + + + +

Class

+

Method

+

Description

+

Storage

+

put(key: string, value: ValueType): Promise<void>;

+

Writes data of the number, string, and Boolean types.

+
+ +**Reading Data** + +Call the **get\(\)** method to read data from a **Storage** instance. + +**Table 3** API for reading data + + + + + + + + + + + + +

Class

+

Method

+

Description

+

Storage

+

get(key: string, defValue: ValueType): Promise<ValueType>;

+

Reads data of the number, string, and Boolean types.

+
+ +**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 + + + + + + + + + + + + +

Class

+

Method

+

Description

+

Storage

+

flush(): Promise<void>;

+

Writes data in the Storage instance back to its file through an asynchronous thread.

+
+ +**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 + + + + + + + + + + + + + + + + +

Class

+

Method

+

Description

+

Storage

+

on(type: 'change', callback: Callback<StorageObserver>): void;

+

Subscribes to data changes.

+

Storage

+

off(type: 'change', callback: Callback<StorageObserver>): void;

+

Unsubscribes from data changes.

+
+ +**Deleting Data** + +Use the following APIs to delete a **Storage** instance or data file. + +**Table 6** APIs for deleting data + + + + + + + + + + + + + + + + +

Package Name

+

Method

+

Description

+

ohos.data.storage

+

deleteStorage(path: string): Promise<void>;

+

Deletes a Storage instance from the cache and deletes its file from the device.

+

ohos.data.storage

+

removeStorageFromCache(path: string): Promise<void>;

+

Deletes a Storage instance from the cache to release memory.

+
+ +## How to Develop + +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) + }) + ``` + + diff --git a/en/application-dev/database/database-preference-overview.md b/en/application-dev/database/database-preference-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..45639c75e8ad5d1b3f68c79da90fbc598af7e840 --- /dev/null +++ b/en/application-dev/database/database-preference-overview.md @@ -0,0 +1,31 @@ +# Lightweight Data Store Overview + +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 + +- **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 + +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 + + +![](figures/en-us_image_0000001199139454.png) + +## Constraints + +- **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. + diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..2411dd2c9a15ce0976587dd3caa74e31e7777ce5 --- /dev/null +++ b/en/application-dev/database/database-relational-guidelines.md @@ -0,0 +1,671 @@ +# RDB Development + +## When to Use + +On the basis of the SQLite database, the RDB allows you to operate data with or without native SQL statements. An RDB is also called RDB store. + +## Available APIs + +**Creating and Deleting an RDB Store** + +The following table describes APIs available for creating and deleting an RDB store. + +**Table 1** APIs for creating and deleting an RDB store + + + + + + + + + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

dataRdb

+

getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void

+

Obtains an RDB store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a callback to return the result.

+
  • config: configuration of the RDB store.
  • version: version of the RDB store.
  • callback: callback invoked to return the RDB store.
+

dataRdb

+

getRdbStore(config: StoreConfig, version: number): Promise<RdbStore>

+

Obtains an RDB store. You can set parameters for the RDB store based on service requirements, call APIs to perform data operations, and use a promise to return the result.

+
  • config: configuration of the RDB store.
  • version: version of the RDB store.
+

dataRdb

+

deleteRdbStore(name: string, callback: AsyncCallback<void>): void

+

Deletes an RDB store. This method uses a callback to return the result.

+
  • name: name of the RDB store to delete.
  • callback: callback invoked to return the result. If the RDB store is deleted, true will be returned. Otherwise, false will be returned.
+

dataRdb

+

deleteRdbStore(name: string): Promise<void>

+

Deletes an RDB store. This method uses a promise to return the result.

+
  • name: name of the RDB store to delete.
+
+ +**Managing Data in an RDB Store** + +The RDB provides APIs for inserting, deleting, modifying, and querying data in the local RDB store. + +- **Inserting data** + + The RDB provides methods for inserting data through **ValuesBucket** in a data table. If the data is inserted successfully, the row number of the data inserted is returned; otherwise, **-1** is returned. + + **Table 2** APIs for inserting data to a data table + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

RdbStore

+

insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void

+

Inserts a row of data into a table. This method uses a callback to return the result.

+
  • name: name of the target table.
  • values: data to be inserted into the table.
  • callback: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, -1 will be returned.
+

RdbStore

+

insert(name: string, values: ValuesBucket): Promise<number>

+

Inserts a row of data into a table. This method uses a promise to return the result.

+
  • name: name of the target table.
  • values: data to be inserted into the table.
+
+ +- **Updating data** + + Call the **update\(\)** method to pass the new data and specify the update conditions by using **RdbPredicates**. If the data is successfully updated, the row number of the updated data is returned; otherwise, **0** is returned. + + **Table 3** APIs for updating data + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

RdbStore

+

update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void

+

Updates the data that meets the conditions specified by the RdbPredicates object. This method uses a callback to return the result.

+
  • values: data to update, which is stored in ValuesBucket.
  • rdbPredicates: conditions for updating data.
  • callback: callback invoked to return the number of rows updated.
+

RdbStore

+

update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise

+

Updates the data that meets the conditions specified by the RdbPredicates object. This method uses a promise to return the result.

+
  • values: data to update, which is stored in ValuesBucket.
  • rdbPredicates: conditions for updating data.
+
+ +- **Deleting data** + + Call the **delete\(\)** method to delete data meeting the conditions specified by **RdbPredicates**. If the data is deleted, the row number of the deleted data is returned; otherwise, **0** is returned. + + **Table 4** APIs for deleting data + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

RdbStore

+

delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void

+

Deletes data based on the conditions specified by RdbPredicates. This method uses a callback to return the result.

+
  • rdbPredicates: conditions for deleting data.
  • callback: callback invoked to return the number of rows deleted.
+

RdbStore

+

delete(rdbPredicates: RdbPredicates): Promise

+

Deletes data based on the conditions specified by RdbPredicates. This method uses a promise to return the result.

+
  • rdbPredicates: conditions for deleting data.
+
+ +- **Querying data** + + You can query data in the RDB in either of the following ways: + + - Call the **query** method to query data based on the predicates, without passing any SQL statement. + - Run the native SQL statement. + + **Table 5** APIs for querying data + + + + + + + + + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

RdbStore

+

query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void;

+

Queries data in the database based on specified conditions. This method uses a callback to return the result.

+
  • rdbPredicates: conditions for querying data.
+
  • columns: columns to query. If this parameter is not specified, the query applies to all columns.
  • callback: callback invoked to return the result. If the operation is successful, a ResultSet object will be returned.
+

RdbStore

+

query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet>;

+

Queries data in the database based on specified conditions. This method uses a promise to return the result.

+
  • rdbPredicates: conditions for querying data.
+
  • columns: columns to query. If this parameter is not specified, the query applies to all columns.
+

RdbStore

+

querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void

+

Queries data in the RDB store using the specified SQL statement. This method uses a callback to return the result.

+
  • sql: SQL statement.
+
  • bindArgs: arguments in the SQL statement.
  • callback: callback invoked to return the result. If the operation is successful, a ResultSet object will be returned.
+

RdbStore

+

querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet>

+

Queries data in the RDB store using the specified SQL statement. This method uses a promise to return the result.

+
  • sql: SQL statement.
+
  • bindArgs: arguments in the SQL statement.
+
+ + +**Using Predicates** + +The RDB provides **RdbPredicates** for you to set database operation conditions. + +**Table 6** APIs for RDB predicates + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

RdbPredicates

+

equalTo(field: string, value: ValueType): RdbPredicates

+

Sets the RdbPredicates to match the field with data type ValueType and value equal to the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

notEqualTo(field: string, value: ValueType): RdbPredicates

+

Sets the RdbPredicates to match the field with data type ValueType and value not equal to the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

beginWrap(): RdbPredicates

+

Adds a left parenthesis to the RdbPredicates.

+
  • RdbPredicates: RdbPredicates with a left parenthesis.
+

RdbPredicates

+

endWrap(): RdbPredicates

+

Adds a right parenthesis to the RdbPredicates.

+
  • RdbPredicates: RdbPredicates with a right parenthesis.
+

RdbPredicates

+

or(): RdbPredicates

+

Adds the OR condition to the RdbPredicates.

+
  • RdbPredicates: RdbPredicates with the OR condition.
+

RdbPredicates

+

and(): RdbPredicates

+

Adds the AND condition to the RdbPredicates.

+
  • RdbPredicates: RdbPredicates with the AND condition.
+

RdbPredicates

+

contains(field: string, value: string): RdbPredicats

+

Sets the RdbPredicates to match a string containing the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

beginsWith(field: string, value: string): RdbPredicates

+

Sets the RdbPredicates to match a string that starts with the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

endsWith(field: string, value: string): RdbPredicates

+

Sets the RdbPredicates to match a string that ends with the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

isNull(field: string): RdbPredicates

+

Sets the RdbPredicates to match the field whose value is null.

+
  • field: column name in the database table.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

isNotNull(field: string): RdbPredicates

+

Sets the RdbPredicates to match the field whose value is not null.

+
  • field: column name in the database table.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

like(field: string, value: string): RdbPredicates

+

Sets the RdbPredicates to match a string that is similar to the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

glob(field: string, value: string): RdbPredicates

+

Sets the RdbPredicates to match the specified string.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

between(field: string, low: ValueType, high: ValueType): RdbPredicates

+

Sets the RdbPredicates to match the field with data type ValueType and value within the specified range.

+
  • field: column name in the database table.
  • low: minimum value that matches the RdbPredicates.
  • high: maximum value that matches the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates

+

Sets the RdbPredicates to match the field with data type ValueType and value out of the specified range.

+
  • field: column name in the database table.
  • low: minimum value that matches the RdbPredicates.
  • high: maximum value that matches the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

greaterThan(field: string, value: ValueType): RdbPredicatesgr

+

Sets the RdbPredicates to match the field with data type ValueType and value greater than the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

lessThan(field: string, value: ValueType): RdbPredicates

+

Sets the RdbPredicates to match the field with data type ValueType and value less than the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates

+

Sets the RdbPredicates to match the field with data type ValueType and value greater than or equal to the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates

+

Sets the RdbPredicates to match the field with data type ValueType and value less than or equal to the specified value.

+
  • field: column name in the database table.
  • value: value to match the RdbPredicates.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

orderByAsc(field: string): RdbPredicates

+

Sets the RdbPredicates to match the column with values sorted in ascending order.

+
  • field: column name in the database table.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

orderByDesc(field: string): RdbPredicates

+

Sets the RdbPredicates to match the column with values sorted in descending order.

+
  • field: column name in the database table.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

distinct(): RdbPredicates

+

Sets the RdbPredicates to filter out duplicate records.

+
  • RdbPredicates: RdbPredicates that can filter out duplicate records.
+

RdbPredicates

+

limitAs(value: number): RdbPredicates

+

Sets the RdbPredicates to specify the maximum number of records to match in a column.

+
  • value: maximum number of records in a column.
  • RdbPredicates: RdbPredicates that can be used to set the maximum number of records to match in a column.
+

RdbPredicates

+

offsetAs(rowOffset: number): RdbPredicates

+

Sets the RdbPredicates to specify the start position of the returned result.

+
  • rowOffset: start position of the returned result. The value is a positive integer.
  • RdbPredicates: RdbPredicates object that specifies the start position of the returned result.
+

RdbPredicates

+

groupBy(fields: Array<string>): RdbPredicates

+

Sets the RdbPredicates to group rows that have the same value into summary rows.

+
  • fields: names of the columns grouped for querying data.
  • RdbPredicates: RdbPredicates that groups rows that have the same value.
+

RdbPredicates

+

indexedBy(indexName: string): RdbPredicates

+

Sets the RdbPredicates object to specify the index column.

+
  • indexName: name of the index column.
  • RdbPredicates: RdbPredicates object that specifies the index column.
+

RdbPredicates

+

in(field: string, value: Array<ValueType>): RdbPredicates

+

Sets the RdbPredicates to match the field with data type Array<ValueType> and value within the specified range.

+
  • field: column name in the database table.
+
  • value: array of ValueType to match.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+

RdbPredicates

+

notIn(field: string, value: Array<ValueType>): RdbPredicates

+

Sets the RdbPredicates to match the field with data type Array<ValueType> and value out of the specified range.

+
  • field: column name in the database table.
+
  • value: array of ValueType to match.
  • RdbPredicates: RdbPredicates object that matches the specified field.
+
+ +**Using the Result Set** + +A result set can be regarded as rows of data in the queried results. It allows you to traverse and access the data you have queried. The following table describes the external APIs of **ResultSet**. + +>![](public_sys-resources/icon-notice.gif) **NOTICE:** +>After a result set is used, you must call the **close\(\)** method to close it explicitly. + +**Table 7** APIs for using the result set + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

ResultSet

+

goTo(offset:number): boolean

+

Moves the result set forwards or backwards by an offset relative to its current position.

+

ResultSet

+

goToRow(position: number): boolean

+

Moves the result set to a specified row.

+

ResultSet

+

goToNextRow(): boolean

+

Moves the result set to the next row.

+

ResultSet

+

goToPreviousRow(): boolean

+

Moves the result set to the previous row.

+

ResultSet

+

getColumnIndex(columnName: string): number

+

Obtains the column index based on the specified column name.

+

ResultSet

+

getColumnName(columnIndex: number): string

+

Obtains the column name based on the specified column index.

+

ResultSet

+

goToFirstRow(): boolean

+

Checks whether the result set is located in the first row.

+

ResultSet

+

goToLastRow(): boolean

+

Checks whether the result set is located in the last row.

+

ResultSet

+

getString(columnIndex: number): string

+

Obtains the values in the specified column of the current row, in strings.

+

ResultSet

+

getBlob(columnIndex: number): Uint8Array

+

Obtains the values in the specified column of the current row, in a byte array.

+

ResultSet

+

getDouble(columnIndex: number): number

+

Obtains the values in the specified column of the current row, in double.

+

ResultSet

+

isColumnNull(columnIndex: number): boolean

+

Checks whether the values in the specified column of the current row are null.

+

ResultSet

+

close(): void

+

Closes the result set.

+
+ +**Encrypting an RDB Store** + +You can encrypt an RDB store. + +When creating an RDB store, you can add a key for security purposes. After that, the RDB store can be accessed only with the correct key. You can change the key but cannot delete it. + +Once an RDB store is created without a key, you cannot add a key any longer. + +**Table 8** APIs for changing the key + + + + + + + + + + + + + + + + +

Class

+

API

+

Description

+

RdbStore

+

changeEncryptKey(newEncryptKey:Uint8Array, callback: AsyncCallback<number>):void;

+

Changes the encryption key for an RDB store. This method uses a callback to return the result. If the key is changed, 0 is returned. Otherwise, a non-zero value is returned.

+

RdbStore

+

changeEncryptKey(newEncryptKey:Uint8Array): Promise<number>;

+

Changes the encryption key for an RDB store. This method uses a promise to return the result. If the key is changed, 0 is returned. Otherwise, a non-zero value is returned.

+
+ +## How to Develop + +1. Create an RDB store. + + 1. Configure the RDB attributes, including the name and storage mode of the database and whether it is read-only. + 2. Initialize the table structure and related data in the database. + 3. Create an RDB store. + + The sample code is as follows: + + ``` + import dataRdb from '@ohos.data.rdb'; + + const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + const STORE_CONFIG = {name: "rdbstore.db",} + + let rdbStore = await dataRdb.getRdbStore(STORE_CONFIG, 1); + await rdbStore.executeSql(CREATE_TABLE_TEST); + ``` + +2. Insert data. + + 1. Create a **ValuesBucket** object to store the data you need to insert. + 2. Call the **insert\(\)** method to insert data into the RDB store. + + The sample code is as follows: + + ``` + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} + let insertPromise = rdbStore.insert("test", valueBucket) + ``` + +3. Query data. + + 1. Create an **RdbPredicates** object to specify query conditions. + 2. Call the **query \(\)** method to query data in the RDB store. + 3. Call the **ResultSet\(\)** method to obtain the query result. + + The sample code is as follows: + + ``` + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("name", "Tom") + let resultSet = await rdbStore.query(predicates) + + resultSet.goToFirstRow() + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + + resultSet.close() + ``` + + diff --git a/en/application-dev/database/database-relational-overview.md b/en/application-dev/database/database-relational-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..cd675b9701e9e22147833d1fb7b471f420af2f12 --- /dev/null +++ b/en/application-dev/database/database-relational-overview.md @@ -0,0 +1,42 @@ +# RDB Overview + +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 + +- **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 + +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 +![](figures/how-rdb-works.png "how-rdb-works") + +## Default Settings + +- 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 maximum of four connection pools can be connected to an RDB to manage read and write operations. + +- To ensure data accuracy, the RDB supports only one write operation at a time. + diff --git a/en/application-dev/database/figures/en-us_image_0000001199139454.png b/en/application-dev/database/figures/en-us_image_0000001199139454.png new file mode 100644 index 0000000000000000000000000000000000000000..ca52bd43d384c5b2d06fe19623b50e0c66ba6295 Binary files /dev/null and b/en/application-dev/database/figures/en-us_image_0000001199139454.png differ diff --git a/en/application-dev/database/figures/how-rdb-works.png b/en/application-dev/database/figures/how-rdb-works.png new file mode 100644 index 0000000000000000000000000000000000000000..35e10dc3a07aef0e85a8f02332c3c6cd9d605448 Binary files /dev/null and b/en/application-dev/database/figures/how-rdb-works.png differ diff --git a/en/application-dev/media/Readme-EN.md b/en/application-dev/media/Readme-EN.md index 8e57cf850c58132fda114da0b2b9e31abf09ec27..6949606c73c67956d204680c9ccea34764c0df7a 100755 --- a/en/application-dev/media/Readme-EN.md +++ b/en/application-dev/media/Readme-EN.md @@ -1,6 +1,6 @@ # Media -- [Audio](audio.md) +- Audio - [Audio Overview](audio-overview.md) - [Audio Playback Development](audio-playback.md) diff --git a/en/application-dev/media/audio-playback.md b/en/application-dev/media/audio-playback.md index 573baf7669768528a5aa9bc434eca886f4283db8..2fccef4e22c1f1779b7dee4cb5ccf583bfb86675 100644 --- a/en/application-dev/media/audio-playback.md +++ b/en/application-dev/media/audio-playback.md @@ -2,127 +2,178 @@ ## When to Use -You use audio playback APIs to convert audio data into audible analog signals, play the audio signals using output devices, and manage playback tasks. +You can use audio playback APIs to convert audio data into audible analog signals, play the signals using output devices, and manage playback tasks. **Figure 1** Playback status -![](figures/playback-status.png "playback-status") - - -## Available APIs - -**Table 1** APIs for audio playback - -| API| Description| -| -------- | -------- | -| media.createAudioPlayer() | Creates an **AudioPlayer** instance.| -| AudioPlayer | Provides audio playback features. For details, see the table below.| - -**Table 2** AudioPlayer methods - -| Method| Description| -| -------- | -------- | -| release() | Releases audio resources.| -| play() | Starts audio playback.| -| pause() | Pauses playback.| -| stop() | Stops playback.| -| reset()7+ | Resets the audio source to be played.| -| setVolume(vol: number) | Sets playback volume.| -| seek(timeMs: number) | Changes the playback position.| -| src:string | Defines the URI of an audio file to play.| -| state:AudioState | Defines the playback state.| -| currentTime:number | Defines the current playback position.| -| duration:number | Defines the playback duration. The value **-1** is returned if the data source does not support playback position change, for example, in the real-time streaming media scenario.| -| loop:boolean | Defines whether to loop audio playback.| -| on('play', function callback) | Subscribes to the playback start event.| -| on('pause', function callback) | Subscribes to the playback pause event.| -| on('stop', function callback) | Subscribes to the playback stop event.| -| on('reset', function callback) | Subscribes to the playback reset event.| -| on('finish',function callback) | Subscribes to the playback end event.| -| on('error', function callback) | Subscribes to the playback error event.| -| on('dataload', function callback) | Subscribes to the data loading event.| -| on('volumeChange', function callback) | Subscribes to the volume change event.| -| on('timeUpdate', function callback) | Subscribes to the progress change event.| - - -1. Create an audio player. - ``` - import media from '@ohos.multimedia.media'; - var player = media.createAudioPlayer(); - ``` - -2. Set the subscription events. - ``` - player.on('play', (err, action) => { - if (err) { - console.error('Error returned in the play() callback.'); - return; - } - console.info('Current player duration: '+ player.duration); - console.info('Current player time: ' + player.currentTime); - console.info('Current player status: '+player.state); - console.info('Pause MP3'); - player.pause(); - }); - player.on('pause', (err, action) => { - if (err) { - console.error('Error returned in the pause() callback.'); + +![en-us_image_20220117](figures/en-us_image_20220117.jpg) + +## How to Develop + +For details about the APIs used for audio playback, see [js-apis-media.md](../reference/apis/js-apis-media.md). + +### Full-Process Scenario + +The full audio playback process includes creating an instance, setting the URI, playing audio, seeking to the playback position, setting the volume, pausing playback, obtaining track information, stopping playback, resetting resources, and releasing resources. + +For details about the **src** media source input types supported by **AudioPlayer**, see the [src attribute](../reference/apis/js-apis-media.md#audioplayer_Attributes). + +```js +function SetCallBack(audioPlayer) { + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + // The playback page is ready. You can click the Play button to start the playback. + }); + audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + // The Play button is changed to the pausable state. + }); + audioPlayer.on('pause', () => { // Set the 'pause' event callback. + console.info('audio pause success'); + // The Play button is changed to the playable state. + }); + audioPlayer.on('stop', () => { // Set the 'stop' event callback. + console.info('audio stop success'); + // The playback stops, the playback progress bar returns to 0, and the Play button is changed to the playable state. + }); + audioPlayer.on('reset', () => { // Set the 'reset' event callback. + console.info('audio reset success'); + // You can reconfigure the src attribute to play another audio file. + }); + audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback. + if (typeof(seekDoneTime) == 'undefined') { + console.info('audio seek fail'); return; - } - console.info('Current player status: ' + player.state); - console.info('Current player time: ' + player.currentTime); - player.seek(30000); // Seek for 30 seconds. - }); - player.on('stop', (err, action) => { - if (err) { - console.error('Error returned in the stop() callback.'); - return; - } - console.info('stop callback invoked. State:' + player.state); - player.reset(); - }); - player.on('dataLoad', (err, action) => { - if (err) { - console.error('Error returned in the dataLoad() callback.'); - return; - } - console.info('dataLoad callback invoked. Current time: ' + player.currentTime); - console.info('Duration of the source:' + player.duration); - player.play(); - }); - player.on('reset', (err, action) => { - if (err) { - console.error('Error returned in the reset() callback.'); - return; - } - console.info('reset callback invoked.'); - player.release(); - }); - player.on('finish', (err, action) => { - if (err) { - console.error('Error returned in the finish() callback.'); - return; } - console.info('finish callback invoked.'); - }); - player.on('timeUpdate', (seekTime, action) => { - console.info('Seek time: ' + seekTime); - console.info('Current player time: ' + player.currentTime); - var newTime = player.currentTime; - if(newTime == 30000) { - console.info('Seek succeeded. New time: ' + newTime); - } else { - console.error('Seek failed: ', + newTime); + console.info('audio seek success, and seek time is ' + seekDoneTime); + // The playback progress bar is updated to the seek position. + }); + audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + console.info('audio volumeChange success'); + // Display the updated volume. + }); + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + console.info('audio play finish'); + }); + audioPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); + console.info(`audio error called, errCode is ${error.code}`); + console.info(`audio error called, errMessage is ${error.message}`); + }); +} + +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} + +// 1. Create an audioPlayer instance. +let audioPlayer = media.createAudioPlayer(); +SetCallBack(audioPlayer); // Set the event callbacks. +// 2. Set the URI of the audio file. +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +// 3. Play the audio. +audioPlayer.play(); // The play() method can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is triggered. +// 4. Seek to the playback position. +audioPlayer.seek(30000); // Trigger the 'timeUpdate' event callback, and seek to 30000 ms for playback. +// 5. Set the volume. +audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback. +// 6. Pause the playback. +audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback. +// 7. Obtain the track information. +audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. + if (typeof (arrlist) != 'undefined') { + for (let i = 0; i < arrlist.length; i++) { + printfDescription(arrlist[i]); } - player.stop(); - }); - player.on('error', (err) => { - console.error('Player error: ${err.message}'); - }); - ``` - -3. Start playback. - ``` - var audioSourceMp3 = 'file://test.mp3'; - player.src = audioSourceMp3; - player.loop = true; - ``` + } else { + console.log(`audio getTrackDescription fail, error:${error.message}`); + } +}); +// 8. Stop playback. +audioPlayer.stop(); // Trigger the 'stop' event callback. +// 9. Reset the playback resources. +audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song. +// 10. Release the resource. +audioPlayer.release(); // Release the AudioPlayer resource. +audioPlayer = undefined; +``` + +### Normal Playback Scenario + +```js +function SetCallBack(audioPlayer) { + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. + }); + audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + }); + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + console.info('audio play finish'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; + }); +} + +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. +/* Set the URI of the audio file selected by the user. */ +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +``` + +### Switching to the Next Song + +```js +function SetCallBack(audioPlayer) { + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. + }); + audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + }); + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + console.info('audio play finish'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; + }); +} + +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. +/* Set the URI of the audio file selected by the user. */ +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +/* Send the instruction to switch to the next song after a period of time. */ +audioPlayer.reset(); +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/next.mp3'; +``` + +### Looping a Song + +```js +function SetCallBack(audioPlayer) { + audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Call the play() method to start the playback and trigger the 'play' event callback. + }); + audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + }); + audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete. + console.info('audio play finish'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; + }); +} + +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +SetCallBack(audioPlayer); // Set the event callbacks. +/* Set the URI of the audio file selected by the user. */ +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp3'; // Set the src attribute and trigger the 'dataLoad' event callback. +audioPlayer.loop = true; // Set the loop playback attribute. +``` diff --git a/en/application-dev/media/figures/en-us_image_20220117.jpg b/en/application-dev/media/figures/en-us_image_20220117.jpg new file mode 100644 index 0000000000000000000000000000000000000000..3442add1bf969cc8ea89d201cf2e6e6c42321b99 Binary files /dev/null and b/en/application-dev/media/figures/en-us_image_20220117.jpg differ diff --git a/en/application-dev/media/figures/playback-status.png b/en/application-dev/media/figures/playback-status.png deleted file mode 100755 index e0777e28838f6d2455233f2068339f8548f50c67..0000000000000000000000000000000000000000 Binary files a/en/application-dev/media/figures/playback-status.png and /dev/null differ diff --git a/en/application-dev/quick-start/import-sample-to-create-project.md b/en/application-dev/quick-start/import-sample-to-create-project.md index 9287c0694679ec14bfdbda15278caf6f1531e3bf..b05970a735b5a22a45f5717436f9261e721e91dc 100644 --- a/en/application-dev/quick-start/import-sample-to-create-project.md +++ b/en/application-dev/quick-start/import-sample-to-create-project.md @@ -6,11 +6,11 @@ After the OpenHarmony SDK is configured, you can get started to develop your app by **importing a sample project**. 1. On the DevEco Studio welcome page, select **Configure** or click the ![](figures/en-us_image_0000001118018452.png) icon, and choose **Settings** \> **Version Control** \> **Git**. Then click **Test** to check whether the Git tool has been installed. - - If the tool has been installed, import a sample by referring to [2](#li5947194711181). + - If the tool has been installed, import a sample by following the instructions in Step 2. ![](figures/en-us_image_0000001118018088.png) - - If the tool hasn't been installed, click **Download and Install**. DevEco Studio will automatically download and install it. Then import a sample by referring to [2](#li5947194711181). + - If the tool hasn't been installed, click **Download and Install**. DevEco Studio will automatically download and install it. Then import a sample by following the instructions in Step 2. ![](figures/en-us_image_0000001164498191.png) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index ea1585a4aca4f2addf6631e801f0f4267a50cf05..47a186f0c126877789c41f0b93923e72a500ed24 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -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) diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-Context.md index e2b51f2e3cdf0468fe08a8913d4630b80c28269a..ad42e566a0c64f94801f982541cdd5382d96c55c 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-Context.md @@ -1,28 +1,5 @@ # Context Module -## Applicable Devices - -| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device| -| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ | -| Context.getOrCreateLocalDir(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.getOrCreateLocalDir() | Yes| Yes| Yes| Yes| No| No| -| Context.verifyPermission(permission: string, options: PermissionOptions, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.verifyPermission(permission: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.verifyPermission(permission: string, options?: PermissionOptions) | Yes| Yes| Yes| Yes| No| No| -| Context.requestPermissionsFromUser(permissions: Array\, requestCode: number, resultCallback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.getApplicationInfo(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.getApplicationInfo() | Yes| Yes| Yes| Yes| No| No| -| Context.getBundleName(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.getBundleName() | Yes| Yes| Yes| Yes| No| No| -| Context.getProcessInfo(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.getProcessInfo() | Yes| Yes| Yes| Yes| No| No| -| Context.getElementName(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.getElementName() | Yes| Yes| Yes| Yes| No| No| -| Context.getProcessName(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.getProcessName() | Yes| Yes| Yes| Yes| No| No| -| Context.getCallingBundle(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| Context.getCallingBundle() | Yes| Yes| Yes| Yes| No| No| - ## Modules to Import ```js diff --git a/en/application-dev/reference/apis/js-apis-ability-context.md b/en/application-dev/reference/apis/js-apis-ability-context.md new file mode 100644 index 0000000000000000000000000000000000000000..5d85731dc2ee337581c5fa38d7d52d60170675d4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -0,0 +1,217 @@ +# AbilityContext + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +Implements the ability context. This module is inherited from **Context**. + + +## Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| abilityInfo | AbilityInfo | Yes| No| Ability information.| +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| + + +## startAbility + +startAbility(want: Want, callback: AsyncCallback<void>): void + +Starts an ability. This method uses a callback to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +- Example + ``` + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" + }; + this.context.startAbility(want, (error) => { + console.log("error.code = " + error.code) + }) + ``` + + +## startAbility + +startAbility(want: Want): Promise<void>; + +Starts an ability. This method uses a promise to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +- Example + ``` + var want = { + "deviceId": "", + "bundleName": "com.extreme.test", + "abilityName": "com.extreme.test.MainAbility" + }; + this.context.startAbility(want) + .then((data) => { + console.log('Operation successful.') + }).catch((error) => { + console.log('Operation failed.'); + }) + ``` + + +## startAbilityForResult + +startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; + +Starts an ability. This method uses a callback to return the execution result when the ability is terminated. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| + | callback | Callback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| + + +- Example + ``` + this.context.startAbilityForResult( + {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}, + (error, result) => { + console.log("startAbilityForResult AsyncCallback is called, error.code = " + error.code) + console.log("startAbilityForResult AsyncCallback is called, result.resultCode = " + result.resultCode) + } + ); + ``` + + +## startAbilityForResult + +startAbilityForResult(want: Want): Promise<AbilityResult>; + +Starts an ability. This method uses a promise to return the execution result when the ability is terminated. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the **Want** used for starting an ability.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| + +- Example + ``` + this.context.startAbilityForResult({bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo2"}).then((result) => { + console.log("startAbilityForResult Promise.resolve is called, result.resultCode = " + result.resultCode) + }, (error) => { + console.log("startAbilityForResult Promise.Reject is called, error.code = " + error.code) + }) + ``` + + +## terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void; + +Terminates this ability. This method uses a callback to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringfy(err); + } + ``` + + +## terminateSelf + +terminateSelf(): Promise<void>; + +Terminates this ability. This method uses a promise to return the result. + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.terminateSelf(want).then((data) => { + console.log('success:' + JSON.stringfy(data)); + )).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); + }); + ``` + + +## terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; + +Terminates this ability. This method uses a callback to return the information to the caller of **startAbilityForResult**. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| + | callback | Callback<void> | No| Callback used to return the information.| + +- Example + ``` + this.context.terminateSelfWithResult( + { + want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, + resultCode: 100 + }, (error) => { + console.log("terminateSelfWithResult is called = " + error.code) + } + ); + ``` + + +## terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult): Promise<void>; + +Terminates this ability. This method uses a promise to return information to the caller of **startAbilityForResult**. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +- Example + ``` + this.context.terminateSelfWithResult( + { + want: {bundleName: "com.extreme.myapplication", abilityName: "MainAbilityDemo"}, + resultCode: 100 + }).then((result) => { + console.log("terminateSelfWithResult") + } + ) + ``` diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index de50ce278c4c0e8bae9541ddec417efceb2e0c94..eb6fbc82775e1631bd852319de66b4318a1c28de 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -337,13 +337,6 @@ Enumerates the audio channels. | :----- | :------------ | :--------------- | | CHANNEL_1 | 0x1 << 0 | Channel count 1. | | CHANNEL_2 | 0x1 << 1 | Channel count 2. | -| CHANNEL_3 | 0x1 << 2 | Channel count 3. | -| CHANNEL_4 | 0x1 << 3 | Channel count 4. | -| CHANNEL_5 | 0x1 << 4 | Channel count 5. | -| CHANNEL_6 | 0x1 << 5 | Channel count 6. | -| CHANNEL_7 | 0x1 << 6 | Channel count 7. | -| CHANNEL_8 | 0x1 << 7 | Channel count 8. | - ## AudioSamplingRate8+ Enumerates the audio sampling rates. diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md new file mode 100644 index 0000000000000000000000000000000000000000..e9962bab099f10ea3a8e662d6615ba31c1c6f574 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -0,0 +1,123 @@ +# Background Task Management + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +``` +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +``` + + +## Required Permissions + +None + + +## backgroundTaskManager.requestSuspendDelay + +requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo + +Requests delayed suspension after the application switches to the background. + +The default duration of delayed suspension is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level. + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | reason | string | Yes| Reason for delayed transition to the suspended state.| + | callback | Callback<void> | Yes| Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.| + +- **Return value** + | Type| Description| + | -------- | -------- | + | [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.| + +- **Example** + ``` + let myReason = 'test requestSuspendDelay'; + let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { + console.info("Request suspension delay will time out."); + }) + ``` + + +## backgroundTaskManager.getRemainingDelayTime + +getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void + +Obtains the remaining duration before the application is suspended. This method uses an asynchronous callback to return the result. + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | requestId | number | Yes| ID of the suspension delay request.| + | callback | AsyncCallback<number> | Yes| Callback used to return the remaining duration before the application is suspended, in milliseconds.| + +- **Example** + ``` + let id = 1; + backgroundTaskManager.getRemainingDelayTime(id, (err, res) => { + if(err.data === 0) { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); + } else { + console.log('promise => Operation failed. Cause: ' + err.data); + } + }) + ``` + + +## backgroundTaskManager.getRemainingDelayTime + +getRemainingDelayTime(requestId: number): Promise<number> + +Obtains the remaining duration before the application is suspended. This method uses a promise to return the result. + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | requestId | number | Yes| ID of the suspension delay request.| + +- **Return value** + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.| + +- **Example** + ``` + let id = 1; + backgroundTaskManager.getRemainingDelayTime(id).then( res => { + console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); + }).catch( err => { + console.log('promise => Operation failed. Cause: ' + err.data); + }) + ``` + + +## backgroundTaskManager.cancelSuspendDelay + +cancelSuspendDelay(requestId: number): void + +Cancels the suspension delay. + +- **Parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | requestId | number | Yes| ID of the suspension delay request.| + +- **Example** + ``` + backgroundTaskManager.cancelSuspendDelay(id); + ``` + + +#### DelaySuspendInfo + +Provides the information about the suspension delay. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| requestId | number | Yes| ID of the suspension delay request.| +| actualDelayTime | number | Yes| Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.| diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md index a4c533575f626f9b7c4dffb968da7809e0fe84e8..c573b79ab8f0af4128f4cbf950167607a7935baa 100644 --- a/en/application-dev/reference/apis/js-apis-brightness.md +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -1,6 +1,6 @@ # Brightness ->![](../../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 @@ -9,6 +9,10 @@ import brightness from '@ohos.brightness'; ``` +## System Capabilities + +SystemCapability.PowerManager.DisplayPowerManager + ## brightness.setValue setValue\(value: number\) diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index e3f7238a1279728877203071f3e2bfd5b391fa2e..9ef873e163d62b5391c97a0941ef1226c09cd6a1 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -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\) | Yes| Yes| Yes| Yes| No| -| CommonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| -| CommonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| -| CommonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Yes| Yes| Yes| Yes| No| -| CommonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| -| CommonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\) | Yes| Yes| Yes| Yes| No| - ## Required Permissions | Common Event Macro| Common Event Name| Subscriber Permissions| diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md new file mode 100644 index 0000000000000000000000000000000000000000..7d3d923d94128325d197e6fda5d97c8c08752cd6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -0,0 +1,277 @@ +# XML-to-JavaScript Conversion + +>![](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 convertxml from '@ohos.convertxml'; +``` + +## Required Permissions + +None + +## ConvertXML + +### convert + +convert\(xml: string, options?: ConvertOptions\) : Object + +Converts an XML text into a JavaScript object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

xml

+

string

+

Yes

+

XML text to convert.

+

options

+

ConvertOptions

+

No

+

Settings of the convert operation.

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

Type

+

Description

+

string

+

JavaScript object.

+
+ +- Example + + ``` + var xml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; + var conv = new convertxml.ConvertXML(); + var result1 = conv.convert(xml, {trim: false, ignoreDeclaration: false}); + console.log(result1) + ``` + + +## ConvertOptions + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

trim

+

boolean

+

No

+

Whether to trim the whitespace characters before and after the text. The default value is false.

+

ignoreDeclaration

+

boolean

+

No

+

Whether to ignore the XML declaration. The default value is false.

+

ignoreInstruction

+

boolean

+

No

+

Whether to ignore the XML processing instruction. The default value is false.

+

ignoreAttributes

+

boolean

+

No

+

Whether to print attributes across multiple lines and indent attributes. The default value is false.

+

ignoreComment

+

boolean

+

No

+

Whether to ignore element comments. The default value is false.

+

ignoreCDATA

+

boolean

+

No

+

Whether to ignore the element's CDATA information. The default value is false.

+

ignoreDoctype

+

boolean

+

No

+

Whether to ignore the element's Doctype information. The default value is false.

+

ignoreText

+

boolean

+

No

+

Whether to ignore the element's text information. The default value is false.

+

declarationKey

+

string

+

No

+

Name of the attribute key for declaration in the output object. The default value is _declaration.

+

instructionKey

+

string

+

No

+

Name of the attribute key for instruction in the output object. The default value is _instruction.

+

attributesKey

+

string

+

No

+

Name of the attribute key for attributes in the output object. The default value is _attributes.

+

textKey

+

string

+

No

+

Name of the attribute key for text in the output object. The default value is _text.

+

cdataKey

+

string

+

No

+

Name of the attribute key for CDATA in the output object. The default value is _cdata.

+

doctypeKey

+

string

+

No

+

Name of the attribute key for Doctype in the output object. The default value is _doctype.

+

commentKey

+

string

+

No

+

Name of the attribute key for comment in the output object. The default value is _comment.

+

parentKey

+

string

+

No

+

Name of the attribute key for parent in the output object. The default value is _parent.

+

typeKey

+

string

+

No

+

Name of the attribute key for type in the output object. The default value is _type.

+

nameKey

+

string

+

No

+

Name of the attribute key for name in the output object. The default value is _name.

+

elementsKey

+

string

+

No

+

Name of the attribute key for elements in the output object. The default value is _elements.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md index 39d8c92342f998da7e18b8731e47a0f9929a5b92..dc09e186854d248a51cb7c1260de5db3febb3dee 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md @@ -1,33 +1,4 @@ -### DataAbilityHelper Module (JavaScript SDK APIs) - -#### Applicable Devices - -| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device| -| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ | -| DataAbilityHelper.openFile(uri: string, mode: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.openFile(uri: string, mode: string) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.on(type: 'dataChange', uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.off(type: 'dataChange', uri: string, callback?: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback>) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.getFileTypes(uri: string, mimeTypeFilter: string) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.getType(uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.getType(uri: string) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.normalizeUri(uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.normalizeUri(uri: string) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.denormalizeUri(uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.denormalizeUri(uri: string) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.notifyChange(uri: string, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.notifyChange(uri: string) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.insert(uri: string, valuesBucket: rdb.ValuesBucket, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.insert(uri: string, valuesBucket: rdb.ValuesBucket) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.batchInsert(uri: string, valuesBuckets: Array, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.batchInsert(uri: string, valuesBuckets: Array) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.delete(uri: string, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.delete(uri: string, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.update(uri: string, valuesBucket: rdb.ValuesBucket, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates, callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| DataAbilityHelper.query(uri: string, columns: Array\, predicates: dataAbility.DataAbilityPredicates) | Yes| Yes| Yes| Yes| No| No| +# DataAbilityHelper Module (JavaScript SDK APIs) #### Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-extension-context.md b/en/application-dev/reference/apis/js-apis-extension-context.md new file mode 100644 index 0000000000000000000000000000000000000000..be430dce1a7275fd27d7c387199c0d353b8e8d02 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-extension-context.md @@ -0,0 +1,14 @@ +# ExtensionContext + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +Implements the extension context. This module is inherited from **Context**. + + +## Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-featureAbility.md index 88279ca8591d41229d43084cc1cd4dda603dd107..c07e862c47c43c70bff819c4e2e4d41ed23c2bce 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-featureAbility.md @@ -1,27 +1,5 @@ # FeatureAbility Module (JavaScript) -#### Applicable Devices - -| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device| -| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ | -| FeatureAbility.startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.startAbility(parameter: StartAbilityParameter): Promise\ | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.acquireDataAbilityHelper(uri: string): DataAbilityHelper | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.startAbilityForResult(parameter: StartAbilityParameter): Promise\ | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.terminateSelfWithResult(parameter: AbilityResult): Promise\ | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.hasWindowFocus(callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.hasWindowFocus(): Promise\ | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.getWant(callback: AsyncCallback\) | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.getWant(): void | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.getContext(): Context | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.terminateSelf(callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.terminateSelf(): Promise\ | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.connectAbility(request: Want, options:ConnectOptions): number | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.disconnectAbility(connection: number, callback:AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| -| FeatureAbility.disconnectAbility(connection: number): Promise\ | Yes| Yes| Yes| Yes| No| No| - #### Constraints APIs of the **FeatureAbility** module can be called only by Page abilities. diff --git a/en/application-dev/reference/apis/js-apis-formbindingdata.md b/en/application-dev/reference/apis/js-apis-formbindingdata.md new file mode 100644 index 0000000000000000000000000000000000000000..cf59cffd6eaf7cdd36176d0a8426627a7dd3620c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formbindingdata.md @@ -0,0 +1,51 @@ +# 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.| diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md new file mode 100644 index 0000000000000000000000000000000000000000..3368ad16eb84fb8477f4b086d372b5289f85d209 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formextension.md @@ -0,0 +1,171 @@ +# 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); + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-formextensioncontext.md b/en/application-dev/reference/apis/js-apis-formextensioncontext.md new file mode 100644 index 0000000000000000000000000000000000000000..b4cf3bca0a580270658be8d19ce0fd4a7cf3b403 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-formextensioncontext.md @@ -0,0 +1,59 @@ +# 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 + +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\ | 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\ + +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\ | 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);}); + ``` diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index 6f684c8c06d674c9cc43cc409acd1c2e962129f7..0763a1598728414c51ec8036cbe2243235d012b0 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,10 +1,10 @@ -# Internationalization \(i18n\) +# Internationalization (i18n) + >![](../../public_sys-resources/icon-note.gif) **NOTE:** >- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. >- This module contains enhanced i18n APIs, which are not defined in ECMA 402. - ## Modules to Import ``` @@ -21,9 +21,10 @@ getDisplayLanguage\(language: string, locale: string, sentenceCase?: boolean\): Obtains the localized script for the specified language. -- Parameters +- Parameters + - - - - -

Name

Type

@@ -163,6 +164,58 @@ Obtains the localized script for the specified country. ``` +## i18n.isRTL8+ + +isRTL\(locale: string\): boolean + +Checks whether the localized script for the specified language is displayed from right to left. + +- Parameters + + + + + + + + + + + + +

Name

+

Type

+

Description

+

locale

+

string

+

Locale ID.

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

Type

+

Description

+

boolean

+

The value true indicates that the localized script is displayed from right to left, and value false indicates the opposite.

+
+ +- Example + + ``` + i18n.isRTL("zh-CN");// Since Chinese is not written from right to left, false is returned. + i18n.isRTL("ar-EG");// Since Arabic is written from right to left, true is returned. + ``` + + ## i18n.getSystemLanguage getSystemLanguage\(\): string @@ -253,3 +306,2086 @@ Obtains the system locale. ``` +## i18n.getCalendar8+ + +getCalendar\(locale: string, type? : string\): Calendar + +Obtains a **Calendar** object. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

Valid locale value, for example, zh-Hans-CN.

+

type

+

string

+

No

+

Valid calendar type. Currently, the valid types are as follows: buddhist, chinese, coptic, ethiopic, hebrew, gregory, indian, islamic_civil, islamic_tbla, islamic_umalqura, japanese, and persian. If this parameter is left unspecified, the default calendar type of the specified locale is used.

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

Type

+

Description

+

Calendar

+

Calendar object.

+
+ +- Example + + ``` + i18n.getCalendar("zh-Hans", "gregory"); + ``` + + +## Calendar8+ + +### setTime8+ + +setTime\(date: Date\): void + +Sets the date for this **Calendar** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

date

+

Date

+

Yes

+

Date to be set for the Calendar object.

+
+ + +- Example + + ``` + var calendar = I18n.getCalendar("en-US", "gregory"); + var date = new Date(2021, 10, 7, 8, 0, 0, 0); + calendar.setTime(date); + ``` + + +### setTime8+ + +setTime\(time: number\): void + +Sets the date and time for this **Calendar** object. The value is represented by the number of milliseconds that have elapsed since the Unix epoch \(00:00:00 UTC on January 1, 1970\). + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

time

+

number

+

Yes

+

Number of milliseconds that have elapsed since the Unix epoch.

+
+ + +- Example + + ``` + var calendar = I18n.getCalendar("en-US", "gregory"); + calendar.setTime(10540800000); + ``` + + +### set8+ + +set\(year: number, month: number, date:number, hour?: number, minute?: number, second?: number\): void + +Sets the year, month, day, hour, minute, and second for this **Calendar** object. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

year

+

number

+

Yes

+

Year to set.

+

month

+

number

+

Yes

+

Month to set.

+

date

+

number

+

Yes

+

Day to set.

+

hour

+

number

+

No

+

Hour to set.

+

minute

+

number

+

No

+

Minute to set.

+

second

+

number

+

No

+

Second to set.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("zh-Hans"); + calendar.setTime(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 + ``` + + +### setTimeZone8+ + +setTimeZone\(timezone: string\): void + +Sets the time zone of this **Calendar** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

timezone

+

string

+

Yes

+

Time zone, for example, Asia/Shanghai.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("zh-Hans"); + calendar.setTimeZone("Asia/Shanghai"); + ``` + + +### getTimeZone8+ + +getTimeZone\(\): string + +Obtains the time zone of this **Calendar** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Time zone of the Calendar object.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("zh-Hans"); + calendar.setTimeZone("Asia/Shanghai"); + calendar.getTimeZone(); // Asia/Shanghai" + ``` + + +### getFirstDayOfWeek8+ + +getFirstDayOfWeek\(\): number + +Obtains the start day of a week for this **Calendar** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Start day of a week. The value 1 indicates Sunday, and value 7 indicates Saturday.

+
+ + +- Example + + ``` + var calendar = I18n.getCalendar("en-US", "gregory"); + calendar.getFirstDayOfWeek(); + ``` + + +### setFirstDayOfWeek8+ + +setFirstDayOfWeek\(value: number\): void + +Sets the start day of a week for this **Calendar** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

number

+

No

+

Start day of a week. The value 1 indicates Sunday, and value 7 indicates Saturday.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("zh-Hans"); + calendar.setFirstDayOfWeek(0); + ``` + + +### getMinimalDaysInFirstWeek8+ + +getMinimalDaysInFirstWeek\(\): number + +Obtains the minimum number of days in the first week of a year. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Minimum number of days in the first week of a year.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("zh-Hans"); + calendar.getMinimalDaysInFirstWeek(); + ``` + + +### setMinimalDaysInFirstWeek8+ + +setMinimalDaysInFirstWeek\(value: number\): void + +Sets the minimum number of days in the first week of a year. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

number

+

No

+

Minimum number of days in the first week of a year.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("zh-Hans"); + calendar.setMinimalDaysInFirstWeek(3); + ``` + + +### get8+ + +get\(field: string\): number + +Obtains the value of the specified field in the **Calendar** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

field

+

string

+

Yes

+

Value of the specified field in the Calendar object. Currently, the valid fields are as follows: era, year, month, week_of_year, week_of_month, date, day_of_year, day_of_week, day_of_week_in_month, hour, hour_of_day, minute, second, millisecond, zone_offset, dst_offset, year_woy, dow_local, extended_year, julian_day, milliseconds_in_day, and is_leap_month.

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

Type

+

Description

+

number

+

Value of the specified field. For example, if the year in the internal date of this Calendar object is 1990, the get("year") function will return 1990.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("zh-Hans"); + calendar.setTime(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 + calendar.get("hour_of_day"); // 8 + ``` + + +### getDisplayName8+ + +getDisplayName\(locale: string\): string + +Obtains the name of the **Calendar** object displayed for the specified locale. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

Locale for which the name of the Calendar object is displayed. For example, if locale is en-US, the name of the Buddhist calendar will be Buddhist Calendar.

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

Type

+

Description

+

string

+

Name of the Calendar object displayed for the specified locale.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("en-US", "buddhist"); + calendar.getDisplayName("zh"); // Obtain the name of the Buddhist calendar in zh. + ``` + + +### isWeekend8+ + +isWeekend\(date?: Date\): boolean + +Checks whether the specified date in this **Calendar** object is a weekend. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

date

+

Date

+

No

+

Specified date in this Calendar object. If this parameter is left unspecified, the system checks whether the current date in the Calendar object is a weekend.

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

Type

+

Description

+

boolean

+

The value true indicates that the date is a weekend, and value false indicates a weekday.

+
+ +- Example + + ``` + var calendar = i18n.getCalendar("zh-Hans"); + calendar.setTime(2021, 11, 11, 8, 0, 0); // Set the time to 2021.11.11 08:00:00. + calendar.isWeekend(); // false + var date = new Date(2011, 11, 6, 9, 0, 0); + calendar.isWeekend(date); // true + ``` + + +## PhoneNumberFormat8+ + +### constructor8+ + +constructor\(country: string, options?: PhoneNumberFormatOptions\) + +Creates a **PhoneNumberFormat** object. + +Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

country

+

string

+

Yes

+

Country or region to which the phone number to be formatted belongs.

+

options

+

PhoneNumberFormatOptions

+

No

+

Options of the PhoneNumberFormat object.

+
+ +- Example + + ``` + var phoneNumberFormat= new i18n.PhoneNumberFormat("CN", {"type": "E164"}); + ``` + + +### isValidNumber8+ + +isValidNumber\(number: string\): boolean + +Checks whether the format of the specified phone number is valid. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

number

+

string

+

Yes

+

Phone number to be checked.

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

Type

+

Description

+

boolean

+

The value true indicates the phone number format is valid, and value false indicates the opposite.

+
+ + +- Example + + ``` + var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); + phonenumberfmt.isValidNumber("15812312312"); + ``` + + +### format8+ + +format\(number: string\): string + +Formats a phone number. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

number

+

string

+

Yes

+

Phone number to be formatted.

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

Type

+

Description

+

string

+

Formatted phone number.

+
+ + +- Example + + ``` + var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); + phonenumberfmt.format("15812312312"); + ``` + + +## PhoneNumberFormatOptions8+ + +Defines the options for this **PhoneNumberFormat** object. + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

type

+

string

+

Yes

+

Yes

+

Format type of a phone number. The available options are as follows: E164, INTERNATIONAL, NATIONAL, and RFC3966.

+
+ +## UnitInfo8+ + +Defines the measurement unit information. + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

unit

+

string

+

Yes

+

Yes

+

Name of the measurement unit, for example, meter, inch, or cup.

+

measureSystem

+

string

+

Yes

+

Yes

+

Measurement system. The value can be SI, US, or UK.

+
+ +## Util8+ + +### unitConvert8+ + +unitConvert\(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string\): string + +Converts one measurement unit into another and formats the unit based on the specified locale and style. + +- Parameters + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

fromUnit

+

UnitInfo

+

Yes

+

Measurement unit to be converted.

+

toUnit

+

UnitInfo

+

Yes

+

Measurement unit to be converted to.

+

value

+

number

+

Yes

+

Value of the measurement unit to be converted.

+

locale

+

string

+

Yes

+

Locale used for formatting, for example, zh-Hans-CN.

+

style

+

string

+

No

+

Style used for formatting. The value can be long, short, or medium.

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

Type

+

Description

+

string

+

Character string obtained after formatting based on the measurement unit specified by toUnit.

+
+ + +- Example + + ``` + I18n.Util.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); + ``` + + +## i18n.getInstance8+ + +getInstance\(locale?: string\): IndexUtil + +Creates an **IndexUtil** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

No

+

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

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

Type

+

Description

+

IndexUtil

+

IndexUtil object mapping to the specified locale.

+
+ + +- Example + + ``` + var indexUtil= i18n.getInstance("zh-CN"); + ``` + + +## IndexUtil8+ + +### getIndexList8+ + +getIndexList\(\): Array + +Obtains the index list for this **locale** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Array<string>

+

Index list for this locale.

+
+ + +- Example + + ``` + var indexUtil = i18n.getInstance("zh-CN"); + var indexList = indexUtil.getIndexList(); + ``` + + +### addLocale8+ + +addLocale\(locale: string\) + +Adds the index of the new **locale** object to the index list. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

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

+
+ + +- Example + + ``` + var indexUtil = i18n.getInstance("zh-CN"); + indexUtil.addLocale("en-US"); + ``` + + +### getIndex8+ + +getIndex\(text: string\): string + +Obtains the index of a **text** object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

text

+

string

+

Yes

+

text object whose index is to be obtained.

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

Type

+

Description

+

string

+

Index of the text object.

+
+ + +- Example + + ``` + var indexUtil= i18n.getInstance("zh-CN"); + indexUtil.getIndex("hi"); // Return h. + ``` + + +## Character8+ + +### isDigit8+ + +isDigit\(char: string\): boolean + +Checks whether the input character string is comprised of digits. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

boolean

+

The value true indicates that the input character is a digit, and value false indicates the opposite.

+
+ + +- Example + + ``` + var isdigit = Character.isDigit("1"); // Return true. + ``` + + +### isSpaceChar8+ + +isSpaceChar\(char: string\): boolean + +Checks whether the input character is comprised of space. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

boolean

+

The value true indicates that the input character is a space, and value false indicates the opposite.

+
+ + +- Example + + ``` + var isspacechar = Character.isSpaceChar("a"); // Return false. + ``` + + +### isWhitespace8+ + +isWhitespace\(char: string\): boolean + +Checks whether the input character is comprised of white space. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

boolean

+

The value true indicates that the input character is a white space, and value false indicates the opposite.

+
+ + +- Example + + ``` + var iswhitespace = Character.isWhitespace("a"); // Return false. + ``` + + +### isRTL8+ + +isRTL\(char: string\): boolean + +Checks whether the input character string is of the right to left \(RTL\) language. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

boolean

+

The value true indicates that the input character is of the RTL language, and value false indicates the opposite.

+
+ + +- Example + + ``` + var isrtl = Character.isRTL("a"); // Return false. + ``` + + +### isIdeograph8+ + +isIdeograph\(char: string\): boolean + +Checks whether the input character string is comprised of ideographic characters. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

boolean

+

The value true indicates that the input character is an ideographic character, and value false indicates the opposite.

+
+ + +- Example + + ``` + var isideograph = Character.isIdeograph("a"); // Return false. + ``` + + +### isLetter8+ + +isLetter\(char: string\): boolean + +Checks whether the input character string is comprised of letters. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

boolean

+

The value true indicates that the input character is a letter, and value false indicates the opposite.

+
+ + +- Example + + ``` + var isletter = Character.isLetter("a"); // Return true. + ``` + + +### isLowerCase8+ + +isLowerCase\(char: string\): boolean + +Checks whether the input character is comprised of lowercase letters. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

boolean

+

The value true indicates that the input character is a lowercase letter, and value false indicates the opposite.

+
+ + +- Example + + ``` + var islowercase = Character.isLowerCase("a"); // Return true. + ``` + + +### isUpperCase8+ + +isUpperCase\(char: string\): boolean + +Checks whether the input character is comprised of uppercase letters. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

boolean

+

The value true indicates that the input character is an uppercase letter, and value false indicates the opposite.

+
+ + +- Example + + ``` + var isuppercase = Character.isUpperCase("a"); // Return false. + ``` + + +### getType8+ + +getType\(char: string\): string + +Obtains the type of the input character string. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

char

+

string

+

Yes

+

Input character.

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

Type

+

Description

+

string

+

Type of the input character.

+
+ + +- Example + + ``` + var type = Character.getType("a"); + ``` + + +## i18n.getLineInstance8+ + +getLineInstance\(locale: string\): BreakIterator + +Obtains a [BreakIterator](#section1312302611613) object for text segmentation. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

Valid locale value, for example, zh-Hans-CN. The BreakIterator object segments text according to the rules of the specified locale.

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

Type

+

Description

+

BreakIterator

+

Break iterator used for text segmentation.

+
+ +- Example + + ``` + i18n.getLineInstance("en"); + ``` + + +## BreakIterator8+ + +### setLineBreakText8+ + +setLineBreakText\(text: string\): void + +Sets the text to be processed by the [BreakIterator](#section1312302611613) object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

text

+

string

+

Yes

+

Text to be processed by the BreakIterator object.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + ``` + + +### getLineBreakText8+ + +getLineBreakText\(\): string + +Obtains the text being processed by the [BreakIterator](#section1312302611613) object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Text being processed by the BreakIterator object.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + iterator.getLineBreakText(); // Apple is my favorite fruit. + ``` + + +### current8+ + +current\(\): number + +Obtains the position of the [BreakIterator](#section1312302611613) object in the text being processed. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Position of the BreakIterator object in the text being processed.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + breakIter.current(); // 0 + ``` + + +### first8+ + +first\(\): number + +Puts the [BreakIterator](#section1312302611613) object to the first text boundary, which is always at the beginning of the processed text. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Offset to the first text boundary of the processed text.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + breakIter.first(); // 0 + ``` + + +### last8+ + +last\(\): number + +Puts the [BreakIterator](#section1312302611613) object to the last text boundary, which is always the next position after the end of the processed text. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Offset of the last text boundary of the processed text.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + iterator.last(); // 27 + ``` + + +### next8+ + +next\(index?: number\): number + +Moves the [BreakIterator](#section1312302611613) object backward by the specified number of text boundaries if the specified index is a positive number. If the index is a negative number, the [BreakIterator](#section1312302611613) object will be moved forward by the corresponding number of text boundaries. If no index is specified, the index will be treated as **1**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

index

+

number

+

No

+

Number of text boundaries by which the BreakIterator object is moved. A positive value indicates that the text boundary is moved backward, and a negative value indicates the opposite. If no index is specified, the index will be treated as 1.

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

Type

+

Description

+

number

+

Position of the BreakIterator object in the text after it is moved by the specified number of text boundaries. The value -1 is returned if the position of the BreakIterator object is outside of the processed text after it is moved by the specified number of text boundaries.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + iterator.first(); // 0 + iterator.next(); // 6 + iterator.next(10); // -1 + ``` + + +### previous8+ + +previous\(\): number + +Moves the [BreakIterator](#section1312302611613) object to the previous text boundary. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Position of the BreakIterator object in the text after it is moved to the previous text boundary. The value -1 is returned if the position of the BreakIterator object is outside of the processed text after it is moved by the specified number of text boundaries.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + iterator.first(); // 0 + iterator.next(3); // 12 + iterator.previous(); // 9 + ``` + + +### following8+ + +following\(offset: number\): number + +Moves the [BreakIterator](#section1312302611613) object to the text boundary after the position specified by the offset. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

offset

+

number

+

Yes

+

Offset to the position before the text boundary to which the BreakIterator object is moved.

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

Type

+

Description

+

number

+

The value -1 is returned if the text boundary to which the BreakIterator object is moved is outside of the processed text.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + iterator.following(0); // 6 + iterator.following(100); // -1 + iterator.current(); // 27 + ``` + + +### isBoundary8+ + +isBoundary\(offset: number\): boolean + +Checks whether the position specified by the offset is a text boundary. If **true** is returned, the [BreakIterator](#section1312302611613) object is moved to the position specified by the offset. If **false** is returned, the [BreakIterator](#section1312302611613) object is moved to the text boundary after the position specified by the offset, which is equivalent to calling [following\(offset\)](#section1743155314301). + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

offset

+

number

+

Yes

+

Position to check.

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

Type

+

Description

+

boolean

+

The value true indicates that the position specified by the offset is a text boundary, and value false indicates the opposite.

+
+ + +- Example + + ``` + iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit."); + iterator.isBoundary(0); // true; + iterator.isBoundary(5); // false; + ``` + diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 7d182fd07eb55b848088f153625278a4e469e405..f18b8b8bf316bb4b680d03cef06dbcd19e14bbfe 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,10 +1,9 @@ -# Internationalization \(intl\) +# Internationalization (intl) >![](../../public_sys-resources/icon-note.gif) **NOTE:** >- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. >- This module contains standard i18n APIs, which are defined in ECMA 402. - ## Modules to Import ``` @@ -17,7 +16,7 @@ None ## Locale -### Attributes +### Attributes - - - - - - - - -

Name

@@ -40,7 +39,7 @@ None

No

Language associated with the locale.

+

Language associated with the locale, for example, zh.

script

@@ -51,7 +50,7 @@ None

No

Script type of the language.

+

Script type of the language, for example, Hans.

region

@@ -62,7 +61,7 @@ None

No

Region associated with the locale.

+

Region associated with the locale, for example, CN.

baseName

@@ -73,7 +72,7 @@ None

No

Basic information about the locale.

+

Basic key information about the locale, which consists of the language, script, and region, for example, zh-Hans-CN.

caseFirst

@@ -84,7 +83,7 @@ None

No

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

+

Whether case is taken into account for the locale's collation rules. The value can be upper, lower, or false.

calendar

@@ -95,7 +94,7 @@ None

No

Calendar for the locale.

+

Calendar for the locale. The value can be buddhist, chinese, coptic, dangi, ethioaa, ethiopic, gregory, hebrew, indian, islamic, islamic-umalqura, islamic-tbla, islamic-civil, islamic-rgsa, iso8601, japanese, persian, roc, or islamicc.

collation

@@ -106,7 +105,7 @@ None

No

Collation rules for the locale.

+

Collation rules for the locale. The value can be any of the following: big5han, compat, dict, direct, ducet, eor, gb2312, phonebk, phonetic, pinyin, reformed, searchjl, stroke, trad, unihan, and zhuyin.

hourCycle

@@ -117,7 +116,7 @@ None

No

Time system for the locale.

+

Time system for the locale. The value can be h11, h12, h23, or h24.

numberingSystem

@@ -128,7 +127,7 @@ None

No

Numbering system for the locale.

+

Numbering system for the locale. The value can be any of the following: adlm, ahom, arab, arabext, bali, beng, bhks, brah, cakm, cham, deva, diak, fullwide, gong, gonm, gujr, guru, hanidec, hmng, hmnp, java, kali, khmr, knda, lana, lanatham, laoo, latn, lepc, limb, mathbold, mathdbl, mathmono, mathsanb, mathsans, mlym, modi, mong, mroo, mtei, mymr, mymrshan, mymrtlng, newa, nkoo, olck, orya, osma, rohg, saur, segment, shrd, sind, sinh, sora, sund, takr, talu, tamldec, telu, thai, tibt, tirh, vaii, wara, and wcho.

numeric

@@ -145,9 +144,9 @@ None
-### constructor +### constructor -constructor\(locale: string, options?:options\) +constructor\(locale: string, options?: options\) Creates a **Locale** object. @@ -173,15 +172,6 @@ Creates a **Locale** object.

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

options

-

options

-

No

-

Options for creating the Locale object.

-
@@ -193,7 +183,7 @@ Creates a **Locale** object. ``` -### toString +### toString toString\(\): string @@ -225,7 +215,7 @@ Converts locale information to a string. ``` -### maximize +### maximize maximize\(\): Locale @@ -240,7 +230,7 @@ Maximizes information of the **Locale** object. If the script and locale infor -

Locale

+

Locale

Locale object with the maximized information.

@@ -257,7 +247,7 @@ Maximizes information of the **Locale** object. If the script and locale infor ``` -### minimize +### minimize minimize\(\): Locale @@ -272,7 +262,7 @@ Minimizes information of the **Locale** object. If the script and locale infor -

Locale

+

Locale

Locale object with the minimized information.

@@ -291,9 +281,9 @@ Minimizes information of the **Locale** object. If the script and locale infor ## DateTimeFormat -### constructor +### constructor -constructor\(locale: string, options?:DateTimeOptions\) +constructor\(locale: string, options?: DateTimeOptions\) Creates a **DateTimeOptions** object for the specified locale. @@ -321,11 +311,11 @@ Creates a **DateTimeOptions** object for the specified locale.

options

-

DateTimeOptions

+

DateTimeOptions

No

-

Options of the DateTimeFormat object.

+

Options for creating a DateTimeFormat object.

@@ -339,9 +329,9 @@ Creates a **DateTimeOptions** object for the specified locale. ``` -### constructor +### constructor -constructor\(locales: Array, options?:DateTimeOptions\) +constructor\(locales: Array, options?: DateTimeOptions\) Creates a **DateTimeOptions** object for the specified array of locales. @@ -369,11 +359,11 @@ Creates a **DateTimeOptions** object for the specified array of locales.

options

-

DateTimeOptions

+

DateTimeOptions

No

-

Options of the DateTimeFormat object.

+

Options for creating a DateTimeFormat object.

@@ -387,9 +377,9 @@ Creates a **DateTimeOptions** object for the specified array of locales. ``` -### format +### format -format\(date: Date\): string; +format\(date: Date\): string Formats the specified date and time. @@ -445,9 +435,9 @@ Formats the specified date and time. ``` -### formatRange +### formatRange -formatRange\(fromDate: Date, toDate: Date\): string; +formatRange\(fromDate: Date, toDate: Date\): string Formats the specified date range. @@ -513,11 +503,11 @@ Formats the specified date range. ``` -### resolvedOptions +### resolvedOptions resolvedOptions\(\): DateTimeOptions -Obtains the options of the **DateTimeFormat** object. +Obtains the formatting options for **DateTimeFormat** object. - Return values @@ -528,9 +518,9 @@ Obtains the options of the **DateTimeFormat** object. -

DateTimeOptions

+

DateTimeOptions

-

Options of the DateTimeFormat object.

+

Formatting options for DateTimeFormat objects.

@@ -545,193 +535,7 @@ Obtains the options of the **DateTimeFormat** object. ``` -## NumberFormat - -### constructor - -constructor\(locale: string, options?:NumberOptions\) - -Creates a **NumberFormat** object for the specified locale. - -Parameters - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Mandatory

-

Description

-

locale

-

string

-

Yes

-

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

-

options

-

NumberOptions

-

No

-

Options of the NumberFormat object.

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

Name

-

Type

-

Mandatory

-

Description

-

locales

-

Array<string>

-

Yes

-

An array of strings containing locale information.

-

options

-

NumberOptions

-

No

-

Options of the NumberFormat object.

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

Name

-

Type

-

Mandatory

-

Description

-

number

-

number

-

Yes

-

Number to be formatted.

-
- -- Return values - - - - - - - - - - -

Type

-

Description

-

string

-

Formatted number.

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

Type

-

Description

-

NumberOptions

-

Options of the NumberFormat object.

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

No

-

Locale information.

+

Locale, for example, zh-Hans-CN.

dateStyle

@@ -789,7 +593,7 @@ Provides the options for the **DateTimeFormat** object.

Yes

-

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

+

Time system for the locale. The value can be h11, h12, h23, or h24.

timeZone

@@ -811,7 +615,7 @@ Provides the options for the **DateTimeFormat** object.

Yes

-

Numbering system.

+

Numbering system for the locale. The value can be any of the following: adlm, ahom, arab, arabext, bali, beng, bhks, brah, cakm, cham, deva, diak, fullwide, gong, gonm, gujr, guru, hanidec, hmng, hmnp, java, kali, khmr, knda, lana, lanatham, laoo, latn, lepc, limb, mathbold, mathdbl, mathmono, mathsanb, mathsans, mlym, modi, mong, mroo, mtei, mymr, mymrshan, mymrtlng, newa, nkoo, olck, orya, osma, rohg, saur, segment, shrd, sind, sinh, sora, sund, takr, talu, tamldec, telu, thai, tibt, tirh, vaii, wara, and wcho.

hour12

@@ -960,94 +764,291 @@ Provides the options for the **DateTimeFormat** object. -## NumberOptions +## NumberFormat -Provides the device capability. +### constructor - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + +

Name

-

Parameter Type

-

Readable

-

Writable

-

Description

-

locale

-

string

-

Yes

-

No

-

Locale information.

-

currency

-

string

-

Yes

-

Yes

-

Currency for the specified locale.

-

currencySign

-

string

-

Yes

-

Yes

-

Currency symbol.

-

currencyDisplay

-

string

-

Yes

-

Yes

-

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

-

unit

-

string

-

Yes

-

Yes

-

Currency unit.

-

unitDisplay

-

string

-

Yes

-

Yes

-

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

-

signDisplay

-

string

-

Yes

+constructor\(locale: string, options?: NumberOptions\) + +Creates a **NumberFormat** object for the specified locale. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string

+

Yes

+

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

+

options

+

NumberOptions

+

No

+

Options for creating a NumberFormat object.

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

Name

+

Type

+

Mandatory

+

Description

+

locales

+

Array<string>

+

Yes

+

An array of strings containing locale information.

+

options

+

NumberOptions

+

No

+

Options for creating a NumberFormat object.

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

Name

+

Type

+

Mandatory

+

Description

+

number

+

number

+

Yes

+

Number to be formatted.

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

Type

+

Description

+

string

+

Formatted number.

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

Type

+

Description

+

NumberOptions

+

Options of the NumberFormat object.

+
+ + +- Example + + ``` + var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + numfmt.resolvedOptions(); + ``` + + +## NumberOptions + +Provides the device capability. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @@ -1106,7 +1107,7 @@ Provides the device capability. - - - - - - -

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

locale

+

string

+

Yes

+

No

+

Locale, for example, zh-Hans-CN.

+

currency

+

string

+

Yes

+

Yes

+

Currency unit, for example, EUR, CNY, or USD.

+

currencySign

+

string

+

Yes

+

Yes

+

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

+

currencyDisplay

+

string

+

Yes

+

Yes

+

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

+

unit

+

string

+

Yes

+

Yes

+

Unit name, for example, meter, inch, or hectare.

+

unitDisplay

+

string

+

Yes

+

Yes

+

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

+

unitUsage

+

string

+

Yes

+

Yes

+

Unit use case. The value can be any of the following: default, area-land-agricult, area-land-commercl, area-land-residntl, length-person, length-person-small, length-rainfall, length-road, length-road-small, length-snowfall, length-vehicle, length-visiblty, length-visiblty-small, length-person-informal, length-person-small-informal, length-road-informal, speed-road-travel, speed-wind, temperature-person, temperature-weather, and volume-vehicle-fuel.

+

signDisplay

+

string

+

Yes

Yes

Yes

Numbering system.

+

Numbering system for the locale. The value can be any of the following: adlm, ahom, arab, arabext, bali, beng, bhks, brah, cakm, cham, deva, diak, fullwide, gong, gonm, gujr, guru, hanidec, hmng, hmnp, java, kali, khmr, knda, lana, lanatham, laoo, latn, lepc, limb, mathbold, mathdbl, mathmono, mathsanb, mathsans, mlym, modi, mong, mroo, mtei, mymr, mymrshan, mymrtlng, newa, nkoo, olck, orya, osma, rohg, saur, segment, shrd, sind, sinh, sora, sund, takr, talu, tamldec, telu, thai, tibt, tirh, vaii, wara, and wcho.

useGrouping

@@ -1117,7 +1118,7 @@ Provides the device capability.

Yes

Whether to enable grouping for display.

+

Whether to use grouping for display.

miniumumIntegerDigits

@@ -1128,7 +1129,7 @@ Provides the device capability.

Yes

Minimum number of integer digits.

+

Minimum number of digits allowed in the integer part of a number. The value ranges from 1 to 21.

miniumumFractionDigits

@@ -1139,7 +1140,7 @@ Provides the device capability.

Yes

Minimum number of fraction digits.

+

Minimum number of digits in the fraction part of a number. The value ranges from 0 to 20.

maxiumumFractionDigits

@@ -1150,7 +1151,7 @@ Provides the device capability.

Yes

Maximum number of fraction digits.

+

Maximum number of digits in the fraction part of a number. The value ranges from 1 to 21.

miniumumSignificantDigits

@@ -1161,7 +1162,7 @@ Provides the device capability.

Yes

Minimum number of significant digits.

+

Minimum number of the least significant digits. The value ranges from 1 to 21.

maxiumumSignificantDigits

@@ -1172,9 +1173,824 @@ Provides the device capability.

Yes

Maximum number of significant digits.

+

Maximum number of the least significant digits. The value ranges from 1 to 21.

+## Collator8+ + +### constructor8+ + +constructor\(\) + +Creates a **Collator** object. + +- Example + + ``` + var collator = new Intl.Collator(); + ``` + + +### constructor8+ + +constructor\(locale: string | Array, options?: CollatorOptions\) + +Creates a **Collator** object based on the specified locale and options. + +Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string|Array<string>

+

Yes

+

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

+

options

+

CollatorOptions

+

No

+

Options for creating a Collator object.

+
+ +- Example + + ``` + var collator = new Intl.Collator("zh-CN", {"localeMatcher": "lookup", "usage": "sort"}); + ``` + + +### compare8+ + +compare\(first: string, second: string\): number + +Compares two strings based on the sorting policy of the **Collator**. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

first

+

string

+

Yes

+

First string to compare.

+

second

+

string

+

Yes

+

Second string to compare.

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

Type

+

Description

+

number

+

Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is 0, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.

+
+ + +- Example + + ``` + var collator = new intl.Collator("zh-Hans"); + collator.compare("first", "second"); + ``` + + +### resolvedOptions8+ + +resolvedOptions\(\): CollatorOptions + +Returns properties reflecting the locale and collation options of a **Collator** object. + +- Return values + + + + + + + + + + +

Type

+

Description

+

CollatorOptions

+

Properties of the Collator object.

+
+ + +- Example + + ``` + var collator = new intl.Collator("zh-Hans"); + var options = collator.resolvedOptions(); + ``` + + +## CollatorOptions8+ + +Represents the properties of a **Collator** object. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

localeMatcher

+

string

+

Yes

+

Yes

+

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

+

usage

+

string

+

Yes

+

Yes

+

Whether the comparison is for sorting or for searching. The value can be sort or search.

+

sensitivity

+

string

+

Yes

+

Yes

+

Differences in the strings that lead to non-zero return values. The value can be base, accent, case, or variant.

+

ignorePunctuation

+

boolean

+

Yes

+

Yes

+

Whether punctuation is ignored. The value can be true or false.

+

collation

+

string

+

Yes

+

Yes

+

Sorting policy. The value can be any of the following: big5han, compat, dict, direct, ducet, eor, gb2312, phonebk, phonetic, pinyin, reformed, searchjl, stroke, trad, unihan, and zhuyin.

+

numeric

+

boolean

+

Yes

+

Yes

+

Whether numeric collation is used. The value can be true or false.

+

caseFirst

+

string

+

Yes

+

Yes

+

Whether upper case or lower case is sorted first. The value can be upper, lower, or false.

+
+ +## PluralRules8+ + +### constructor8+ + +constructor\(\) + +Create a **PluralRules** object. + +- Example + + ``` + var pluralRules = new Intl.PluralRules(); + ``` + + +### constructor8+ + +constructor\(locale: string | Array, options?: PluralRulesOptions\) + +Creates a **PluralRules** object based on the specified locale and options. + +Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string|Array<string>

+

Yes

+

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

+

options

+

PluralRulesOptions

+

No

+

Options for creating a PluralRules object.

+
+ +- Example + + ``` + var pluralRules= new Intl.PluraRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); + ``` + + +### select8+ + +select\(n: number\): string + +Obtains a string that represents the singular-plural type of the specified number. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

n

+

number

+

Yes

+

Number for which the singular-plural type is to be obtained.

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

Type

+

Description

+

string

+

Singular-plural type. The options are as follows: zero, one, two, few, many, and others.

+
+ + +- Example + + ``` + var pluralRules = new intl.PluralRules("zh-Hans"); + pluralRules.select(1); + ``` + + +## PluralRulesOptions8+ + +Represents the properties of a **PluralRules** object. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

localeMatcher

+

string

+

Yes

+

Yes

+

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

+

type

+

string

+

Yes

+

Yes

+

Sorting type. The value can be cardinal or ordinal.

+

minimumIntegerDigits

+

number

+

Yes

+

Yes

+

Minimum number of digits allowed in the integer part of a number. The value ranges from 1 to 21.

+

minimumFractionDigits

+

number

+

Yes

+

Yes

+

Minimum number of digits in the fraction part of a number. The value ranges from 0 to 20.

+

maximumFractionDigits

+

number

+

Yes

+

Yes

+

Maximum number of digits in the fraction part of a number. The value ranges from 1 to 21.

+

minimumSignificantDigits

+

number

+

Yes

+

Yes

+

Minimum number of the least significant digits. The value ranges from 1 to 21.

+

maximumSignificantDigits

+

number

+

Yes

+

Yes

+

Maximum number of the least significant digits. The value ranges from 1 to 21.

+
+ +## RelativeTimeFormat8+ + +### constructor8+ + +constructor\(\) + +Creates a **RelativeTimeFormat** object. + +- Example + + ``` + var relativetimefmt = new Intl.RelativeTimeFormat(); + ``` + + +### constructor8+ + +constructor\(locale: string | Array, options?: RelativeTimeFormatInputOptions\) + +Creates a **RelativeTimeFormat** object based on the specified locale and options. + +Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

locale

+

string|Array<string>

+

Yes

+

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

+

options

+

RelativeTimeFormatInputOptions

+

No

+

Options for creating a RelativeTimeFormat object.

+
+ +- Example + + ``` + var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); + ``` + + +### format8+ + +format\(value: numeric, unit: string\): string + +Formats the value and unit based on the specified locale and formatting options. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

numeric

+

Yes

+

Value to format.

+

unit

+

string

+

Yes

+

Unit to format. The value can be year, quarter, month, week, day, hour, minute, or second.

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

Type

+

Description

+

string

+

Relative time after formatting.

+
+ + +- Example + + ``` + var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); + relativetimefmt.format(3, "quarter") + ``` + + +### formatToParts8+ + +formatToParts\(value: numeric, unit: string\): Array + +Returns an array of **RelativeTimeFormat** objects in parts for locale-aware formatting. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

value

+

numeric

+

Yes

+

Value to format.

+

unit

+

string

+

Yes

+

Unit to format. The value can be year, quarter, month, week, day, hour, minute, or second.

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

Type

+

Description

+

Array<Object>

+

An array of RelativeTimeFormat objects in parts.

+
+ + +- Example + + ``` + var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); + var parts = relativetimefmt.format(10, "seconds"); + ``` + + +### resolvedOptions8+ + +resolvedOptions\(\): RelativeTimeFormatResolvedOptions + +Obtains the formatting options for **RelativeTimeFormat** objects. + +- Return values + + + + + + + + + + +

Type

+

Description

+

RelativeTimeFormatResolvedOptions

+

Formatting options for RelativeTimeFormat objects.

+
+ + +- Example + + ``` + var relativetimefmt= new Intl.RelativeTimeFormat("en-GB"); + relativetimefmt.resolvedOptions(); + ``` + + +## RelativeTimeFormatInputOptions8+ + +Represents the properties of a **RelativeTimeFormat** object. + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

localeMatcher

+

string

+

Yes

+

Yes

+

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

+

numeric

+

string

+

Yes

+

Yes

+

Format of the output message. The value can be always or auto.

+

style

+

string

+

Yes

+

Yes

+

Length of the internationalized message. The value can be long, short, or narrow.

+
+ +## RelativeTimeFormatResolvedOptions8+ + +Represents the properties of a **RelativeTimeFormat** object. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Parameter Type

+

Readable

+

Writable

+

Description

+

locale

+

string

+

Yes

+

Yes

+

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

+

numeric

+

string

+

Yes

+

Yes

+

Format of the output message. The value can be always or auto.

+

style

+

string

+

Yes

+

Yes

+

Length of the internationalized message. The value can be long, short, or narrow.

+

numberingSystem

+

string

+

Yes

+

Yes

+

Numbering system.

+
diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index d4430fd798d4ef558605cb65e7463d2e1c646921..dff84877c9592c93bba4f1bfed5e31cd9a957119 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,42 +1,105 @@ -# Audio Playback and Recording +# Media + +The multimedia subsystem provides a set of simple and easy-to-use APIs for you to access the system and use media resources. + +This subsystem offers various media services covering audio and video, which provide the following capabilities: + +- Audio playback ([AudioPlayer](#audioplayer)) +- Audio recording ([AudioRecorder](#audiorecorder)) + +The following capabilities will be provided in the future: video playback, video recording, data source audio/video playback, audio/video encoding and decoding, container encapsulation and decapsulation, and media capability query. ## Modules to Import -``` +```js import media from '@ohos.multimedia.media'; ``` -## Required Permissions - -None +## media.createAudioPlayer -## media.createAudioPlayer +createAudioPlayer(): [AudioPlayer](#audioplayer) -Creates an **AudioPlayer** instance. +Creates an **AudioPlayer** instance in synchronous mode. **Return values** -| Type | Description | +| Type| Description| | --------------------------- | ------------------------------------------------------------ | -| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. | +| [AudioPlayer](#audioplayer) | Returns the **AudioPlayer** instance if the operation is successful; returns **null** otherwise. After the instance is created, you can start, pause, or stop audio playback.| + +**Example** + +```js +var audioPlayer = media.createAudioPlayer(); +``` + +## media.createAudioPlayerAsync8+ + +createAudioPlayerAsync(callback: AsyncCallback\<[AudioPlayer](#audioplayer)>): void + +Creates an **AudioPlayer** instance in asynchronous mode. This method uses a callback to return the result. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ------------------------------------------ | ---- | ------------------------------ | +| callback | AsyncCallback<[AudioPlayer](#audioplayer)> | Yes| Callback used to return the **AudioPlayer** instance created.| **Example** +```js +media.createAudioPlayerAsync((error, audio) => { + if (typeof(audio) != 'undefined') { + audioPlayer = audio; + console.info('audio createAudioPlayerAsync success'); + } else { + console.info(`audio createAudioPlayerAsync fail, error:${error.message}`); + } +}); ``` -var audioplayer = media.createAudioPlayer(); + +## media.createAudioPlayerAsync8+ + +createAudioPlayerAsync: Promise<[AudioPlayer](#audioplayer)> + +Creates an **AudioPlayer** instance in asynchronous mode. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ------------------------------------ | ----------------------------------- | +| Promise<[AudioPlayer](#audioplayer)> | Promise used to return the **AudioPlayer** instance created.| + +**Example** + +```js +function failureCallback(error) { + console.info(`audio failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`audio catchCallback, error:${error.message}`); +} + +await media.createAudioPlayerAsync.then((audio) => { + if (typeof(audio) != 'undefined') { + audioPlayer = audio; + console.info('audio createAudioPlayerAsync success'); + } else { + console.info('audio createAudioPlayerAsync fail'); + } +}, failureCallback).catch(catchCallback); ``` ## media.createAudioRecorder - createAudioRecorder(): AudioRecorder -Creates an **AudioRecorder** instance to control audio recording. +Creates an **AudioRecorder** instance to control audio recording. **Return values** -| Type | Description | -| ------------------------------- | ------------------------------------------------------------ | -| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. | +| Type| Description| +| ------------------------------- | ----------------------------------------- | +| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise.| **Example** @@ -44,255 +107,486 @@ Creates an **AudioRecorder** instance to control audio recording. var audiorecorder = media.createAudioRecorder(); ``` +## MediaErrorCode8+ + +Enumerates the media error codes. + +| Name| Value| Description| +| -------------------------- | ---- | -------------------------------------- | +| MSERR_OK | 0 | The operation is successful.| +| MSERR_NO_MEMORY | 1 | Failed to allocate memory. The system may have no available memory.| +| MSERR_OPERATION_NOT_PERMIT | 2 | No permission to perform this operation.| +| MSERR_INVALID_VAL | 3 | Invalid input parameter.| +| MSERR_IO | 4 | An I/O error occurs.| +| MSERR_TIMEOUT | 5 | The operation times out.| +| MSERR_UNKNOWN | 6 | An unknown error occurs.| +| MSERR_SERVICE_DIED | 7 | Invalid server.| +| MSERR_INVALID_STATE | 8 | The operation is not allowed in the current state.| +| MSERR_UNSUPPORTED | 9 | The operation is not supported in the current version.| + +## MediaType8+ + +Enumerates the media types. + +| Name| Value| Description| +| ------------------- | ---- | ------------------ | +| MEDIA_TYPE_AUD | 0 | Media.| +| MEDIA_TYPE_VID | 1 | Video.| +| MEDIA_TYPE_SUBTITLE | 2 | Subtitle. (under development)| + +## CodecMimeType8+ + +Enumerates the codec MIME types. + +| Name| Value| Description| +| ------------ | ----------------- | ------------------------ | +| AUDIO_MPEG | "audio/mpeg" | Audio in MPEG format.| +| AUDIO_AAC | "audio/mp4a-latm" | Audio in MP4A-LATM format.| +| AUDIO_VORBIS | "audio/vorbis" | Audio in Vorbis format.| +| AUDIO_FLAC | "audio/flac" | Audio in FLAC format.| + +## MediaDescriptionKey8+ + +Enumerates the media description keys. + +| Name| Value| Description| +| ------------------------ | --------------- | ------------------------------------------------------------ | +| MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number.| +| MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).| +| MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string.| +| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms.| +| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s.| +| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel.| +| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel.| +| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.| +| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number.| +| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz.| + +## BufferingInfoType8+ + +Enumerates the buffering event types. + +| Name| Value| Description| +| ----------------- | ---- | -------------------------- | +| BUFFERING_START | 1 | Buffering starts.| +| BUFFERING_END | 2 | Buffering ends.| +| BUFFERING_PERCENT | 3 | Buffering progress, in percent.| +| CACHED_DURATION | 4 | Cache duration, in milliseconds.| + ## AudioPlayer -Manages and plays audio. Before calling a method of **AudioPlayer**, you must use [createAudioPlayer()](#mediacreateaudioplayer) to create an **AudioPlayer** instance. +Manages and plays audio. Before calling a method of the **AudioPlayer** class, you must call [createAudioPlayer()](#media.createaudioplayer) or [createAudioPlayerAsync()](#media.createaudioplayerasync8) to create an [AudioPlayer](#audioplayer) instance. + +For details about the audio playback demo, see [Audio Playback Development](.../media/audio-playback.md). -### Attributes +### Attributes -| Name | Type | Readable | Writable | Description | -| ----------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | -| src | string | Yes | Yes | Audio media URI. Popular audio formats (mp4, aac, mp3, and ogg) are supported. The value can be a local absolute path starting with **file://**. | -| loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop playback. | -| currentTime | number | Yes | No | Current playback position. | -| duration | number | Yes | No | Audio duration. | -| state | [AudioState](#audiostate) | Yes | No | Playback status. | +| Name| Type| Readable| Writable| Description| +| ----------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | +| src | string | Yes| Yes| Audio media URI. The mainstream audio formats (MP4, AAC, MP3, and OGG) are supported.
**Examples of supported URIs**:
1. Local absolute path: file:///data/data/ohos.xxx.xxx/files/test.mp4
![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. HTTP network playback path (under development)
3. HLS network playback path (under development)
4. FD playback (under development)
**Precautions**:
Media files can be played only after the read permission is granted.| +| loop | boolean | Yes| Yes| Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite.| +| currentTime | number | Yes| No| Current audio playback position.| +| duration | number | Yes| No| Audio duration.| +| state | [AudioState](#audiostate) | Yes| No| Audio playback state.| -### play +### play -play\(\): void +play(): void -Starts audio playback. +Starts to play audio resources. This method can be called only after the **dataLoad** event is triggered. **Example** -``` -audioplayer.src = 'file:///data/media/sounds.mp4'; -audioplayer.on('play', () => { - console.log('Playback starts.'); +```js +audioPlayer.on('play', () => { // Set the 'play' event callback. + console.log('audio play success'); }); -audioplayer.play(); +audioPlayer.play(); ``` -### pause +### pause -pause\(\): void +pause(): void Pauses audio playback. **Example** -``` -audioplayer.src = 'file:///data/media/sounds.mp4'; -audioplayer.on('pause', () => { - console.log('Playback paused.'); +```js +audioPlayer.on('pause', () => { // Set the 'pause' event callback. + console.log('audio pause success'); }); -audioplayer.pause(); +audioPlayer.pause(); ``` +### stop -### stop - -stop\(\): void +stop(): void Stops audio playback. **Example** -``` -audioplayer.src = 'file:///data/media/sounds.mp4'; -audioplayer.on('stop',() => { - console.log('Playback stopped.'); +```js +audioPlayer.on('stop', () => { // Set the 'stop' event callback. + console.log('audio stop success'); }); -audioplayer.stop(); +audioPlayer.stop(); ``` +### reset7+ + +reset(): void -### seek +Switches the audio resource to be played. -seek\(timeMs: number\): void +**Example** + +```js +audioPlayer.on('reset', () => { // Set the 'reset' event callback. + console.log('audio reset success'); +}); +audioPlayer.reset(); +``` + +### seek + +seek(timeMs: number): void Seeks to the specified playback position. **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | ----------------------------- | -| timeMs | number | Yes | Playback position to seek to. | +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ------------------------------ | +| timeMs | number | Yes| Position to seek to, in milliseconds.| **Example** -``` -audioplayer.src = 'file:///data/media/sounds.mp4'; -audioplayer.on('timeupdate', (action) => { - var newTime = audioplayer.currenTime; - if(newTime >= 30000) { - console.info('Seek succeeded. New time: ' + newTime); - } else { - console.info('Seek failed.'); - } +```js +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. + if (typeof (seekDoneTime) == 'undefined') { + console.info('audio seek fail'); + return; + } + console.log('audio seek success. seekDoneTime: ' + seekDoneTime); }); -audioplayer.seek(30000); +audioPlayer.seek(30000); // Seek to 30000 ms. ``` -### setVolume +### setVolume -setVolume\(vol: number\): void +setVolume(vol: number): void Sets the volume. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | --------- | ------------------------------------------------------------ | -| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%). | +| Name| Type| Mandatory| Description| +| ------ | ------ | ---- | ------------------------------------------------------------ | +| vol | number | Yes| Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| **Example** -``` -audioplayer.src = 'file:///data/media/sounds.mp4'; -audioplayer.on('volumeChange', () => { - console.log('Playback volume changed.'); +```js +audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + console.log('audio volumeChange success'); }); -audioplayer.setVolume(1); +audioPlayer.setVolume(1); // Set the volume to 100%. ``` -### reset7+ +### release -reset\(\): void +release(): void -Switches the audio resource to be played. +Releases this **AudioPlayer** instance. **Example** -``` -audioplay.reset(); +```js +audioPlayer.release(); +audioPlayer = undefined; ``` -### release +### getTrackDescription8+ + +getTrackDescription(callback: AsyncCallback>): void -release\(\): void +Obtains the audio track information. This method uses a callback to return the result. -Releases audio resources. +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ------------------------------------------------------------ | ---- | -------------------------- | +| callback | AsyncCallback> | Yes| Callback used to return the audio track information obtained.| **Example** +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} + +audioPlayer.getTrackDescription((error, arrlist) => { + if (typeof (arrlist) != 'undefined') { + for (let i = 0; i < arrlist.length; i++) { + printfDescription(arrlist[i]); + } + } else { + console.log(`audio getTrackDescription fail, error:${error.message}`); + } +}); ``` -audioplay.release(); + +### getTrackDescription8+ + +getTrackDescription(): Promise> + +Obtains the audio track information. This method uses a promise to return the result. + +**Return values** + +| Type| Description| +| ------------------------------------------------------ | ------------------------------- | +| Promise> | Promise used to return the audio track information obtained.| + +**Example** + +```js +function printfDescription(obj) { + for (let item in obj) { + let property = obj[item]; + console.info('audio key is ' + item); + console.info('audio value is ' + property); + } +} +function failureCallback(error) { + console.info(`audio failureCallback, error:${error.message}`); +} +function catchCallback(error) { + console.info(`audio catchCallback, error:${error.message}`); +} + +await audioPlayer.getTrackDescription.then((arrlist) => { + if (typeof (arrlist) != 'undefined') { + arrayDescription = arrlist; + } else { + console.log('audio getTrackDescription fail'); + } +}, failureCallback).catch(catchCallback); +for (let i = 0; i < arrayDescription.length; i++) { + printfDescription(arrayDescription[i]); +} ``` -### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') +### on('bufferingUpdate')8+ -Listens for audio playback events. +on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void -on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void) +Subscribes to the audio buffering update event. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Type of the playback event to listen for. The following events are supported: **play**, **pause**, **stop**, **reset**, **dataLoad**, **finish**, and **volumeChange**.
- The **play** event is triggered when audio playback starts.
- The **pause** event is triggered when audio playback is paused.
- The **stop** event is triggered when audio playback stops.
- The **reset** event is triggered when the player is reset.
- The **dataLoad** event is triggered when audio data is loaded.
- The **finish** event is triggered when audio playback is finished.
- The **volumeChange** event is triggered when the playback volume changes. | -| callback | function | Yes | Callback used to listen for the playback event. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to, which is 'bufferingUpdate' in this example.| +| callback | (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void | Yes| Callback invoked when the event is triggered.
When [BufferingInfoType](#bufferinginfotype8) is set to **BUFFERING_PERCENT** or **CACHED_DURATION**, **value** is valid. Otherwise, **value** is fixed at **0**.| **Example** +```js +audioPlayer.on('bufferingUpdate', (infoType, value) => { + console.log('audio bufferingInfo type: ' + infoType); + console.log('audio bufferingInfo value: ' + value); +}); ``` -audioplayer.src = 'file://xxx/sounds.mp4'; -audioplayer.on('play', () => { - console.log('Playback starts.'); + + ### on('play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange') + +on(type: 'play' | 'pause' | 'stop' | 'reset' | 'dataLoad' | 'finish' | 'volumeChange', callback: () => void): void + +Subscribes to the audio playback events. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ---------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to. The following events are supported: 'play' \| 'pause' \| 'stop' \| 'reset' \| 'dataLoad' \| 'finish' \| 'volumeChange'
- The 'play' event is triggered when the [play()](#audioplayer_play) method is called and audio playback starts.
- The 'pause' event is triggered when the [pause()](#audioplayer_pause) method is called and audio playback is paused.
- The 'stop' event is triggered when the [stop()](#audioplayer_stop) method is called and audio playback stops.
- The 'reset' event is triggered when the [reset()](#audioplayer_reset) method is called and audio playback is reset.
- The 'dataLoad' event is triggered when the audio data is loaded, that is, when the **src** attribute is configured.
- The 'finish' event is triggered when the audio playback is finished.
- The 'volumeChange' event is triggered when the [setVolume()](#audioplayer_setvolume) method is called and the playback volume is changed.| +| callback | () => void | Yes| Callback invoked when the event is triggered.| + +**Example** + +```js +let audioPlayer = media.createAudioPlayer(); // Create an AudioPlayer instance. +audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully. + console.info('audio set source success'); + audioPlayer.play(); // Start the playback and trigger the 'play' event callback. +}); +audioPlayer.on('play', () => { // Set the 'play' event callback. + console.info('audio play success'); + audioPlayer.seek(30000); // Call the seek() method and trigger the 'timeUpdate' event callback. }); -audioplayer.play(); +audioPlayer.on('pause', () => { // Set the 'pause' event callback. + console.info('audio pause success'); + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. +}); +audioPlayer.on('reset', () => { // Set the 'reset' event callback. + console.info('audio reset success'); + audioPlayer.release(); // Release the AudioPlayer instance. + audioPlayer = undefined; +}); +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. + if (typeof(seekDoneTime) == "undefined") { + console.info('audio seek fail'); + return; + } + console.info('audio seek success, and seek time is ' + seekDoneTime); + audioPlayer.setVolume(0.5); // Set the volume to 50% and trigger the 'volumeChange' event callback. +}); +audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback. + console.info('audio volumeChange success'); + audioPlayer.pause(); // Pause the playback and trigger the 'pause' event callback. +}); +audioPlayer.on('finish', () => { // Set the 'finish' event callback. + console.info('audio play finish'); + audioPlayer.stop(); // Stop the playback and trigger the 'stop' event callback. +}); +audioPlayer.on('error', (error) => { // Set the 'error' event callback. + console.info(`audio error called, errName is ${error.name}`); + console.info(`audio error called, errCode is ${error.code}`); + console.info(`audio error called, errMessage is ${error.message}`); +}); +audioPlayer.src = 'file:///data/data/ohos.xxx.xxx/files/test.mp4'; // Set the src attribute and trigger the 'dataLoad' event callback. ``` ### on('timeUpdate') on(type: 'timeUpdate', callback: Callback\): void -Listens for audio playback timestamp update events. +Subscribes to the 'timeUpdate' event. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Type of the playback event to listen for. Only the **timeUpdate** event is supported.
- The **timeUpdate** event is triggered when the audio playback timestamp is updated. It is also triggered when the **seek** method is called. | -| callback | Callback<number> | Yes | Callback used to listen for the playback event. | +| Name| Type| Mandatory| Description| +| -------- | ----------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to, which is 'timeUpdate' in this method.
The 'timeUpdate' event is triggered when the [seek()](#audioplayer_seek) method is called.| +| callback | Callback\ | Yes| Callback invoked when the event is triggered. The input parameter of the callback is the time when the seek operation is successful.| **Example** -``` -audioplayer.src = 'file://xxx/sounds.mp4'; -audioplayer.on('timeupdate', (newTime ) => { - if(newTime >= 30000) { - console.info('Seek succeeded. New time: ' + newTime); - } else { - console.info('Seek failed.'); - } +```js +audioPlayer.on('timeUpdate', (seekDoneTime) => { // Set the 'timeUpdate' event callback. + if (typeof (seekDoneTime) == 'undefined') { + console.info('audio seek fail'); + return; + } + console.log('audio seek success. seekDoneTime: ' + seekDoneTime); }); -audioplayer.seek(30000); +audioPlayer.seek(30000); // Seek to 30000 ms. ``` ### on('error') on(type: 'error', callback: ErrorCallback): void -Listens for playback error events. +Subscribes to the audio playback error event. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Type of the playback error event to listen for.
- The **error** event is triggered when an error occurs during audio playback. | -| callback | ErrorCallback | Yes | Callback used to listen for the playback event. | +| Name| Type| Mandatory| Description| +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio playback.| +| callback | ErrorCallback | Yes| Callback invoked when the event is triggered.| **Example** -``` -audioplayer.src = 'file:///data/sounds.mp4'; -audioplayer.on('error', (err) => { - console.info('error callback info: ' + err); +```js +audioPlayer.on('error', (error) => { // Set the error event callback. + console.info(`audio error called, errName is ${error.name}`); // Print the error name. + console.info(`audio error called, errCode is ${error.code}`); // Print the error code. + console.info(`audio error called, errMessage is ${error.message}`);// Print the detailed description of the error type. }); -audioplayer.setVolume(30000); +audioPlayer.setVolume(3); // Set volume to an invalid value to trigger the 'error' event. ``` - ## AudioState -Describes the audio playback state. +Describes the audio playback state. You can obtain the state through the **state** attribute. + +| Name| Type| Description| +| ------------------ | ------ | -------------- | +| idle | string | Audio playback is idle.| +| playing | string | Audio playback is in progress.| +| paused | string | Audio playback is paused.| +| stopped | string | Audio playback is stopped.| +| error8+ | string | Audio playback is in the error state.| -| Name | Description | -| ------- | -------------------------- | -| idle | Audio playback is idle. | -| playing | The audio is being played. | -| paused | Audio playback is paused. | -| stopped | Audio playback is stopped. | +## MediaDescription8+ + +### [key : string] : any + +Defines media information in key-value mode. + +| Name| Type| Description| +| ----- | ------ | ------------------------------------------------------------ | +| key | string | Key of the media information. For details about the keys, see [MediaDescriptionKey](#mediadescriptionkey8).| +| value | any | Value of the key. For details about the values, see [MediaDescriptionKey](#mediadescriptionkey8).| + +**Example** + +```js +function printfItemDescription(obj, key) { + let property = obj[key]; + console.info('audio key is ' + key); + console.info('audio value is ' + property); +} + +audioPlayer.getTrackDescription((error, arrlist) => { + if (typeof (arrlist) != 'undefined') { + for (let i = 0; i < arrlist.length; i++) { + printfItemDescription(arrlist[i], MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. + } + } else { + console.log(`audio getTrackDescription fail, error:${error.message}`); + } +}); +``` ## AudioRecorder -Provides methods to record audio. Before calling an **AudioRecorder** method, you must use [createAudioRecorder\(\)](#mediacreateaudiorecorder) to create an **AudioRecorder** instance. +Implements audio recording. Before calling a method of the **AudioRecorder** class, you must call [createAudioRecorder()](#createaudiorecorder-audiorecorder) to create an **AudioRecorder** instance. ### prepare prepare(config: AudioRecorderConfig): void +Prepares for recording. + **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------------------------------------------- | --------- | ------------------------------------------------------------ | -| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes | Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels | +| Name| Type| Mandatory| Description| +| ------ | ------------------------------------------- | ---- | ------------------------------------------------------------ | +| config | [AudioRecorderConfig](#audiorecorderconfig) | Yes| Recording parameters, including the audio output URI, encoding format, sampling rate, and number of audio channels.| **Example** - ``` - let audioRecorderConfig = { - audioEncoder : AAC_LC , - audioEncodeBitRate : 22050, - audioSampleRate : 22050, - numberOfChannels : 2, - format : AAC_ADTS, - uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', - } - audiorecorder.prepare(audioRecorderConfig) - ``` +``` +let audioRecorderConfig = { + audioEncoder : AAC_LC , + audioEncodeBitRate : 22050, + audioSampleRate : 22050, + numberOfChannels : 2, + format : AAC_ADTS, + uri : 'file:///data/accounts/account_0/appdata/appdata/recorder/test.m4a', +} +audiorecorder.prepare(audioRecorderConfig) +``` + + ### start start(): void @@ -321,6 +615,8 @@ audiorecorder.stop(); release(): void +Releases this **AudioRecorder** instance. + **Example** ``` @@ -333,7 +629,7 @@ reset(): void Resets audio recording. -Before resetting audio recording, you must call **stop\(\)** to stop recording. After audio recording is reset, you must call **prepare\(\)** to set the recording configurations for another recording. +Before resetting audio recording, you must call **stop()** to stop recording. After audio recording is reset, you must call **prepare()** to set the recording configurations for another recording. **Example** @@ -345,14 +641,14 @@ audiorecorder.reset(); on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => void): void -Listens for audio recording events. +Subscribes to the audio recording events. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Type of the audio recording event to listen for. The following events are supported: **prepare**, **start**, **stop**, **release**, and **reset**.
- The **prepare** event is triggered when the audio recording preparation is complete.
- The **start** event is triggered when audio recording starts.
- The **stop** event is triggered when audio recording stops.
- The **release** event is triggered when resources related to audio recording are released.
- The **reset** event is triggered when audio recording is reset. | -| callback | function | Yes | Callback used to listen for the audio recording event. | +| Name| Type| Mandatory| Description| +| -------- | -------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to. The following events are supported: 'prepare'\|'start'\|'stop'\|'release'\|'reset'
- The 'prepare' event is triggered when audio recording preparation is complete.
- The 'start' event is triggered when audio recording starts.
- The 'stop' event is triggered when audio recording is stopped.
- The 'release' event is triggered when the resources related to audio recording are released.
- The 'reset' event is triggered when audio recording is reset.| +| callback | function | Yes| Callback invoked when the event is triggered.| **Example** @@ -367,41 +663,44 @@ audiorecorder.on('prepare', () => { on(type: 'error', callback: ErrorCallback): void -Listens for audio recording error events. +Subscribes to the audio recording error event. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Type of the audio recording error event to listen for.
- The **error** event is triggered when an error occurs during audio recording. | -| callback | function | Yes | Callback used to listen for the audio recording event. | +| Name| Type| Mandatory| Description| +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes| Type of the event to subscribe to, which is 'error' in this method.
The 'error' event is triggered when an error occurs during audio recording.| +| callback | ErrorCallback | Yes| Callback invoked when the event is triggered.| + ## AudioRecorderConfig Describes audio recording configurations. -| Name | Type | Mandatory | Description | -| ------------------ | --------------------------------------- | --------- | ------------------------------------------------------------ | -| audioEncoder | [AudioEncoder](#audioencoder) | No | Audio encoding format. The default value is **AAC_LC**. | -| audioEncodeBitRate | number | No | Bit rate for audio encoding. The default value is **48000**. | -| audioSampleRate | number | No | Audio sampling rate. The default value is **48000**. | -| numberOfChannels | number | No | Number of audio channels. The default value is **2**. | -| format | [AudioOutputFormat](#audiooutputformat) | No | Audio output format. The default value is **MPEG_4**. | -| uri | string | Yes | Audio output URI. The following types of URIs are supported:
1. Absolute path:
file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. Path with the file descriptor (FD): file://1 (FD number) | +| Name| Type| Mandatory| Description| +| ------------------ | --------------------------------------- | ---- | ------------------------------------------------------------ | +| audioEncoder | [AudioEncoder](#audioencoder) | No| Audio encoding format. The default value is **AAC_LC**.| +| audioEncodeBitRate | number | No| Audio encoding bit rate. The default value is **48000**.| +| audioSampleRate | number | No| Audio sampling rate. The default value is **48000**.| +| numberOfChannels | number | No| Number of audio channels. The default value is **2**.| +| format | [AudioOutputFormat](#audiooutputformat) | No| Audio output format. The default value is **MPEG_4**.| +| uri | string | Yes| Audio output URI. The following URI types are supported:
1. Absolute file path: file:///data/data/ohos.xxx.xxx/cache/test.mp4![en-us_image_0000001164217678](figures/en-us_image_0000001164217678.png)
2. FD path: file://1 (fd number)| + ## AudioEncoder -Enumerates audio encoding formats. +Enumerates the audio encoding formats. + +| Name| Default Value| Description| +| ------ | ------ | ------------------------------------------------------------ | +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| -| Name | Default Value | Description | -| ------ | ------------- | ---------------------------------------------- | -| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC). | ## AudioOutputFormat -Enumerates audio output formats. +Enumerates the audio output formats. -| Name | Default Value | Description | -| -------- | ------------- | ------------------------------------------------------------ | -| MPEG_4 | 2 | MPEG-4. | -| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), a transmission stream format of Advanced Audio Coding (AAC) audio. | \ No newline at end of file +| Name| Default Value| Description| +| -------- | ------ | ------------------------------------------------------------ | +| MPEG_4 | 2 | MPEG-4.| +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index 1e4bbafcd5e8928ab009a869bddfbb2debb8f1c4..1105fa9acb63775bd860a5cb611b65ebec77a255 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,88 +1,5 @@ # Notification Module -## Applicable Devices - -| API | Phone | Tablet | Smart TV | Wearable | -| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -| Notification.publish(request: NotificationRequest, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.publish(request: NotificationRequest) | Yes | Yes | Yes | Yes | -| Notification.cancel(id: number, label: string, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.cancel(id:number, label?:string) | Yes | Yes | Yes | Yes | -| Notification.cancel(id: number, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.cancelAll(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.cancelAll() | Yes | Yes | Yes | Yes | -| Notification.addSlot(slot: NotificationSlot, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.addSlot(slot: NotificationSlot) | Yes | Yes | Yes | Yes | -| Notification.addSlot(type: SlotType, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.addSlot(type: SlotType) | Yes | Yes | Yes | Yes | -| Notification.addSlots(slots: Array\, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.addSlots(slots: Array\) | Yes | Yes | Yes | Yes | -| Notification.getSlot(slotType: SlotType, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.getSlot(slotType: SlotType) | Yes | Yes | Yes | Yes | -| Notification.getSlots(callback: AsyncCallback>) | Yes | Yes | Yes | Yes | -| Notification.getSlots() | Yes | Yes | Yes | Yes | -| Notification.removeSlot(slotType: SlotType, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.removeSlot(slotType: SlotType) | Yes | Yes | Yes | Yes | -| Notification.removeAllSlots(callback: AsyncCallback\): void | Yes | Yes | Yes | Yes | -| Notification.removeAllSlots(): Promise\ | Yes | Yes | Yes | Yes | -| Notification.subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo) | Yes | Yes | Yes | Yes | -| Notification.unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.unsubscribe(subscriber: NotificationSubscriber) | Yes | Yes | Yes | Yes | -| Notification.enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.enableNotification(bundle: BundleOption, enable: boolean) | Yes | Yes | Yes | Yes | -| Notification.isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.isNotificationEnabled(bundle: BundleOption) | Yes | Yes | Yes | Yes | -| Notification.isNotificationEnabled(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.isNotificationEnabled() | Yes | Yes | Yes | Yes | -| Notification.displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.displayBadge(bundle: BundleOption, enable: boolean) | Yes | Yes | Yes | Yes | -| Notification.isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.isBadgeDisplayed(bundle: BundleOption) | Yes | Yes | Yes | Yes | -| Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.setSlotByBundle(bundle: BundleOption, slot: NotificationSlot) | Yes | Yes | Yes | Yes | -| Notification.getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>) | Yes | Yes | Yes | Yes | -| Notification.getSlotsByBundle(bundle: BundleOption) | Yes | Yes | Yes | Yes | -| Notification.getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.getSlotNumByBundle(bundle: BundleOption) | Yes | Yes | Yes | Yes | -| Notification.remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.remove(bundle: BundleOption, notificationKey: NotificationKey) | Yes | Yes | Yes | Yes | -| Notification.remove(hashCode: string, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.remove(hashCode: string) | Yes | Yes | Yes | Yes | -| Notification.removeAll(bundle: BundleOption, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.removeAll(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.removeAll(bundle?: BundleOption) | Yes | Yes | Yes | Yes | -| Notification.getAllActiveNotifications(callback: AsyncCallback>) | Yes | Yes | Yes | Yes | -| Notification.getAllActiveNotifications() | Yes | Yes | Yes | Yes | -| Notification.getActiveNotificationCount(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.getActiveNotificationCount() | Yes | Yes | Yes | Yes | -| Notification.getActiveNotifications(callback: AsyncCallback>) | Yes | Yes | Yes | Yes | -| Notification.getActiveNotifications() | Yes | Yes | Yes | Yes | -| Notification.cancelGroup(groupName: string, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.cancelGroup(groupName: string) | Yes | Yes | Yes | Yes | -| Notification.removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.removeGroupByBundle(bundle: BundleOption, groupName: string) | Yes | Yes | Yes | Yes | -| Notification.setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.setDoNotDisturbDate(date: DoNotDisturbDate) | Yes | Yes | Yes | Yes | -| Notification.getDoNotDisturbDate(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.getDoNotDisturbDate() | Yes | Yes | Yes | Yes | -| Notification.supportDoNotDisturbMode(callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| Notification.supportDoNotDisturbMode() | Yes | Yes | Yes | Yes | -| WantAgent.getWantAgent(info: WantAgentInfo, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| WantAgent.getWantAgent(info: WantAgentInfo): Promise\ | Yes | Yes | Yes | Yes | -| WantAgent.getBundleName(agent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| WantAgent.getBundleName(agent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | -| WantAgent.getUid(agent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| WantAgent.getUid(agent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | -| WantAgent.getWant(agent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| WantAgent.getWant(agent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | -| WantAgent.cancel(agent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| WantAgent.cancel(agent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | -| WantAgent.trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback\) | Yes | Yes | Yes | Yes | -| WantAgent.equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\) | Yes | Yes | Yes | Yes | -| WantAgent.equal(agent: WantAgent, otherAgent: WantAgent): Promise\ | Yes | Yes | Yes | Yes | - ## Required Permissions diff --git a/en/application-dev/reference/apis/js-apis-particleAbility.md b/en/application-dev/reference/apis/js-apis-particleAbility.md index 128d8282ba250fc4e887bd178e90308ee015b114..9d4a14ccbeaf81d49fc1de51156613cde3812bda 100644 --- a/en/application-dev/reference/apis/js-apis-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-particleAbility.md @@ -1,18 +1,5 @@ # ParticleAbility Module -## Applicable Devices - -| API | Phone| Tablet| Smart TV| Wearable| Lite Wearable| SmartVision Device| -| ------------------------------------------------------------ | ---- | ---- | ------ | -------- | -------------- | ------------ | -| particleAbility.startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\: void | Yes| Yes| Yes| Yes| No| No| -| particleAbility.startAbility(parameter: StartAbilityParameter): Promise\ | Yes| Yes| Yes| Yes| No| No| -| particleAbility.terminateSelf(callback: AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| -| particleAbility.terminateSelf(): Promise\ | Yes| Yes| Yes| Yes| No| No| -| particleAbility.acquireDataAbilityHelper(uri: string): DataAbilityHelper | Yes| Yes| Yes| Yes| No| No| -| particleAbility.connectAbility(request: Want, options:ConnectOptions): number | Yes| Yes| Yes| Yes| No| No| -| particleAbility.disconnectAbility(connection: number, callback:AsyncCallback\): void | Yes| Yes| Yes| Yes| No| No| -| particleAbility.disconnectAbility(connection: number): Promise\ | Yes| Yes| Yes| Yes| No| No| - ## Constraints The ParticleAbility module is used to perform operations on abilities of the Data and Service types. diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index 34fc52c05097d07cd12caffa8f2952492cfc95b7..40c0baf56efe5173e0f1c679f21b1ec1e825821d 100644 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -1,4 +1,4 @@ -# Obtaining Process Information +# Obtaining Process Information >![](../../public_sys-resources/icon-note.gif) **NOTE:** >The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -80,7 +80,7 @@ None

No

An array with supplementary group IDs.

+

Array with supplementary group IDs.

pid

@@ -105,12 +105,23 @@ None

Parent process ID (PPID) of a process.

tid8+

+

number

+

Yes

+

No

+

Thread ID (TID) of a process.

+
## ChildProcess -Allows a process to obtain the standard input and output of its child processes, send signals, and close its child processes. +Provides methods for a process to obtain the standard input and output of its child processes, send signals, and close its child processes. ### Attributes @@ -200,7 +211,6 @@ Waits until the child process ends. This method uses a promise to return the exi - Example ``` - import process from '@ohos.process'; var child = process.runCmd('ls'); var result = child.wait(); result.then(val=>{ @@ -235,7 +245,6 @@ Obtains the standard output of the child process. - Example ``` - import process from '@ohos.process'; var child = process.runCmd('ls'); var result = child.wait(); child.getOutput.then(val=>{ @@ -270,7 +279,6 @@ Obtains the standard error output of the child process. - Example ``` - import process from '@ohos.process'; var child = process.runCmd('madir test.text'); var result = child.wait(); child.getErrorOutput.then(val=>{ @@ -288,7 +296,6 @@ Closes the child process in running. - Example ``` - import process from '@ohos.process'; var child = process.runCmd('sleep 5; ls'); child.close(); ``` @@ -328,12 +335,413 @@ Sends a signal to the specified child process to terminate it. - Example ``` - import process from '@ohos.process'; var child = process.runCmd('sleep 5; ls'); child.kill(9); ``` +## process.isIsolatedProcess8+ + +isIsolatedProcess\(\): boolean + +Checks whether the process is isolated. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the process is isolated; returns false otherwise.

+
+ + +- Example + + ``` + var result = process.isIsolatedProcess(); + ``` + + +## process.isAppUid8+ + +isAppUid\(v:number\): boolean + +Checks whether a UID belongs to this app. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

v

+

number

+

Yes

+

UID.

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

Type

+

Description

+

boolean

+

Returns true if the UID is the app's UID; returns false otherwise.

+
+ + +- Example + + ``` + var result = process.isAppUid(688); + ``` + + +## process.is64Bit8+ + +is64Bit\(\): boolean + +Checks whether the operating environment is of 64-bit. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the operating environment is of 64-bit; returns false otherwise.

+
+ +- Example + + ``` + var ressult = process.is64Bit(); + ``` + + +## process.getUidForName8+ + +getUidForName\(v:string\): number + +Obtains the process UID based on the process name. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

v

+

string

+

Yes

+

Process name.

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

Type

+

Description

+

number

+

Process UID.

+
+ +- Example + + ``` + var pres = process.getUidForName("tool") + ``` + + +## process.getThreadPriority8+ + +getThreadPriority\(v:number\): number + +Obtains the thread priority based on the specified TID. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

v

+

number

+

Yes

+

TID.

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

Type

+

Description

+

number

+

Priority of the thread.

+
+ +- Example + + ``` + var tid = process.tid; + var pres = process.getThreadPriority(tid); + ``` + + +## process.getStartRealtime8+ + +getStartRealtime\(\) :number + +Obtains the duration, in milliseconds, from the time the system starts to the time the process starts. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Time duration obtained.

+
+ + +- Example + + ``` + var realtime = process.getStartRealtime(); + ``` + + + +## process.getPastCputime8+ + +getPastCputime\(\) :number + +Obtains the CPU time \(in milliseconds\) from the time the process starts to the current time. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

CPU time obtained.

+
+ + +- Example + + ``` + var result = process.getPastCputime() ; + ``` + + +## process.getSystemConfig8+ + +getSystemConfig\(name:number\): number + +Obtains the system configuration. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

number

+

Yes

+

System configuration parameter name.

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

Type

+

Description

+

number

+

System configuration obtained.

+
+ +- Example + + ``` + var _SC_ARG_MAX = 0 + var pres = process.getSystemConfig(_SC_ARG_MAX) + ``` + + +## process.getEnvironmentVar8+ + +getEnvironmentVar\(name:string\): string + +Obtains the value of an environment variable. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Environment variable name.

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

Type

+

Description

+

string

+

Value of the environment variable.

+
+ +- Example + + ``` + var pres = process.getEnvironmentVar("PATH") + ``` + + ## process.runCmd runCmd\(command: string, options?: \{ timeout : number, killSignal : number | string, maxBuffer : number \}\) : ChildProcess @@ -437,12 +845,11 @@ Forks a new process to run a shell command and returns the **ChildProcess** ob - Example ``` - import process from '@ohos.process'; var child = process.runCmd('ls', { maxBuffer : 2 }); var result = child.wait(); child.getOutput.then(val=>{ console.log("child.getOutput = " + val); - } + }) ``` @@ -455,7 +862,6 @@ Aborts a process and generates a core file. This method will cause a process to - Example ``` - import process from '@ohos.process'; process.abort(); ``` @@ -520,7 +926,6 @@ Stores the events triggered by the user. - Example ``` - import process from '@ohos.process'; process.on("data", (e)=>{ console.log("data callback"); }) @@ -569,7 +974,7 @@ Deletes the event stored by the user.

boolean

-

Whether the event is deleted.

+

Returns true if the event is deleted; returns false otherwise.

@@ -578,7 +983,6 @@ Deletes the event stored by the user. - Example ``` - import process from '@ohos.process'; process.on("data", (e)=>{ console.log("data callback"); }) @@ -590,7 +994,7 @@ Deletes the event stored by the user. exit\(code: number\): void -Terminates a process. +Terminates this process. - Parameters @@ -620,7 +1024,6 @@ Terminates a process. - Example ``` - import process from '@ohos.process'; process.exit(0); ``` @@ -629,12 +1032,11 @@ Terminates a process. cwd\(\): string -Obtains the working directory of the process. +Obtains the working directory of this process. - Example ``` - import process from '@ohos.process'; var path = process.cwd(); ``` @@ -643,7 +1045,7 @@ Obtains the working directory of the process. chdir\(dir: string\): void -Changes the working directory of the process. +Changes the working directory of this process. - Parameters @@ -673,7 +1075,6 @@ Changes the working directory of the process. - Example ``` - import process from '@ohos.process'; process.chdir('/system'); ``` @@ -682,7 +1083,7 @@ Changes the working directory of the process. uptime\(\): number -Obtains the running time of the process. +Obtains the running time of this process. - Return values @@ -704,7 +1105,6 @@ Obtains the running time of the process. - Example ``` - import process from '@ohos.process'; var time = process.uptime(); ``` @@ -760,7 +1160,7 @@ Sends a signal to the specified process to terminate it.

boolean

-

Whether the signal is sent successfully.

+

Returns true if the signal is sent successfully; returns false otherwise.

@@ -769,7 +1169,6 @@ Sends a signal to the specified process to terminate it. - Example ``` - import process from '@ohos.process' var pres = process.pid var result = that.kill(pres, 28) ``` diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md new file mode 100644 index 0000000000000000000000000000000000000000..9522366139b7fd8e2e73a4630eefeb279e063315 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -0,0 +1,1199 @@ +# Reminder Agent + +>**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 + + + + + + + + + + + + + + +

Phone

+

Tablet

+

Smart TV

+

Wearable

+

Yes

+

Yes

+

Yes

+

Yes

+
+ +## Modules to Import + +``` +import reminderAgent from '@ohos.reminderAgent'; +``` + +## Required Permissions + +ohos.permission.PUBLISH\_AGENT\_REMINDER + +## reminderAgent.publishReminder + +publishReminder\(reminderReq: ReminderRequest, callback: AsyncCallback\): void + +Publishes an agent-powered reminder. This method uses an asynchronous callback to return the published reminder's ID. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reminderReq

+

ReminderRequest

+

Yes

+

Reminder to be published.

+

callback

+

AsyncCallback<number>

+

Yes

+

Asynchronous callback used to return the result.

+
+ +- Example + + ``` + export default { + data: { + timer: { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + }, + startTimer() { + reminderAgent.publishReminder(timer, (err, reminderId) => { + console.log("reminderId = " + reminderId); + }); + } + } + ``` + + +## reminderAgent.publishReminder + +publishReminder\(reminderReq: ReminderRequest\): Promise + +Publishes an agent-powered reminder. This method uses a promise callback to return the published reminder's ID. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reminderReq

+

ReminderRequest

+

Yes

+

Reminder to be published.

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

Type

+

Description

+

Promise<number>

+

Promise used to return the result.

+
+ +- Example + + ``` + export default { + data: { + timer: { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + }, + startTimer() { + reminderAgent.publishReminder(this.timer).then((reminderId) => { + console.log("reminderId = " + reminderId); + }); + } + } + ``` + + +## reminderAgent.cancelReminder + +cancelReminder\(reminderId: number, callback: AsyncCallback\): void + +Cancels the reminder with the specified ID. This method uses an asynchronous callback to return the cancellation result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reminderId

+

number

+

Yes

+

ID of the reminder to cancel.

+

callback

+

AsyncCallback<void>

+

Yes

+

Asynchronous callback used to return the result.

+
+ +- Example + +``` +export default { + cancel() { + reminderAgent.cancelReminder(1, (err, data) => { + console.log("do next"); + }); + } +} +``` + +## reminderAgent.cancelReminder + +cancelReminder\(reminderId: number\): Promise + +Cancels the reminder with the specified ID. This method uses a promise to return the cancellation result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reminderId

+

number

+

Yes

+

ID of the reminder to cancel.

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

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + +``` +export default { + cancel() { + reminderAgent.cancelReminder(1).then(() => { + console.log("do next"); + }); + } +} +``` + +## reminderAgent.getValidReminders + +getValidReminders\(callback: AsyncCallback\>\): void + +Obtains all valid \(not yet expired\) reminders set by the current application. This method uses an asynchronous callback to return the reminders. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<Array<ReminderRequest>>

+

Yes

+

Asynchronous callback used to return an array of all valid reminders set by the current application.

+
+ +- Example + +``` +reminderAgent.getValidReminders((err, reminders) => { + for (let i = 0; i < reminders.length; i++) { + console.log("getValidReminders = " + reminders[i]); + console.log("getValidReminders, reminderType = " + reminders[i].reminderType); + for (let j = 0; j < reminders[i].actionButton.length; j++) { + console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); + console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); + } + console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); + console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); + console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); + console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); + console.log("getValidReminders, title = " + reminders[i].title); + console.log("getValidReminders, content = " + reminders[i].content); + console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); + console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); + console.log("getValidReminders, notificationId = " + reminders[i].notificationId); + console.log("getValidReminders, slotType = " + reminders[i].slotType); + } +}) +``` + +## reminderAgent.getValidReminders + +getValidReminders\(\): Promise\> + +Obtains all valid \(not yet expired\) reminders set by the current application. This method uses a promise to return the reminders. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<Array<ReminderRequest>>

+

Promise used to return an array of all valid reminders set by the current application.

+
+ +- Example + +``` +reminderAgent.getValidReminders().then((reminders) => { + for (let i = 0; i < reminders.length; i++) { + console.log("getValidReminders = " + reminders[i]); + console.log("getValidReminders, reminderType = " + reminders[i].reminderType); + for (let j = 0; j < reminders[i].actionButton.length; j++) { + console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); + console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); + } + console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); + console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); + console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); + console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); + console.log("getValidReminders, title = " + reminders[i].title); + console.log("getValidReminders, content = " + reminders[i].content); + console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); + console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); + console.log("getValidReminders, notificationId = " + reminders[i].notificationId); + console.log("getValidReminders, slotType = " + reminders[i].slotType); + } +}) +``` + +## reminderAgent.cancelAllReminders + +cancelAllReminders\(callback: AsyncCallback\): void + +Cancels all reminders set by the current application. This method uses an asynchronous callback to return the cancellation result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

callback

+

AsyncCallback<void>

+

Yes

+

Asynchronous callback used to return the result.

+
+ +- Example + +``` +reminderAgent.cancelAllReminders((err, data) =>{ + console.log("do next")} +) +``` + +## reminderAgent.cancelAllReminders + +cancelAllReminders\(\): Promise + +Cancels all reminders set by the current application. This method uses a promise to return the cancellation result. + +- Return values + + + + + + + + + + +

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + +``` +reminderAgent.cancelAllReminders().then(() => { + console.log("do next")} +) +``` + +## reminderAgent.addNotificationSlot + +addNotificationSlot\(slot: NotificationSlot, callback: AsyncCallback\): void + +Adds a reminder notification slot. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

slot

+

NotificationSlot

+

Yes

+

Reminder notification slot to add.

+

callback

+

AsyncCallback<void>

+

Yes

+

Asynchronous callback used to return the result.

+
+ +- Example + +``` +export default { + data: { + mySlot: { + type: 3, + sound: "/sdcard/music2.mp3" + } + }, + addSlot() { + reminderAgent.addNotificationSlot(this.mySlot, (err, data) => { + console.log("do next"); + }); + } +} +``` + +## reminderAgent.addNotificationSlot + +addNotificationSlot\(slot: NotificationSlot\): Promise + +Adds a reminder notification slot. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

slot

+

NotificationSlot

+

Yes

+

Reminder notification slot to add.

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

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + +``` +export default { + data: { + mySlot: { + type: 3, + sound: "/sdcard/music2.mp3" + } + }, + addSlot() { + reminderAgent.addNotificationSlot(this.mySlot).then(() => { + console.log("do next"); + }); + } +} +``` + +## reminderAgent.removeNotificationSlot + +removeNotificationSlot\(slotType: notification.SlotType, callback: AsyncCallback\): void + +Removes a **NotificationSlot** instance of a specified type. This method uses an asynchronous callback to return the result. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

slotType

+

notification.SlotType

+

Yes

+

Type of the reminder notification slot to remove.

+

callback

+

AsyncCallback<void>

+

Yes

+

Asynchronous callback used to return the result.

+
+ +- Example + +``` +export default { + removeSlot() { + reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { + console.log("do next"); + }); + } +} +``` + +## reminderAgent.removeNotificationSlot + +removeNotificationSlot\(slotType: notification.SlotType\): Promise + +Removes a **NotificationSlot** instance of a specified type. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

slotType

+

notification.SlotType

+

Yes

+

Type of the reminder notification slot to remove.

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

Type

+

Description

+

Promise<void>

+

Promise used to return the result.

+
+ +- Example + +``` +export default { + removeSlot() { + reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { + console.log("do next"); + }); + } +} +``` + +## ActionButtonType + +Enumerates button types. + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

ACTION_BUTTON_TYPE_CLOSE

+

0

+

Button for closing the reminder.

+

ACTION_BUTTON_TYPE_SNOOZE

+

1

+

Button for snoozing the reminder.

+
+ +## ReminderType + +Enumerates reminder types. + + + + + + + + + + + + + + + + + + + + +

Name

+

Default Value

+

Description

+

REMINDER_TYPE_TIMER

+

0

+

Countdown reminder.

+

REMINDER_TYPE_CALENDAR

+

1

+

Calendar reminder.

+

REMINDER_TYPE_ALARM

+

2

+

Alarm reminder.

+
+ +## ActionButton + +Defines a button displayed in the reminder notification. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

title

+

string

+

Yes

+

Text on the button.

+

type

+

ActionButtonType

+

Yes

+

Button type.

+
+ +## WantAgent + +Sets the package and ability that are redirected to when the reminder notification is clicked. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

pkgName

+

string

+

Yes

+

Name of the package redirected to when the reminder notification is clicked.

+

abilityName

+

string

+

Yes

+

Name of the ability that is redirected to when the reminder notification is clicked.

+
+ +## MaxScreenWantAgent + +Sets the name of the target package and ability to start automatically when the reminder arrives and the device is not in use. If the device is in use, a notification will be displayed. + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

pkgName

+

string

+

Yes

+

Name of the package that is automatically started when the reminder arrives and the device is not in use.

+

abilityName

+

string

+

Yes

+

Name of the ability that is automatically started when the reminder arrives and the device is not in use.

+
+ +## ReminderRequest + +Defines the reminder to publish. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

reminderType

+

ReminderType

+

Yes

+

Type of the reminder.

+

actionButton

+

[ActionButton?, ActionButton?]

+

No

+

Action button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)

+

wantAgent

+

WantAgent

+

No

+

Information about the ability that is redirected to when the notification is clicked.

+

maxScreenWantAgent

+

MaxScreenWantAgent

+

No

+

Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.

+

ringDuration

+

number

+

No

+

Ringing duration.

+

snoozeTimes

+

number

+

No

+

Number of reminder snooze times.

+

timeInterval

+

number

+

No

+

Reminder snooze interval.

+

title

+

string

+

No

+

Reminder title.

+

content

+

string

+

No

+

Reminder content.

+

expiredContent

+

string

+

No

+

Content to be displayed after the reminder expires.

+

snoozeContent

+

string

+

No

+

Content to be displayed when the reminder is snoozing.

+

notificationId

+

number

+

No

+

Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.

+

slotType

+

notification.SlotType

+

No

+

Type of the slot used by the reminder.

+
+ +## ReminderRequestCalendar + +ReminderRequestCalendar extends ReminderRequest + +Defines a reminder for a calendar event. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

dateTime

+

LocalDateTime

+

Yes

+

Reminder time.

+

repeatMonths

+

Array<number>

+

No

+

Month in which the reminder repeats.

+

repeatDays

+

Array<number>

+

No

+

Date on which the reminder repeats.

+
+ +## ReminderRequestAlarm + +ReminderRequestAlarm extends ReminderRequest + +Defines a reminder for the alarm clock. + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

hour

+

number

+

Yes

+

Hour portion of the reminder time.

+

minute

+

number

+

Yes

+

Minute portion of the reminder time.

+

daysOfWeek

+

Array<number>

+

No

+

Days of a week when the reminder repeats.

+
+ +## ReminderRequestTimer + +Defines a **ReminderRequestTimer** instance, which extends **ReminderRequest**. + +Defines a reminder for a scheduled timer. + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

triggerTimeInSeconds

+

number

+

Yes

+

Number of seconds in the countdown timer.

+
+ +## LocalDateTime + +Sets the time information for a calendar reminder. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

year

+

number

+

Yes

+

Year.

+

month

+

number

+

Yes

+

Month.

+

day

+

number

+

Yes

+

Date.

+

hour

+

number

+

Yes

+

Hour.

+

minute

+

number

+

Yes

+

Minute.

+

second

+

number

+

No

+

Second.

+
+ diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index d90f8aef6a156bfc2eb68a8d639aa001831d4f11..011b9cc217a06a07416cb37cc689d093f86c3947 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,9 +1,9 @@ -# Resource Manager +# Resource Manager + >![](../../public_sys-resources/icon-note.gif) **NOTE:** >The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ``` @@ -362,8 +362,6 @@ Enumerates screen density types. Provides the device configuration. -### Attributes - @@ -406,8 +404,6 @@ Provides the device configuration. Provides the device capability. -### Attributes -

Name

@@ -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 getString\(resId: number, callback: AsyncCallback\): 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 - @@ -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 - @@ -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 - @@ -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 ``` +### getRawFile8+ + +getRawFile\(path: string, callback: AsyncCallback\): void + +Obtains the content of rawfile in the specified path. This method uses an asynchronous callback to return the result. + +- Parameters + + +

Name

Promise<Array<string>>

Array of character strings corresponding to the specified resource ID.

+

Array of strings corresponding to the specified resource ID.

callback

AsyncCallback<Array<Uint8Array>>

+

AsyncCallback<Uint8Array>

Yes

Promise<Array<Uint8Array>>

+

Promise<Uint8Array>

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

+ + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Path of the rawfile.

+

callback

+

AsyncCallback<Uint8Array>

+

Yes

+

Asynchronous callback used to return the rawfile content, in byte arrays.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getRawFile("test.xml", (error, value) => { + if (error != null) { + console.log(value); + } else { + console.log(value); + } + }); + }); + ``` + + +### getRawFile8+ + +getRawFile\(path: string\): Promise + +Obtains the content of the rawfile in the specified path. This method uses a promise to return the result. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

path

+

string

+

Yes

+

Path of the rawfile.

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

Type

+

Description

+

Promise<Uint8Array>

+

Promise used to return the rawfile content, in byte arrays.

+
+ +- Example + + ``` + resourceManager.getResourceManager((error, mgr) => { + mgr.getRawFile("test.xml").then(value => { + console.log(value); + }).catch(error => { + console.log("getrawfile promise " + error); + }); + }); + ``` + diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index 9c99661eb2ae5544557b53509bcb265d4c2c094e..106d47b814e282b0d22b84d1f84dfe1163313172 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -1,6 +1,6 @@ # Running Lock ->![](../../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 @@ -9,9 +9,10 @@ import runninglock from '@ohos.runningLock'; ``` -## Required Permissions +## System Capabilities + +SystemCapability.PowerManager.PowerManager -To request or use a running lock, you must declare the **ohos.permission.RUNNING\_LOCK** permission. ## RunningLockType diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-service-extension-context.md new file mode 100644 index 0000000000000000000000000000000000000000..fa46ef6df13d0e7bd7b4c8dd788fbe4184417488 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-service-extension-context.md @@ -0,0 +1,193 @@ +# ServiceExtensionContext + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +Implements the context that provides the capabilities and APIs of **ServiceExtension**. This class is inherited from **ExtensionContext**. + + +## startAbility + + +startAbility(want: Want, callback: AsyncCallback<void>): void; + + +Starts an ability. This method uses a callback to return the result. + + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, such as the ability name and bundle name.| + | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the method is successfully called.| + +- Example + ``` + let want = { + "bundleName": "com.example.myapp", + "abilityName": "com.example.myapp.MyAbility" + }; + this.context.startAbility(want, (err) => { + console.log('startAbility result:' + JSON.stringfy(err); + } + ``` + + +## startAbility + +startAbility(want: Want): Promise<void>; + +Starts an ability. This method uses a promise to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to start, such as the ability name and bundle name.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the method is successfully called.| + +- Example + ``` + let want = { + "bundleName": "com.example.myapp", + "abilityName": "com.example.myapp.MyAbility" + }; + this.context.startAbility(want).then((data) => { + console.log('success:' + JSON.stringfy(data)); + )).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); + }); + ``` + + +## terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void; + +Terminates this ability. This method uses a callback to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.terminateSelf((err) => { + console.log('terminateSelf result:' + JSON.stringfy(err); + } + ``` + + +## terminateSelf + +terminateSelf(): Promise<void>; + +Terminates this ability. This method uses a promise to return the result. + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.terminateSelf(want).then((data) => { + console.log('success:' + JSON.stringfy(data)); + )).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); + }); + ``` + + +## connectAbility + +connectAbility(want: Want, options: ConnectOptions): number; + +Connects this ability to a Service ability. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information about the ability to connect to, such as the ability name and bundle name.| + | options | [ConnectOptions](#connectoptions) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| + +- Return value + | Type| Description| + | -------- | -------- | + | number | A number, based on which the connection will be interrupted.| + +- Example + ``` + let want = { + "bundleName": "com.example.myapp", + "abilityName": "com.example.myapp.MyAbility" + }; + let options = { + onConnect: function(elementName, proxy) {} + onDisConnect: function(elementName) {} + onFailed: function(code) {} + } + let connection = this.context.connectAbility(want,options); + ``` + + +## disconnectAbility + +disconnectAbility(connection: number, callback:AsyncCallback<void>): void; + +Disconnects this ability from the Service ability. This method uses a callback to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | connection | number | Yes| Number returned after **connectAbility** is called.| + | callback | AsyncCallback<void> | No| Callback used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.disconnectAbility(connection, (err) => { // connection is the return value of connectAbility. + console.log('terminateSelf result:' + JSON.stringfy(err); + } + ``` + + +## disconnectAbility + +disconnectAbility(connection: number): Promise<void>; + +Disconnects this ability from the Service ability. This method uses a promise to return the result. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | connection | number | Yes| Number returned after **connectAbility** is called.| + +- Return value + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result indicating whether the method is successfully called.| + +- Example + ``` + this.context.disconnectAbility(connection).then((data) => { // connection is the return value of connectAbility. + console.log('success:' + JSON.stringfy(data)); + )).catch((error) => { + console.log('failed:' + JSON.stringfy(error)); + }); + ``` + + +## ConnectOptions + +Defines the **ConnectOptions** data structure. + +| Name| Description| +| -------- | -------- | +| onConnect(elementName:ElementName, remote:IRemoteObject) | Called when this ability is connected to a Service ability.| +| onDisconnect(elementName:ElementName) | Called when the peer service is abnormal or killed.| +| onFailed(code: number) | Called when the connection fails.| diff --git a/en/application-dev/reference/apis/js-apis-service-extension.md b/en/application-dev/reference/apis/js-apis-service-extension.md new file mode 100644 index 0000000000000000000000000000000000000000..22f46948c07041a90488fef30df310ddb2f1294f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-service-extension.md @@ -0,0 +1,133 @@ +# ServiceExtension + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> The initial APIs of this module are supported since API 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +Provides APIs related to **ServiceExtension**. + + +## Modules to Import + +``` +import ServiceExtension from '@ohos.application.ServiceExtension'; +``` + + +## Required Permissions + +None + + +## Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service extension context, which is inherited from **ExtensionContext**.| + + +## onCreate + +onCreate(want: Want): void; + +Called when an extension is created to initialize the service logic. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| + +- Example + ``` + onCreate(want) { + console.log('onCreate, want:' + want.abilityName); + } + ``` + + +## onDestroy + +onDestroy(): void; + +Called when this extension is destroyed to clear resources. + +- Example + ``` + onDestroy() { + console.log('onDestroy'); + destory(); + } + ``` + + +## onRequest + +onRequest(want: Want, startId: number): void; + +Called after **onCreate** is invoked when an ability is started by calling **startAbility**. The value of **startId** is incremented for each ability that is started. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| + | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| + +- Example + ``` + onRequest(want: Want, startId: number) { + console.log('onRequest, want:' + want.abilityName); + } + ``` + + +## onConnect + +onConnect(want: Want): rpc.RemoteObject; + +Called after **onCreate** is invoked when an ability is started by calling **connectAbility**. A **RemoteObject** object is returned for communication with the client. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want | [Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| + +- Return value + | Type| Description| + | -------- | -------- | + | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| + +- Example + ``` + import rpc from '@ohos.rpc' + class StubTest extends rpc.RemoteObject{ + constructor(des) { + super(des); + } + onRemoteRequest(code, data, reply, option) { + } + } + ... + onConnect(want) { + console.log('onConnect , want:' + want.abilityName); + return new StubTest("test"); + } + ``` + + +## onDisconnect + +onDisconnect(want: Want): void; + +Called when the ability is disconnected. + +- Parameters + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | want |[Want](js-apis-featureAbility.md#Want)| Yes| Information related to this extension, including the ability name and bundle name.| + +- Example + ``` + onDisconnect(want) { + console.log('onDisconnect, want:' + want.abilityName); + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-statfs.md b/en/application-dev/reference/apis/js-apis-statfs.md new file mode 100644 index 0000000000000000000000000000000000000000..9e72201f75090675a473d286bd5b0f452a408e65 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-statfs.md @@ -0,0 +1,115 @@ +# statfs + + + +## Modules to Import + +``` +import statfs from '@ohos.statfs' +``` + +## Note + +Before using this module to perform operations on a file or directory, obtain the absolute path of the file or directory. For details, see [getOrCreateLocalDir of the Context module](js-apis-Context.md). + +Absolute file or directory path = Application directory + File name or directory name + +For example, if the application directory obtained by using **getOrCreateLocalDir** is **dir** and the file name is **xxx.txt**, the absolute path of the file is as follows: + +``` +let path = dir + "xxx.txt" +``` + +## Required Permissions + +None + +## statfs.getFreeBytes + +getFreeBytes(path:string):Promise<number> + +Obtains the number of free bytes of the specified file system in asynchronous mode. This method uses a promise to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | ------ | ------ | ---- | ---------------------------- | + | path | string | Yes| File path of the file system.| + +- Return values + + | Type| Description| + | --------------------- | -------------- | + | Promise<number> | Number of free bytes obtained.| + +- Example + + ``` + let num = await statfs.getFreeBytes(path); + ``` + +## statfs.getFreeBytes + +getFreeBytes(path:string, callback:AsyncCallback<number>): void + +Obtains the number of free bytes of the specified file system in asynchronous mode. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | --------------------------- | ---- | ---------------------------- | + | path | string | Yes| File path of the file system.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of free bytes obtained.| + +- Example + + ``` + statfs.getFreeBytes(path, function(err, number){ + // Do something. + }); + ``` + +## statfs.getTotalBytes + +getTotalBytes.(path:string):Promise<number> + +Obtains the total number of bytes of the specified file system in asynchronous mode. This method uses a promise to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | ---- | ------ | ---- | ---------------------------- | + | path | string | Yes| File path of the file system.| + +- Return values + + | Type| Description| + | --------------------- | ------------ | + | Promise<number> | Total number of bytes obtained.| + +- Example + + ``` + let num = await statfs.getTotalBytes(path); + ``` + +## statfs.getTotalBytes + +getTotalBytes(path:string, callback:AsyncCallback<number>): void + +Obtains the total number of bytes of the specified file system in asynchronous mode. This method uses a callback to return the result. + +- Parameters + + | Name| Type| Mandatory| Description| + | -------- | --------------------------- | ---- | ---------------------------- | + | path | string | Yes| File path of the file system.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the total number of bytes obtained.| + +- Example + + ``` + statfs.getTotalBytes(path, function(err, number){ + // Do something. + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index e851eec1055856e6d5a97f45bb45199143ea742d..d7cedf77c5f9d2c403e243952dba0ba3e8974564 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -3,30 +3,6 @@ >![](../../public_sys-resources/icon-note.gif) **NOTE:** >The APIs of this module are supported since API version 7. -## Applicable Devices - - - - - - - - - - - - - - -

Phone

-

Tablet

-

Smart TV

-

Wearable

-

Yes

-

Yes

-

Yes

-

Yes

-
## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md new file mode 100644 index 0000000000000000000000000000000000000000..c3eb105e1c4a8b56a4de085d61c4d9abd76c9fae --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -0,0 +1,338 @@ +# URI String Parsing + +>![](../../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 uri from '@ohos.uri' +``` + +## Required Permissions + +None + +## URI + +### Attributes + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

scheme

+

string

+

Yes

+

No

+

Protocol in the URI.

+

userinfo

+

string

+

Yes

+

No

+

User information in the URI.

+

host

+

string

+

Yes

+

No

+

Host name (without the port number) in the URI.

+

port

+

string

+

Yes

+

No

+

Port number in the URI.

+

path

+

string

+

Yes

+

No

+

Path in the URI.

+

query

+

string

+

Yes

+

No

+

Query part in the URI.

+

fragment

+

string

+

Yes

+

No

+

Fragment part in the URI.

+

authority

+

string

+

Yes

+

No

+

Authority part in the URI.

+

ssp

+

string

+

Yes

+

No

+

Scheme-specific part in the URI.

+
+ +### constructor + +constructor\(uri: string\) + +A constructor used to create a URI instance. + +- Parameters + + + + + + + + + + + + + + + + +

Name

+

Type

+

Readable

+

Writable

+

Description

+

url

+

string

+

Yes

+

Yes

+

Input parameter object.

+
+ + +- Example + + ``` + var mm = 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; + new uri.URI(mm); // Output 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; + ``` + + ``` + new uri.URI('http://username:password@host:8080'); // Output 'http://username:password@host:8080'; + ``` + + +### toString + +toString\(\): string + +Obtains the query string applicable to this URL. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Website address in a serialized string.

+
+ + +- Example + + ``` + const url = new uri.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); + url.toString() + ``` + + +### equals + +equals\(other: URI\): boolean + +Checks whether this URI is the same as another URI object. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

other

+

URI

+

Yes

+

URI object to compare.

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

Type

+

Description

+

boolean

+

Returns true if the two URIs are the same; returns false otherwise.

+
+ + +- Example + + ``` + const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); + const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); + uriInstance.equals(uriInstance1); + ``` + + +### checkIsAbsolute + +checkIsAbsolute\(\): boolean + +Checks whether this URI is an absolute URI \(whether the scheme component is defined\). + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the URI is an absolute URI; returns false otherwise.

+
+ + +- Example + + ``` + const uriInstance = new uri.URI('http://username:password@www.qwer.com:8080?query=pppppp'); + uriInstance.checkIsAbsolute(); + ``` + + +### normalize + +normalize\(\): URI + +Normalizes the path of this URI. + +- Return values + + + + + + + + + + +

Type

+

Description

+

URI

+

URI with the normalized path.

+
+ + +- Example + + ``` + const uriInstance = new uri.URI('http://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); + let uriInstance1 = uriInstance.normalize(); + uriInstance1.path; + ``` + + diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index e05a6fdd45fa03a6c9c47e5114b6f728816f3880..267445bbd619c466f4416e2647c6782e19c61465 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -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 - - - - - - - - - - - - - - -

Phone

-

Tablet

-

Smart TV

-

Wearable

-

Yes

-

Yes

-

No

-

No

-
## Modules to Import diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 6301c943364ab64144197703118e217fe813ff32..420cddd41bad06fb5c125246c856af52a4eaacc3 100644 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -193,8 +193,8 @@ Calls back an asynchronous function. In the callback, the first parameter indica } var cb = util.callbackWrapper(promiseFn); cb((err, ret) => { - expect(err).strictEqual('value'); - expect(ret).strictEqual(undefined); + console.log(err); + console.log(ret); }) ``` @@ -259,7 +259,7 @@ Processes an asynchronous function and returns a promise version. } let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); newPromiseObj.then(res => { - expect(res).strictEqual('HelloWorld'); + console.log(res); }) ``` @@ -3054,7 +3054,7 @@ Encodes the input content asynchronously. var rarray = new Uint8Array([99,122,69,122]); await that.encode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { - expect(val[i]).assertEqual(rarray[i]) + console.log(val[i]) } }) done(); @@ -3115,7 +3115,7 @@ Encodes the input content asynchronously into a string. var that = new util.Base64(); var array = new Uint8Array([115,49,51]); await that.encodeToString(array).then(val=>{ - expect(val).assertEqual('czEz') + console.log(val) }) done(); ``` @@ -3177,7 +3177,7 @@ Decodes the input content asynchronously. var rarray = new Uint8Array([115,49,51]); await that.decode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { - expect(val[i]).assertEqual(rarray[i]) + console.log(val[i]) } }) done(); @@ -5174,4 +5174,3 @@ Checks whether the input value is of the **WeakSet** type. var result = that.isWeakSet(new WeakSet()); ``` - diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 33f56166dd0ba931ceeebc48f506e04e8e8fb661..3493f9813ba2c98d1e62dd6526511fa832c1bbb9 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -9,6 +9,10 @@ import window from '@ohos.window'; ``` +## System Capabilities +SystemCapability.WindowManager.WindowManager.Core + + ## Required Permissions 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)) diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index ff388df2f05e45d5831d4d72102bdfd6a04ae854..53879bb88fdee523a3f5fdbd0ebc61113c3cc367 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -1,6 +1,6 @@ # Worker Startup ->![](../../public_sys-resources/icon-note.gif) **NOTE:** +>**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 @@ -131,13 +131,13 @@ A constructor used to create a worker instance. - Return values -

Name

+ - @@ -148,8 +148,7 @@ A constructor used to create a worker instance. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js", {name:"first worker"}); + const workerInstance = new worker.Worker("workers/worker.js", {name:"first worker"}); ``` @@ -196,13 +195,14 @@ Sends a message to the worker thread. The data is transferred using the structur - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js"); - worker.postMessage("hello world"); - - const worker = new worker.Worker("workers/worker.js"); + const workerInstance = new worker.Worker("workers/worker.js"); + workerInstance.postMessage("hello world"); + ``` + + ``` + const workerInstance = new worker.Worker("workers/worker.js"); var buffer = new ArrayBuffer(8); - worker.postMessage(buffer, [buffer]); + workerInstance.postMessage(buffer, [buffer]); ``` @@ -249,9 +249,8 @@ Adds an event listener to the worker. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.on("alert", (e)=>{ + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.on("alert", (e)=>{ console.log("alert listener callback"); }) ``` @@ -300,9 +299,8 @@ Adds an event listener to the worker and removes the event listener automaticall - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js"); - worker.once("alert", (e)=>{ + const workerInstance = new worker.Worker("workers/worker.js"); + workerInstance.once("alert", (e)=>{ console.log("alert listener callback"); }) ``` @@ -351,9 +349,8 @@ Removes an event listener for the worker. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js"); - worker.off("alert"); + const workerInstance = new worker.Worker("workers/worker.js"); + workerInstance.off("alert"); ``` @@ -366,9 +363,8 @@ Terminates the worker thread to stop the worker from receiving messages. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.terminate() + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.terminate() ``` @@ -406,9 +402,8 @@ Defines the event handler to be called when the worker exits. The handler is exe - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.onexit = function(e) { + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.onexit = function(e) { console.log("onexit") } ``` @@ -448,9 +443,8 @@ Defines the event handler to be called when an exception occurs during worker ex - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.onerror = function(e) { + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.onerror = function(e) { console.log("onerror") } ``` @@ -490,9 +484,8 @@ Defines the event handler to be called when the host thread receives a message c - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.onmessage = function(e) { + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.onmessage = function(e) { console.log("onerror") } ``` @@ -532,9 +525,8 @@ Defines the event handler to be called when the worker receives a message that c - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.onmessageerror= function(e) { + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.onmessageerror= function(e) { console.log("onmessageerror") } ``` @@ -585,9 +577,8 @@ Adds an event listener to the worker. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.addEventListener("alert", (e)=>{ + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) ``` @@ -636,9 +627,8 @@ Removes an event listener for the worker. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.removeEventListener("alert") + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.removeEventListener("alert") ``` @@ -676,7 +666,7 @@ Dispatches the event defined for the worker. - Return values -

Type

Description

worker

+

Worker

Returns the worker instance created; returns undefined if the worker instance fails to be created.

-

Name

+ @@ -693,9 +683,8 @@ Dispatches the event defined for the worker. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.dispatchEvent({type:"alert"}) + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.dispatchEvent({type:"alert"}) ``` @@ -708,9 +697,8 @@ Removes all event listeners for the worker. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.removeAllListener({type:"alert"}) + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.removeAllListener({type:"alert"}) ``` @@ -762,13 +750,15 @@ Sends a message to the host thread from the worker. ``` // main.js - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.postMessage("hello world") - worker.onmessage = function(e) { + import worker from "@ohos.worker"; + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.postMessage("hello world") + workerInstance.onmessage = function(e) { console.log("receive data from worker.js") } - + ``` + + ``` // worker.js import worker from "@ohos.worker"; const parentPort = worker.parentPort; @@ -789,8 +779,10 @@ Closes the worker thread to stop the worker from receiving messages. ``` // main.js import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - + const workerInstance = new worker.Worker("workers/worker.js") + ``` + + ``` // worker.js import worker from "@ohos.worker"; const parentPort = worker.parentPort; @@ -836,9 +828,11 @@ Defines the event handler to be called when the worker thread receives a message ``` // main.js import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - worker.postMessage("hello world") - + const workerInstance = new worker.Worker("workers/worker.js") + workerInstance.postMessage("hello world") + ``` + + ``` // worker.js import worker from "@ohos.worker"; const parentPort = worker.parentPort; @@ -884,8 +878,10 @@ Defines the event handler to be called when the worker receives a message that c ``` // main.js import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - + const workerInstance = new worker.Worker("workers/worker.js") + ``` + + ``` // worker.js import worker from "@ohos.worker"; const parentPort = worker.parentPort; @@ -1004,7 +1000,7 @@ Specifies the callback to invoke. - Return values -

Type

Description

- - - - - - -

Name

+ @@ -1021,9 +1017,8 @@ Specifies the callback to invoke. - Example ``` - import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js"); - worker.addEventListener("alert", (e)=>{ + const workerInstance = new worker.Worker("workers/worker.js"); + workerInstance.addEventListener("alert", (e)=>{ console.log("alert listener callback"); }) ``` @@ -1215,8 +1210,10 @@ Defines the event handler to be called when an exception occurs during worker ex ``` // main.js import worker from '@ohos.worker'; - const worker = new worker.Worker("workers/worker.js") - + const workerInstance = new worker.Worker("workers/worker.js") + ``` + + ``` // worker.js import worker from "@ohos.worker"; const parentPort = worker.parentPort diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md new file mode 100644 index 0000000000000000000000000000000000000000..98ff62e6a3926a15f049b6a18d98d8f9a463c2b4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -0,0 +1,976 @@ +# XML Parsing and Generation + +>![](../../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 xml from '@ohos.xml'; +``` + +## Required Permissions + +None + +## XmlSerializer + +### constructor + +constructor\(buffer: ArrayBuffer | DataView, encoding?: string\) + +A constructor used to create an **XmlSerializer** instance. + +- Parameters + + +

Type

Description

+ + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

buffer

+

ArrayBuffer | DataView

+

Yes

+

ArrayBuffer or DataView for storing the XML information to write.

+

encoding

+

string

+

No

+

Encoding format.

+
+ + +- Example + + ``` + var arrayBuffer = new ArrayBuffer(1024); + var bufView = new DataView(arrayBuffer); + var thatSer = new xml.XmlSerializer(bufView); + ``` + + +### setAttributes + +setAttributes\(name: string, value: string\): void + +Sets an attribute. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Key of the attribute.

+

value

+

string

+

Yes

+

Value of the attribute.

+
+ +- Example + + ``` + var thatSer = new xml.XmlSerializer(bufView); + thatSer.setAttributes("importance", "high"); + ``` + + +### addEmptyElement + +addEmptyElement\(name: string\): void + +Adds an empty element. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the empty element to add.

+
+ + +- Example + + ``` + var thatSer = new xml.XmlSerializer(bufView); + thatSer.addEmptyElement("b"); // => + ``` + + +### setDeclaration + +setDeclaration\(\): void + +Sets a declaration. + +- Example + + ``` + var thatSer = new xml.XmlSerializer(bufView); + thatSer.setDeclaration() // => ; + ``` + + +### startElement + +startElement\(name: string\): void + +Writes the start tag based on the given element name. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

name

+

string

+

Yes

+

Name of the element.

+
+ + +- Example + + ``` + var arrayBuffer = new ArrayBuffer(1024); + var thatSer = new xml.XmlSerializer(arrayBuffer); + thatSer.startElement("notel"); + thatSer.endElement();// => ''; + ``` + + +### endElement + +endElement\(\): void + +Writes the end tag of the element. + +- Example + + ``` + var thatSer = new xml.XmlSerializer(bufView); + thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); + thatSer.startElement("table"); + thatSer.setAttributes("importance", "high"); + thatSer.setText("Happy"); + endElement(); // => Happy + ``` + + +### setNamespace + +setNamespace\(prefix: string, namespace: string\): void + +Sets the namespace for an element tag. + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

prefix

+

string

+

Yes

+

Prefix of the element and its child elements.

+

namespace

+

string

+

Yes

+

Namespace to set.

+
+ + +- Example + + ``` + var arrayBuffer = new ArrayBuffer(1024); + var thatSer = new xml.XmlSerializer(arrayBuffer); + thatSer.setDeclaration(); + thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); + thatSer.startElement("note"); + thatSer.endElement();// = >'\r\n'; + ``` + + +### setComment + +setComment\(text: string\): void + +Sets the comment. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

text

+

string

+

Yes

+

Comment to set.

+
+ + +- Example + + ``` + var arrayBuffer = new ArrayBuffer(1024); + var thatSer = new xml.XmlSerializer(arrayBuffer); + thatSer.startElement("note"); + thatSer.setComment("Hi!"); + thatSer.endElement(); // => '\r\n \r\n'; + ``` + + +### setCDATA + +setCDATA\(text: string\): void + +Sets CDATA attributes. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

text

+

string

+

Yes

+

CDATA attribute to set.

+
+ + +- Example + + ``` + var arrayBuffer = new ArrayBuffer(1028); + var thatSer = new xml.XmlSerializer(arrayBuffer); + thatSer.setCDATA('root SYSTEM') // => ''; + ``` + + +### setText + +setText\(text: string\): void + +Sets **Text**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

text

+

string

+

Yes

+

Content of the Text to set.

+
+ + +- Example + + ``` + var arrayBuffer = new ArrayBuffer(1024); + var thatSer = new xml.XmlSerializer(arrayBuffer); + thatSer.startElement("note"); + thatSer.setAttributes("importance", "high"); + thatSer.setText("Happy1"); + thatSer.endElement(); // => 'Happy1'; + ``` + + +### setDocType + +setDocType\(text: string\): void + +Sets **DocType**. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

text

+

string

+

Yes

+

Content of DocType to set.

+
+ + +- Example + + ``` + var arrayBuffer = new ArrayBuffer(1024); + var thatSer = new xml.XmlSerializer(arrayBuffer); + thatSer.setDocType('root SYSTEM'); // => ''; + ``` + + +## XmlPullParser + +### XmlPullParser + +constructor\(buffer: ArrayBuffer | DataView, encoding?: string\) + +Creates and returns an **XmlPullParser** object. The **XmlPullParser** object passes two parameters. The first parameter is the memory of the **ArrayBuffer** or **DataView** type, and the second parameter is the file format \(UTF-8 by default\). + +- Parameters + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

buffer

+

ArrayBuffer | DataView

+

Yes

+

ArrayBuffer or DataView that contains XML text information.

+

encoding

+

string

+

No

+

Encoding format. Only UTF-8 is supported.

+
+ + +- Example + + ``` + var strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; + var arrayBuffer = new ArrayBuffer(strXml.length*2); + var bufView = new Uint8Array(arrayBuffer); + var strLen = strXml.length; + for (var i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i);// Set the ArrayBuffer mode. + } + var that = new xml.XmlPullParser(arrayBuffer); + ``` + + +### parse + +parse\(option: ParseOptions\): void + +Parses XML information. + +- Parameters + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

option

+

ParseOptions

+

Yes

+

Options for controlling and obtaining the parsed information.

+
+ + +- Example + + ``` + var strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; + var arrayBuffer = new ArrayBuffer(strXml.length*2); + var bufView = new Uint8Array(arrayBuffer); + var strLen = strXml.length; + for (var i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i); + } + var that = new xml.XmlPullParser(arrayBuffer); + var arrTag = {}; + arrTag[0] = '132'; + var i = 1; + function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); + i++; + return true; + } + var options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} + that.parse(options); + ``` + + +## ParseOptions + +Defines the XML parsing options. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Type

+

Mandatory

+

Description

+

supportDoctype

+

boolean

+

No

+

Whether to ignore Doctype. The default value is false.

+

ignoreNameSpace

+

boolean

+

No

+

Whether to ignore Namespace. The default value is false.

+

tagValueCallbackFunction

+

(name: string, value: string)=> boolean

+

No

+

Callback used to return tagValue.

+

attributeValueCallbackFunction

+

(name: string, value: string)=> boolean

+

No

+

Callback used to return attributeValue.

+

tokenValueCallbackFunction

+

(eventType: EventType, value: ParseInfo)=> boolean

+

No

+

Callback used to return tokenValue.

+
+ +## ParseInfo + +Provides methods to manage the parsed XML information. + +### getColumnNumber + +getColumnNumber\(\): number + +Obtains the column line number, which starts from 1. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Column number obtained.

+
+ + +### getDepth + +getDepth\(\): number + +Obtains the depth of this element. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Depth obtained.

+
+ + +### getLineNumber + +getLineNumber\(\): number + +Obtains the current line number, starting from 1. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Line number obtained.

+
+ + +### getName + +getName\(\): string + +Obtains the name of this element. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Element name obtained.

+
+ + +### getNamespace + +getNamespace\(\): string + +Obtains the namespace of this element. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Namespace obtained.

+
+ + +### getPrefix + +getPrefix\(\): string + +Obtains the prefix of this element. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Element prefix obtained.

+
+ + +### getText + +getText\(\): string + +Obtains the text of the current event. + +- Return values + + + + + + + + + + +

Type

+

Description

+

string

+

Text content obtained.

+
+ + +### isEmptyElementTag + +isEmptyElementTag\(\): boolean + +Checks whether the current element is empty. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the element is empty; returns false otherwise.

+
+ + +### isWhitespace + +isWhitespace\(\): boolean + +Checks whether the current text event contains only whitespace characters. + +- Return values + + + + + + + + + + +

Type

+

Description

+

boolean

+

Returns true if the text event contains only whitespace characters; returns false otherwise.

+
+ + +### getAttributeCount + +getAttributeCount\(\): number + +Obtains the number of attributes for the current start tag. + +- Return values + + + + + + + + + + +

Type

+

Description

+

number

+

Number of attributes obtained.

+
+ + +## EventType + +Enumerates the events. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +

Name

+

Value

+

Description

+

START_DOCUMENT

+

0

+

Indicates a start document event.

+

END_DOCUMENT

+

1

+

Indicates an end document event.

+

START_TAG

+

2

+

Indicates a start tag event.

+

END_TAG

+

3

+

Indicates an end tag event.

+

TEXT

+

4

+

Indicates a text event.

+

CDSECT

+

5

+

Indicates a CDATA section event.

+

COMMENT

+

6

+

Indicates an XML comment event.

+

DOCDECL

+

7

+

Indicates an XML document type declaration event.

+

INSTRUCTION

+

8

+

Indicates an XML processing instruction event.

+

ENTITY_REFERENCE

+

9

+

Indicates an entity reference event.

+

WHITESPACE

+

10

+

Indicates a whitespace character event.

+
+ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-caution.gif b/en/application-dev/reference/apis/public_sys-resources/icon-caution.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-caution.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-danger.gif b/en/application-dev/reference/apis/public_sys-resources/icon-danger.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-danger.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-note.gif b/en/application-dev/reference/apis/public_sys-resources/icon-note.gif new file mode 100644 index 0000000000000000000000000000000000000000..6314297e45c1de184204098efd4814d6dc8b1cda Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-note.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-notice.gif b/en/application-dev/reference/apis/public_sys-resources/icon-notice.gif new file mode 100644 index 0000000000000000000000000000000000000000..86024f61b691400bea99e5b1f506d9d9aef36e27 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-notice.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-tip.gif b/en/application-dev/reference/apis/public_sys-resources/icon-tip.gif new file mode 100644 index 0000000000000000000000000000000000000000..93aa72053b510e456b149f36a0972703ea9999b7 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-tip.gif differ diff --git a/en/application-dev/reference/apis/public_sys-resources/icon-warning.gif b/en/application-dev/reference/apis/public_sys-resources/icon-warning.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e90d7cfc2193e39e10bb58c38d01a23f045d571 Binary files /dev/null and b/en/application-dev/reference/apis/public_sys-resources/icon-warning.gif differ diff --git a/en/contribute/OpenHarmony-64bits-coding-guide.md b/en/contribute/OpenHarmony-64bits-coding-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..32d5a20a9e3fc7cbf11149e7324b32ba3e08ecee --- /dev/null +++ b/en/contribute/OpenHarmony-64bits-coding-guide.md @@ -0,0 +1,590 @@ +# 32- and 64-Bit Portability Coding Guide + +## About This Document + +### Purpose + +OpenHarmony aims to build an open, distributed OS framework for smart IoT devices in the full-scenario, full-connectivity, and full-intelligence era. It has the following technical features: hardware collaboration for resource sharing, one-time development for multi-device deployment, and a unified OS for flexible deployment. +OpenHarmony supports the following system types: + +1. Mini system: a device oriented to devices that have MCU processors such as ARM Cortex-M and 32-bit RISC-V. These devices have limited hardware resources. The minimum device memory is 128 KiB. +2. Small system: a device oriented to devices that have application processors such as 64-bit ARM Cortex-A. The minimum device memory is 1 MiB. +3. Standard system: a device oriented to devices that have application processors such as 64-bit ARM Cortex-A. The minimum device memory is 128 MiB. + +OpenHarmony code can run on 32- and 64-bit devices. For easier code portability, clear coding specifications are necessary. This document stipulates the specifications on code porting and 64-bit coding, helping you improve code standardization and portability. + +### Application Scope + +C and C++ code for the user space and kernel space, without distinguishing the programming language standards. + +### Differences Between 32-Bit OS and 64-Bit OS + +#### Data Type Differences + +Most 32-bit OSs use ILP32, which defines int, long, and pointer as 32 bits. Most 64-bit OSs use LP64, which defines long, long long, and pointer as 64 bits. The Windows OS uses LLP64, which defines long long and pointer as 64 bits. The table below lists the length of each primitive data type. + +| **Type**| **ILP32** | **LP64** | **LLP64** | **LP32** | **ILP64** | +| --------- | --------- | -------- | --------- | -------- | --------- | +| char | 1 | 1 | 1 | 1 | 1 | +| short | 2 | 2 | 2 | 2 | 2 | +| int | 4 | 4 | 4 | 2 | 8 | +| long | **4** | **8** | **4** | 4 | 8 | +| long long | 8 | 8 | 8 | 8 | 8 | +| float | 4 | 4 | 4 | 4 | 4 | +| double | 8 | 8 | 8 | 8 | 8 | +| size_t | **4** | **8** | **8** | 4 | 8 | +| pointer | **4** | **8** | **8** | 4 | 8 | + +The table below lists the length of `sizeof` and `print` in ILP32 and LP64 to show the differences between constants and types. + +| Type | ILP32 sizeof | ILP32 print | LP64 sizeof | LP64 print | Remarks| +| ------------------ | ------------ | ----------- | ----------- | ---------- | ------ | +| bool | 1 | %u | 1 | %u | C++ | +| char | 1 | %d or %c| 1 | %d or %c| | +| unsigned char | 1 | %u | 1 | %u | | +| short | 2 | %d | 2 | %d | | +| unsigned short | 2 | %u | 2 | %u | | +| int | 4 | %d | 4 | %d | | +| unsigned int | 4 | %u | 4 | %u | | +| long | 4 | %ld | **8** | %ld | Differences exist.| +| unsigned long | 4 | %lu | **8** | %lu | Differences exist.| +| long int | 4 | %ld | **8** | %ld | Differences exist.| +| unsigned long int | 4 | %lu | **8** | %lu | Differences exist.| +| long long | 8 | %lld | 8 | %lld | | +| unsigned long long | 8 | %llu | 8 | %llu | | +| type * | 4 | %p | **8** | %p | Differences exist.| +| pid_t | 4 | %d | 4 | %d | | +| socklen_t | 4 | %u | 4 | %u | | +| off_t | 4 | %zd | **8** | %zd | Differences exist.| +| time_t | 4 | %zd | 8 | %zd | Differences exist.| +| pthread_t | 4 | %zu | **8** | %zu | Differences exist.| +| size_t | 4 | %zu | 8 | %zu | Differences exist.| +| ssize_t | 4 | %zd | **8** | %zd | Differences exist.| + +#### Differences in Data Structure Alignment + +##### Alignment of the data structure that contains a pointer + +```c +typedef struct tagFoo { + void *p; + uint32_t i; +} Foo; +``` + +On a 32-bit OS, the pointer length is 4, **Foo** is 4-byte aligned, and **sizeof(Foo)** is 8. On a 64-bit OS, the pointer length is 8, **Foo** is 8-byte aligned, and **sizeof(Foo)** is 16. + +##### Alignment of the data structure that contains a 64-bit integer + +```c +typedef struct tagFoo { + uint64_t p; + uint32_t i; +} Foo; +``` + +Although uint64\_t has a fixed length, **sizeof(Foo)** is different due to alignment. On a 32-bit OS, **Foo** is 4-byte aligned, and **sizeof(Foo)** is 12. On a 64-bit OS, **Foo** is 8-byte aligned, and **sizeof(Foo)** is 16. The preceding statement is also true when uint64\_t is replaced by double. + +### Conventions + +**Rule**: Conventions that must be complied with during programming. + +**Rec**: Conventions that should be complied with during programming. + +## Coding Guide + +### General Principles + +#### [Rule] Follow this coding guide to write code that is applicable to both 32- and 64-bit OSs. + +[Description] OpenHarmony will run in both 32- and 64-bit environments for a long time. To ensure code consistency, you must consider code portability during coding. + +### Data Type Definition and Formatting + +#### [Rule] Use the defined data types to define variables, and avoid custom basic data types without special meanings or requirements. + +[Description] Data types with variable lengths may cause incompatibility issues on 32- and 64-bit OSs. Unified and clear data types are required. OpenHarmony defines the following primitive data types: + +| Type| ILP32 | LP64 | Print| Use Case| +| ---------------- | ----- | ----- | ------- | ------------------------------------------------------------ | +| void | - | - | - | Used only for placeholder and general pointer definition.| +| char | 1 | 1 | %c | Used for strings and arrays.| +| int8_t | 1 | 1 | %d | Used for 1-byte integers.| +| uint8_t | 1 | 1 | %u | Used for 1-byte integers.| +| int16_t | 2 | 2 | %d | Used to replace short.| +| uint16_t | 2 | 2 | %u | Used to replace unsigned short.| +| int32_t | 4 | 4 | %d | Used to replace int.| +| uint32_t | 4 | 4 | %u | Used to replace unsigned int.| +| int64_t | 8 | 8 | %PRId64 | Used to replace long long and macros.| +| uint64_t | 8 | 8 | %PRIu64 | Used to replace unsigned long long and macros.| +| float | 4 | 4 | %f | Used for single-precision floating point numbers.| +| double | 8 | 8 | %lf | Used for double-precision floating point numbers.| +| bool | 1 | 1 | %d | Used for Boolean.| +| uintptr_t | **4** | **8** | %zu | Used for pointer storage. Different lengths are defined for 32- and 64-bit OSs.| +| type * | **4** | **8** | %p | Variable-length type. It is equivalent to uintptr_t, which is recommended for type conversion.| +| nullptr_t | **4** | **8** | %p | Used for pointer initialization.| +| pid_t | 4 | 4 | %d | Built-in for the Linux kernel. It has a fixed length.| +| socklen_t | 4 | 4 | %u | Built-in for the Linux kernel. It has a fixed length.| +| off_t/time_t | **4** | **8** | %zd | Signed, variable-length type.| +| size_t/pthread_t | **4** | **8** | %zu | Unsigned, variable-length type. It is used only for compatibility of calling library functions (for example, size_t is used in an underlying API).| + +The preceding types are defined in the **stddef.h** (C) and **cstdint** (C++) standard libraries. When `#define` is used to redefine related types, the source must be one of these types. + +Do not use non-standard types unless otherwise specified. Do not define common basic types unless they have special meanings. For primitive data types used in third-party interfaces and API calling, refer to their respective rules. + +[Example] Do not customize primitive data types unless necessary. + +```c +// Do not use the following code to redefine a data type. +typedef unsigned int UINT32;// This definition is forbidden. + +// The preceding definition can be replaced by uint32_t. However, you can define a type that has a specific meaning. +typedef uint32_t DB_TABLE_ID; // This definition can be retained. +``` + +[Example] Do not use the following two types, because their lengths are different from the common sense. + +| Type| ILP32 | LP64 | PRINT | Use Case| +| -------- | ------ | ----- | ----- | ---------------------- | +| float_t | **12** | **4** | - | Improper length. Do not use it.| +| double_t | **12** | **8** | - | Improper length. Do not use it.| + +#### [Rec] Do not use custom variable-length variables. A clear description is required if they are used to adapt to platforms or third-party interfaces. + +[Description] The native types such as long, int, short, and size_t have different lengths in the 32- and 64-bit environments. This may cause code risks. If these types are used for external storage or communication, system incompatibility may occur. Therefore, do not use them unless otherwise specified. + +[Exception] Due to platform, third-party interface, or library function reasons, they can be used with a clear description. + +[Example] + +```c +long var; +// This data type is 4-byte long on a 32-bit OS and 8-byte long on a 64-bit OS. You are advised to use uint32_t or uint64_t instead. +``` + +#### [Rule] Do not use uchar to define variables. + +[Description] It is not standard to use uchar or unsigned char to define strings. Instead, use char for strings or uint8_t for unsigned integers. + +For non-ANSI character sequences involving 8-bit encoding, char is recommended. In C++, wchar can be used. + +#### [Rule] Define an integer variable that is used to store a pointer as uintptr_t. + +[Description] The uintptr_t type is used to store data of the pointer length. The length can be automatically adjusted in the 32- and 64-bits environments. + +[Example] + +```c +uintptr_t sessionPtr; + +// When the pointer is stored as a variable, both the forced type conversion and left value should be defined as uintptr_t to adapt to the length changes in different scenarios. +sessionPtr = (uintptr_t) GetMemAddress(); +``` + +#### [Rec] When the type defined by the input parameter or return value of a function does not match the variable type, exercise caution to ensure that the result is correct after conversion following the value assignment and type conversion rules. + +[Description] If type inconsistency is inevitable, convert the type with caution to ensure that the final result meets the application requirements. + +[Example] + +```c +long function (long l); +int main () { + int i = -2; + unsigned int k = 1U; + long n = function(i + k); +} +``` + +Note: The preceding code will fail to be executed on a 64-bit OS because the expression (i + k) is an unsigned 32-bit expression. When it is converted to the long type, the symbols are not extended. The result of the input parameter is incorrect. The solution is to forcibly convert one of the operands to a 64-bit type. + +#### [Rule] Use 64-bit compatible macros, such as %PRId64, %PRIu64, and %PRIx64, to print 64-bit integers. Incompatible macros, such as %d, %ld, %zd, %x, and %lx, are not allowed. + +[Description] If the data to be formatted is of the 64-bit type (defined as uint64_t), format the output as follows: + +```c +#include +#include +#include + +int main() +{ + uint64_t a = 0x1234567fffffff; + printf("a = %"PRIx64"\n", a); + return 0; +} +``` + +The preceding code can output 64-bit numbers in both 32- and 64-bit environments. If other formatting methods are used, compatibility issues may occur, as listed in the following table. + +| Formatting Method| ILP32 Build| ILP32 Result| LP64 Build| LP64 Result| Conclusion| +| ---------- | -------------- | --------- | -------------- | -------- | ---------- | +| %lx | Type mismatch alarm| Incorrect| No alarm| Correct| Incompatible| +| %zx | Type mismatch alarm| Incorrect| No alarm| Correct| Incompatible| +| %llx | No alarm| Correct| Type mismatch alarm| Correct| Incompatible| +| %p | Type mismatch alarm| Incorrect| Type mismatch alarm| Correct| Incompatible| +| %PRIx64 | No alarm| Correct| No alarm| Correct| Compatible| + +[Example]The following is an example of the type mismatch alarm information: + +```bash +# Build on a 32-bit OS +format '%lx' expects argument of type 'long unsigned int', but argument 2 has type 'uint64_t {aka long long unsigned int}' +format '%zx' expects argument of type 'size_t', but argument 2 has type 'uint64_t {aka long long unsigned int}' +format '%p' expects argument of type 'void *', but argument 2 has type 'uint64_t {aka long long unsigned int}' + +# Build on a 64-bit OS +format '%llx' expects argument of type 'long long unsigned int', but argument 2 has type 'uint64_t {aka long unsigned int}' +format '%p' expects argument of type 'void *', but argument 2 has type 'uint64_t {aka long unsigned int}' +``` + +#### [Rule] When printing type-variable data, consider the data length and reserve sufficient space during alignment. + +[Description] On a 32-bit OS, the maximum length of the pointer and size_t is 8 bits (hexadecimal) or 10 bits (decimal). On a 64-bit OS, their maximum length is 20 bits. Therefore, you need to consider the length range when printing the data. + +#### [Rule] Do not use L/UL as the suffix of constants. You can add the suffix U to indicate the unsigned int type and the suffix LL/ULL to indicate the 64-bit length. + +[Description] By default, constants without suffixes are of the int type. When L/UL is used as the suffix, the length may change on 32- and 64-bit OSs. Therefore, use LL/ULL as the suffix to ensure that the length is fixed at 64 bits in both the 32- and 64-bit environments. + +| Constant| ILP32 | LP64 | Scenario| +| -------------- | --------- | ----- | ------------------------------------------------------------ | +| 1 | 4 | 4 | The default type is int32_t, and the length is fixed.| +| 1U | 4 | 4 | The default type is uint32_t, and the length is fixed.| +| 1L | **4** | **8** | The suffix is L. The length is not fixed. Do not use this constant.| +| 1UL | **4** | **8** | The suffix is UL. The length is not fixed. Do not use this constant.| +| 1LL | 8 | 8 | The default type is int64_t. The value is a long integer, and the length is fixed at 64 bits.| +| 1ULL | 8 | 8 | The type is uint64_t, and the value is an unsigned long integer.| +| 0x7FFFFFFF | 4 | 4 | The value is an unsigned number. It can be used within the value range of int32\_t. The default type is int32\_t. | +| 0x7FFFFFFFL | **4** | **8** | The length is not fixed. Do not use this constant.| +| 0x7FFFFFFFLL | 8 | 8 | The length is fixed.| +| 0x80000000 | 4 | 4 | It can be used within the value range of uint32\_t. The type is uint32\_t.| +| 0x80000000L | **4** | **8** | The suffix is L. It can be used within the value range of uint32\_t. This constant is meaningless. Do not use it.| +| 0x80000000LL | 8 | 8 | The suffix is LL. It can be used within the value range of uint32\_t. The length is fixed.| +| 0x8000000000 | **NA or 8**| **8** | No prefix. It can be used when the value range of uint32\_t is exceeded. The compiler uses LL by default or considers the value invalid. On a 64-bit OS, the type is fixed at uint64\_t.| +| 0x8000000000L | **NA or 8**| **8** | The suffix is L. It can be used when the value range of uint32_t is exceeded. This constant is meaningless. Do not use it.| +| 0x8000000000LL | 8 | 8 | The suffix is LL. The type is uint64_t.| + +As shown in the preceding table, a constant with the L or UL suffix has different lengths in the 32- and 64-bit environments. This hinders code portability. Therefore, do not use the L or UL suffix. + +[Example] + +```c +// UL in the following definition is meaningless. It causes an error on a 32-bit OS and is unnecessary on a 64-bit OS. +#define YYY_START_ADDRESS(XXX_START_ADDR + 0x80000000UL) +``` + +#### [Rule] Use macro constants defined in the standard header file. + +[Description] The standard header files **stdint.h** (C) and **cstdint.h** (C++) contain macro constants with the maximum and minimum values. Reference these macro constants, rather than customizing new ones. + +[Example] + +```c +#include +#include + +int main() +{ + std::printf("%zu\n", sizeof(std::int64_t)); + std::printf("%s\n", PRId64); + std::printf("%+" PRId64 "\n", INT64_MIN); + std::printf("%+" PRId64 "\n", INT64_MAX); + + std::int64_t n = 7; + std::printf("%+" PRId64 "\n", n); +} +``` + +#### [Rule] Use unified definitions instead of all Fs to indicate invalid values of constants. + +[Description] The same numeric constant value may be understood differently on 32- and 64-bit OSs, since the 32-bit OS has the signed and unsigned types. Especially, if the most significant bit is 1, this bit is considered as a negative number on a 32-bit OS based on the signed type and a positive number on a 64-bit OS. Use the definitions in **typedef.h** to indicate invalid values. + +```c +// Use the definitions in typedef.h. +#define INVALID_INT8((int8_t)(-1)) +#define INVALID_UINT8((uint8_t)(-1)) +#define INVALID_INT16((int16_t)(-1)) +#define INVALID_UINT16((uint16_t)(-1)) +#define INVALID_INT32((int32_t)(-1)) +#define INVALID_UINT32((uint32_t)(-1)) +#define INVALID_INT64((int64_t)(-1)) +#define INVALID_UINT64((uint64_t)(-1)) +``` + +[Example] + +```c +// On a 32-bit OS, n is a negative number. +long n = 0xFFFFFFFF; +// On a 64-bit OS, n is a positive number. The actual value is 0x00000000FFFFFFFF. +long n = 0xFFFFFFFF; +``` + +#### [Rec] Use uint32_t to define temporary variables whose size does not exceed 32 bits. + +[Description] You do not need to pay special attention to the type of a variable. Use the default uint32_t type to minimize forced type conversions caused by type inconsistency. + +### Structure Alignment and Padding + +#### [Rule] Do not hardcode a constant to specify the variable length and structure length. Use built-in types such as **sizeof** to obtain the variable length and structure length. + +[Description] **sizeof** automatically calculates the variable length and structure length, which might be incorrect if hardcoded. In addition, the running performance will not be adversely affected since the variable length is calculated during build. + +On a 64-bit OS, 8-byte alignment is used by default. Using **sizeof()** to obtain the structure length can avoid length calculation errors caused by structure alignment. + +Pay attention to the length differences on 32- and 64-bit OSs to avoid length calculation errors. Calculate and apply for space based on the maximum length. + +[Example] **sizeof** is not used to calculate the structure length, causing insufficient memory space. + +```c +int32_t *p; +p = (int32_t *)malloc(4 * ELEMENTS_NUMBER); +// This code assumes that the pointer length is 4 bytes. However, in LP64, the pointer length is 8 bytes. + +// The correct method is to use sizeof(). +int32_t *p; +p = (int32_t *)malloc(sizeof(p) * ELEMENTS_NUMBER); +``` + +#### [Rec] In special cases, force the compiler to use a specific alignment mode on the 64-bit OS. + +[Description] If necessary, you can use the specified alignment mode to ensure code compatibility. If the pseudo-instruction **#pragma pack (n)** is used, the compiler aligns data by n bytes. If the pseudo-instruction **#pragma pack ()** is used, the compiler cancels the custom byte alignment mode. + +[Example] + +```c +#pragma pack(push) # Save the current alignment mode. +#pragma pack(1) # Set the alignment mode to 1-byte alignment. +struct test +{ + ...... +}; +#pragma pack(pop) # Restore the previous alignment mode. +``` + +#### [Rule] Uniform the message structures related to multi-device communication. For compatibility purposes, 1-byte alignment is preferred. Do not use 8-byte alignment or 64-bit data types to avoid errors during communication with a 32-bit OS. + +Note: Inter-board communication messages involve inter-board operations. The communication fails unless all software is upgraded synchronously. For the sake of compatibility, use 1-byte alignment for the existing protocols and structures and convert them into the network byte order. For new communication protocols, use 4-byte alignment for higher communication efficiency and processing performance. + +#### [Rule] Avoid structure padding for external APIs and use at least 4-byte alignment. + +[Description] If structure definitions are included in an API header file provided externally, do not pad the structures. It is recommended that natural alignment be used to avoid data holes. Use at least 4-byte alignment. + +#### [Rec] Use member names to access structure members. Do not use the offset mode. + +[Description] The offsets of data structure members are different in the 32- and 64-bit environments. Therefore, the size of each member cannot be used as the offset. A 32-bit OS does not have structures automatically padded. However, on a 64-bit OS, automatic padding may occur. + +[Example] + +```c +Struct A +{ + uint32_t a; + uint32_t *p; + uint32_t b; +}; +``` + +The offset of member b is equal to sizeof(a) + sizeof(p) on a 32-bit OS. This is not true on a 64-bit OS. The correct method is to locate the index based on the variable name. + +```c +xxx.b = 123; +``` + +If the structure definition is special, for example, if the structure is only the message header and there are other fields, then you can redefine the structure so that it does not include padding fields. + +[Example] + +```c +typedef struct { + uint32_t self; /* Structure used for alignment. */ + uint32_t brother; /* Structure used for alignment. */ + uint8_t processedFlag; /* Flag indicating whether the current node has been processed. */ + uint8_t reserve[3]; /* Reserved for 4-byte alignment. */ +} TreeNodeInfo; + +typedef struct { + TreeNodeInfo nodeInfo; /* Tree information data structure of each node */ + void *userInfo; /* User information data structure of each node */ +} TreeNode; +``` + +The **TreeNode** structure has two member structures. In the following code, the address of the first member is the initial address of the second member minus the value of sizeof (the first member). (**inUserInfo** points to the **userInfo** field in the structure.) + +```c +inTreeNodeInfo = (TreeNodeInfo *)((void *)(((char *)inUserInfo) - sizeof(TreeNodeInfo))); +``` + +The structure adopts natural alignment. Note that the length of the substructure **TreeNodeInfo** is 12 bytes on both 32- and 64-bit OSs. On a 32-bit OS, there is no padding between member structures of the **TreeNode** structure, and the structure length is 16 bytes. On a 64-bit OS, **sizeof(TreeNodeInfo)** is 12 and **sizeof(TreeNode)** is 24, which means that there is a 4-byte padding field after the substructure **TreeNodeInfo**. Therefore, when the preceding method is used to obtain the address of the previous field on a 64-bit OS, the 4-byte padding field is not calculated, causing a member access error. + +#### [Rec] When defining a structure, implement 8-byte natural alignment to save storage space and avoid padding on the premise that readability is ensured. + +[Description] If a structure can be naturally aligned, no padding is required, which effectively reduces the invalid space of the structure. You are advised to define 64-bit data types such as size_t and pointer at both ends of the structure without affecting readability. + +[Example] + +```c +// The length of the following structure is 24 bytes in natural alignment mode. +struct Foo +{ + int32_t a; + uint64_t l; + int32_t x; +} + +// After proper adjustment, the size can be reduced to 16 bytes. +struct Foo +{ + uint64_t l; + int32_t a; + int32_t x; +} +``` + +### Data Type Conversion and Calculation + +#### [Rule] Avoid implicit type conversion between different data types. If necessary, use explicit type conversion to avoid result inconsistency between the 32- and 64-bit environments. + +[Description] Exercise caution when performing operations between operands with different lengths and precisions. Pay attention to the following about implicit type conversion: + +1. When the value of a 64-bit variable is assigned to a 32-bit variable, the values of the least significant 32 bits are directly assigned, and the values of the most significant 32 bits are ignored. Then the least significant 32 bits are treated as signed or unsigned based on the left value variable type. + +2. When the value of a 32-bit variable is assigned to a 64-bit variable, sign extension is performed based on whether the 32-bit variable is signed or unsigned, and then the 64-bit variable is treated as signed or unsigned based on the variable type. + +3. For operations of signed and unsigned numbers, if the result type is not specified, the result is treated as unsigned by default. + +The preceding conversion process may cause unexpected results. Therefore, exercise caution to avoid implicit type conversion as much as possible. + +[Example] Example of the correct conversion result + +```c +int32_t t1 = -2; +int64_t t2 = 1; +int32_t t3 = t1 + t2; +printf("t3 = %d\n", t3); + +// Printed: t3 = -1 +``` + +t1 is a 32-bit number, and t2 is a 64-bit number. Before the calculation, t1 is extended to 64 bits. After the calculation, the result is a 64-bit int64_t type. The hexadecimal value stored in the memory is 0xffffffffffffffff. During the value assignment, the value is truncated into 0xffffffff. Then, the value is treated as signed, which is -1. Although the result is correct, data truncation occurs. This may not be the author's intention. + +[Example] Conversion from signed to unsigned + +```c +int64_t t1 = -1; +uint32_t t2 = t1; +printf("t2=%u", t2); + +// Printed: t2=4294967295 +``` + +t1 is a 64-bit int64_t type, which is 0xffffffffffffffff in binary mode. When this value is assigned to a 32-bit int type, the most significant 32 bits are ignored and the least significant 32 bits are displayed. The binary value is 0xffffffff, which is 4294967295 in unsigned mode. + +[Example] Conversion from 32-bit to unsigned 64-bit + +```c +int32_t t1 = -1; +uint64_t t2 = t1; +printf("t2 = %lu\n", t2); + +// Printed: t2 = 18446744073709551615 +``` + +t1 is a signed negative 32-bit number, which must be extended with signs. The most significant bits of the negative number are all fs, and the value after extension is 0xffffffffffffffff. t2 is an unsigned 64-bit number, the value of which is a large positive number. + +#### [Rule] When a pointer is used as the base address and the offset is calculated by byte, the pointer must be forcibly converted to a single-byte pointer such as uintptr_t or uint8_t *. + +[Description] If the pointer is converted to an integer of the uint32_t type, the pointer may be truncated. This will not occur if the pointer is converted to uintptr_t. The pointer can also be converted to a single-byte pointer such as uint8_t * and char *. In this case, the offset is considered as bytes. A one-byte offset will be carried out for the void * type. To clarify the type, you are advised to use the type that is more specific. + +[Example] + +```c +// Incorrect +void *pPkt = (void *)((uint32_t)MSG_GET_DATA_ADDR(msgAddr) + OFFSET); + +// Correct +void *pPkt = (void *)((uintptr_t)MSG_GET_DATA_ADDR(msgAddr) + OFFSET);// C +void *pPkt = reinterpret_cast(reinterpret_cast(MSG_GET_DATA_ADDR(msgAddr)) + OFFSET); // C++ +``` + +#### [Rule] Mutual assignment is forbidden between pointers and uint32_t, including function parameter passing. + +[Description] If the variable to be defined is a length-variable pointer, use void *. If the variable to be defined is a pointer or an integer, use uintptr_t. + +[Example] Conversion between pointers and integers + +```c +int32_t i, *p, *q; +p = &i; +q = (int32_t *) (int32_t)&i; + +// In ARM Cortex-A32, p = q; in A64-LP64, p != q +``` + +To avoid this type conflict, use uintptr_t to indicate the pointer type. + +#### [Rule] Mutual assignment is forbidden between size_t and int32_t/uint32_t, including function parameter passing. + +[Description] The variable-length type cannot be forcibly converted to the 32-bit type. + +[Example] + +```c +int32_t length = (int32_t)strlen(str); // Incorrect +``` + +strlen returns size_t (unsigned long in LP64). When the value is assigned to int32_t, truncation is inevitable. Generally, truncation occurs only when the length of **str** is greater than 2 GB. This is rare in programs. + +#### [Rule] When a large array or large `for` loop index is used on a 64-bit OS, the index type must be consistent with the subscript boundary. + +[Description] If a large array or large loop is used on a 64-bit OS, the index range may exceed 32 bits. In this case, the variable-length type or 64-bit type must be used to define the array subscript or loop variable to prevent full traversal failures caused by an incorrect variable range. + +[Example] + +```c +int64_t count = BIG_NUMBER; +for (unsigned int index = 0; index != count; index++) + ... +``` + +On a 64-bit OS, int64_t is a 64-bit type, and count is a large number. unsigned int is a 32-bit type. As a result, the loop never ends. Therefore, the index type should be changed to int64_t. + +### Bit Field and Byte Order + +#### [Rule] When defining variables based on bit fields, fully consider the basic types and alignment of bit fields to avoid calculation errors in different bit widths. + +[Description] Consider both the width of a bit field and alignment. The structure length is different in different environments. Use the name rather than direct calculation result for the value of a bit field. + +#### [Rule] On a 64-bit OS, consider the length difference caused by the shift operation and the problem that the value generated after shift is implicitly extended to 64 bits. + +[Description] During the shift operation, check whether overflow and rewind occur. Change the data type to 32-bit to avoid result inconsistency. + +[Example] + +```c +int64_t t = 1 << a; // Consider the size of a. +``` + +The maximum value of a is 32 on a 32-bit OS and 64 on a 64-bit OS. If a is a 32-bit variable, the extension to 64 bits must also be considered. + +### Third-Party Libraries and Differentiated Features + +#### [Rule] The third-party class libraries used by a 64-bit OS must support 64-bit. + +[Description] Some library functions and third-party open-source code may not fully support 64-bit. You must evaluate all involved code to ensure that it can run in the 64-bit environment. Some library functions are implemented using different APIs in the 32- and 64-bit environments. Ensure that correct APIs are used. + +[Example] In the 32-bit environment, **mmap** can be used. If the size of the memory to map exceeds 2 GB, **mmap64** is required. In the 64-bit environment, **mmap** is used. + +#### [Rule] Functionalities involving bottom-layer assembly must be debugged separately on the 32- and 64-bit OSs. + +[Description] The number and bit width of registers are different in the 32- and 64-bit environments. The debugging functionalities related to assembly must be adjusted. You must also pay attention to the code validity in the 32-bit and 64-bit environments. + +[Example] For the push-to-stack functionality of the call stack, you must write and debug the assembly code in the 32- and 64-bit environment separately. + +#### [Rule] The patch functionality must support both 32- and 64-bit instructions. + +[Description] The patch mechanism and functionalities must be adopted to the command length changes. + +#### [Rule] All tools used on a 64-bit OS must support 64-bit. + +[Description] If type inconsistency is inevitable, convert the type with caution to ensure that the final result meets the application requirements. diff --git a/en/contribute/OpenHarmony-Java-secure-coding-guide.md b/en/contribute/OpenHarmony-Java-secure-coding-guide.md index 79a5726cc1192f3faf495e7fcfa3e6f75781df39..f61c28892897c2f5a66ac2762755c78ed6433af5 100644 --- a/en/contribute/OpenHarmony-Java-secure-coding-guide.md +++ b/en/contribute/OpenHarmony-Java-secure-coding-guide.md @@ -1,4 +1,4 @@ -# OpenHarmony Java Secure Coding Guide +# Java Secure Coding Guide This document provides secure coding suggestions for Java-based development. @@ -1786,7 +1786,7 @@ public void xsltTrans(String src, String dst, String xslt) { } ``` -A security policy can be added to **TransformerFactory**. Java has a built-in blocklist for XSLT. Here some [insecure methods are disabled by setting **http://javax.xml.XMLConstants/feature/secure-processing** to **true**.](http://javax.xml.xmlconstants/feature/secure-processing属性设置为true开启防护,可以禁用一些不安全的方法。) +A security policy can be added to **TransformerFactory**. Java has a built-in blocklist for XSLT. Here some insecure methods are disabled by setting **http://javax.xml.XMLConstants/feature/secure-processing** to **true**. ## Try best to simplify the regular expression (regex) to prevent regular expression denial of service (ReDoS) attacks diff --git a/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md b/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md index 621953b338c8ca14c1e71d1a670788a544ab22aa..e5bcc1db9120dc9bc29ba91bd6b9e5d7a8f4ec08 100644 --- a/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md +++ b/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md @@ -1,4 +1,4 @@ -# OpenHarmony C&C++ Secure Coding Guide +# C&C++ Secure Coding Guide This document provides some secure coding suggestions based on the C\&C++ language to guide development. diff --git a/en/contribute/OpenHarmony-hdf-coding-guide.md b/en/contribute/OpenHarmony-hdf-coding-guide.md new file mode 100644 index 0000000000000000000000000000000000000000..b28b7591c6467b04927d06d53d276e1f69f3b00f --- /dev/null +++ b/en/contribute/OpenHarmony-hdf-coding-guide.md @@ -0,0 +1,635 @@ +# HDF Driver Coding Guide + +## About This Document + +### Purpose + +OpenHarmony aims to build an open, distributed OS framework for smart IoT devices in the full-scenario, full-connectivity, and full-intelligence era. It has the following technical features: hardware collaboration for resource sharing, one-time development for multi-device deployment, and a unified OS for flexible deployment. + +The Hardware Driver Foundation (HDF) provides the following driver framework capabilities: driver loading, driver service management, and driver message mechanism. This unified driver architecture system is designed to provide a more precise and efficient development environment, where you can perform one-time driver development for multi-system deployment. + +As such, certain coding specifications are required for the OpenHarmony driver implemented based on the HDF. This document stipulates the specifications on the driver code, helping you improve code standardization and portability. + +## Coding Guide + +### General Principles + +#### [Rule] Use the capabilities provided by the HDF to implement drivers. + +[Description] The HDF supports driver loading, driver service management, and driver message mechanism. It provides the Operating System Abstraction Layer (OSAL) and Platform Abstraction Layer (PAL) to support cross-system and cross-platform driver deployment. It also provides capabilities such as driver model abstraction, common tools, and peripheral component framework. You should develop drivers based on these capabilities to ensure that the drivers can be deployed on various devices powered by OpenHarmony. + +#### [Rule] Follow this coding guide to develop drivers that can run in both the kernel space and user space. + +[Description] Kernel-mode drivers are different from user-mode drivers in essence. They apply to different use cases. You must follow this guide during service design and development and use the HDF OSAL and PAL to shield the differences, so as to ensure that the drivers can run in both the kernel space and user space. + +#### [Rec] Include the drivers/framework/include directory instead of a subdirectory in the build script. + +[Description] The **drivers/framework/include** directory is the root directory of the header file exposed by the HDF externally. This directory contains multiple subdirectories to represent different modules such as the core framework, OSAL, and PAL. When using a header file, you are advised to include the **drivers/framework/include** directory in the build script. This avoids repeated inclusion when the script is referenced in the code. + +[Example] + +```gn +config("xxxx_private_config") { + include_dirs = [ + "//drivers/framework/include", + "//drivers/framework/include/core", # Not recommended. + ] +} +``` + +```c +#include +#include // Not recommended. +``` + +### HDF Core Framework + +#### [Rule] Implement the Bind, Init, and Release methods based on the responsibility definitions in the HdfDriverEntry object. + +[Description] The **HdfDriverEntry** object is the entry of an HDF driver. The **Bind**, **Init**, and **Release** methods have their own responsibilities. You must implement the corresponding functions based on the responsibilities. + +```c +struct HdfDriverEntry g_sampleDriverEntry = { + .moduleVersion = 1, + .moduleName = "sample_driver", + .Bind = SampleDriverBind, // Responsibility: Bind the service interface provided by the driver to the HDF. + .Init = SampleDriverInit, // Responsibility: Initialize the driver service. + .Release = SampleDriverRelease, // Responsibility: Release driver resources. It is invoked when an exception occurs. +}; + +HDF_INIT(g_sampleDriverEntry); +``` + +#### [Rule] The first member in the driver service structure must be of the IDeviceIoService type. + +[Description] The first member of the service interface defined by the driver must be of the **IDeviceIoService** type. + +[Example] + +```c +struct ISampleDriverService { + struct IDeviceIoService ioService; // The first member must be of the IDeviceIoService type. + int32_t (*FunctionA)(void); // The first service interface of the driver. + int32_t (*FunctionB)(uint32_t inputCode); // The second service interface of the driver. More service interfaces can be added here. +}; +``` + +[Example] + +```c +struct ISampleDriverService { + struct IDeviceIoService ioService; // The first member must be of the IDeviceIoService type. + void *instance; // A service instance can be encapsulated here to provide service interfaces. +}; +``` + +#### [Rule] All driver service interfaces must be bound using the Bind method of the HdfDriverEntry object. All service interfaces must be defined. They cannot be defined as null. + +[Description] The service interfaces defined by the driver are exposed externally. If a service interface is not defined or is defined as null, exceptions may occur during external invocation. + +[Example] + +```c +int32_t SampleDriverBind(struct HdfDeviceObject *deviceObject) +{ + static struct ISampleDriverService sampleDriver = { + .FunctionA = SampleDriverServiceA, + .FunctionB = NULL, // The service interface cannot be defined as null. + }; + // Bind ioService to the device object created by the HDF. + deviceObject->service = &sampleDriver.ioService; + return HDF_SUCCESS; +} +``` + +#### [Rec] Call the HdfDeviceSetClass interface in the Init method of the HdfDriverEntry object to define the driver type. + +[Description] Based on the driver type, you can classify the drivers of the current device and query the driver capabilities of the current device. For better driver management, you are advised to call **HdfDeviceSetClass** to set the driver type. + +[Example] + +```c +int32_t SampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + // Set the driver type to DISPLAY. + if (!HdfDeviceSetClass(deviceObject, DEVICE_CLASS_DISPLAY)) { + HDF_LOGE("HdfDeviceSetClass failed"); + return HDF_FAILURE; + } + return HDF_SUCCESS; +} +``` + +### HCS + +HDF Configuration Source (HCS) describes the configuration source code of the HDF in the form of key-value pairs. It decouples configuration code from driver code, making it easy for you to manage the driver configuration. + +The driver configuration consists of the driver device description defined by the HDF and the private configuration of a driver. + +**Driver Device Description** + +The driver loading information required by the HDF comes from the driver device description. Therefore, you must add the driver device description to the **device_info.hcs** file defined by the HDF. + +#### [Rule] Before configuring a driver, determine the hardware to which the driver belongs and the deployment mode, and plan the directories and files to be configured. + +[Description] In the **vendor** directory of the OpenHarmony source code, plan the directories based on the chip vendor, development board, and configuration. The HDF driver configuration is stored in the **hdf\_config** directory. According to the hardware specifications, the **hdf\_config** directory stores kernel-mode configuration information or both kernel- and user-mode configuration information. You should determine the directory where the driver is to be configured based on the driver hardware and deployment mode. + +[Example] + +```bash +$openharmony_src_root/vendor/hisilicon/hispark_taurus/hdf_config # Directory for storing the kernel-mode configuration file. There are no user-mode configuration files. + +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf # Directory for storing the kernel-mode configuration file. +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/uhdf # Directory for storing the user-mode configuration file. +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf/device_info/device_info.hcs # Device description file of the kernel-mode driver. +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf/lcd/lcd_config.hcs # Private configuration file of the kernel-mode driver. +``` + +#### [Rule] Use existing configuration information and inherit existing configuration templates during driver configuration. + +[Description] The **host**, **device**, and **deviceNode** templates have been configured in the **device_info.hcs** file. When configuring a driver, make full use of the existing configuration information and inherit HCS features to minimize your configuration workload. + +[Example] + +``` +root { + device_info { + match_attr = "hdf_manager"; + template host { // host template + hostName = ""; + priority = 100; // Host startup priority. The value ranges from 0 to 200. A larger value indicates a lower priority. The default value 100 is recommended. If the priorities are the same, the host loading sequence cannot be ensured. + template device { // device template + template deviceNode { // deviceNode template + policy = 0; // Policy for publishing drive services. + priority = 100; // Driver startup priority. The value ranges from 0 to 200. A larger value indicates a lower priority. The default value 100 is recommended. If the priorities are the same, the device loading sequence cannot be ensured. + preload = 0; // The driver is loaded as required. + permission = 0664; // Permission for the driver to create a device node. + moduleName = ""; + serviceName = ""; + deviceMatchAttr = ""; + } + } + } + // To use the default values in the template, the node fields can be not included. + sample_host :: host { // sample_host inherits the host template. + hostName = "host0"; // Host name. The host node is a container used to store a type of drivers. + device_sample :: device { // device_sample inherits the device template. + device0 :: deviceNode { // device0 inherits the deviceNode template. + policy = 1; // Overwrite the policy in the template. + moduleName = "sample_driver"; // Driver name. The value of this field must be the same as that of moduleName in the HdfDriverEntry structure. + serviceName = "sample_service"; // Service name of the driver, which must be unique. + deviceMatchAttr = "sample_config"; // Keyword for matching the private data of the driver. The value must be the same as that of match_attr in the private data configuration table of the driver. + } + } + } + } +} +``` + +#### [Rule] Use the defined types during driver model design and classification. Do not configure hosts and devices repeatedly. + +[Description] The HDF places the same type of devices in the same host. You can develop and deploy the driver functionalities of the host by layer, so that one driver has multiple nodes. The following figure shows the HDF driver model. + +![HDFDriverModel.png]( ../device-dev/driver/figures/HDFDriverModel.png) + +Place devices of the same type in the same host. When adding a device, check whether the host of the same type already exists. If such a host already exists, configure the device in the host. Do not configure the same host again. A device belongs to only one driver. Therefore, do not configure the same device in different hosts. + +#### [Rule] Set publication policies for driver services based on service rules. + +[Description] The driver service is the object of capabilities provided by the driver to external systems and is managed by the HDF in a unified manner. The HDF uses the **policy** field in the configuration file to define policies for drivers to publish services externally. The values and meanings of this field are as follows: + +```c +typedef enum { + /* The driver does not provide services.*/ + SERVICE_POLICY_NONE = 0, + /* The driver provides services for kernel-space applications. */ + SERVICE_POLICY_PUBLIC = 1, + /* The driver provides services for both kernel- and user-space applications. */ + SERVICE_POLICY_CAPACITY = 2, + /** Driver services are not published externally but can be subscribed to. */ + SERVICE_POLICY_FRIENDLY = 3, + /* Driver services are not published externally and cannot be subscribed to. */ + SERVICE_POLICY_PRIVATE = 4, + /** Invalid policy. */ + SERVICE_POLICY_INVALID +} ServicePolicy; +``` + +You must set the policies based on service rules. Do not set unnecessary policies, for example, setting user-mode publication policies for kernel-mode drivers. + +[Example] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + policy = 1; // The driver provides services for kernel-space applications. + ... + } + } + } + } +} +``` + +#### [Rule] The permission to create device nodes for a driver must match the publication policy of the driver. + +[Description] In the **device_info.hcs** file, the **permission** field specifies the permission used by the driver to create a device node. This field is a 4-digit octal number and uses the Unix file permissions, for example, 0644. This field takes effect only when the driver provides services for user-space applications (policy = 2). + +You must ensure that the publication policy of the driver service matches the device node permission. Otherwise, access to the driver service may fail or the permission of the device node may be inappropriate. + +[Example] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + policy = 2; // The driver provides services for both kernel- and user-space applications. + permission = 0640; // Recommended value + ... + } + } + } + } +} +``` + +[Counterexample] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + policy = 2; // The driver provides services for both kernel- and user-space applications. + permission = 0777; // Excessive permission. + ... + } + } + } + } +} +``` + +[Counterexample] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + policy = 1; // The driver provides services for kernel-space applications but does not create a device node. + permission = 0640; // Redundancy configuration + ... + } + } + } + } +} +``` + +#### [Rule] Configure whether to load a driver as required based on service requirements. + +[Description] In the **device_info.hcs**, **preload** specifies the driver loading mode. The values and meanings of this field are as follows: + +```c +typedef enum { + /* The driver is loaded by default during the system boot process. */ + DEVICE_PRELOAD_ENABLE = 0, + /* The driver is loaded after a quick start is complete if the system supports quick start. If the system does not support quick start, this value has the same meaning as DEVICE\_PRELOAD\_ENABLE. */ + DEVICE_PRELOAD_ENABLE_STEP2, + /* The driver is not loaded during the system boot process. When a user-mode process requests the driver service, the HDF attempts to dynamically load the driver if the driver service does not exist. */ + DEVICE_PRELOAD_DISABLE, + /** Invalid value. */ + DEVICE_PRELOAD_INVALID +} DevicePreload; +``` + +Set the **preload** field based on the service requirements. + +[Example] + +``` +root { + device_info { + sample_host { + sample_device { + device0 { + preload = 2; // The driver is loaded as required. + ... + } + } + } + } +} +``` + +#### [Rec] When the preload field is set to 0, configure the loading priority based on the service requirements. + +[Description] In the **device_info.hcs** file, the **priority** field indicates the host and driver loading priority. The value of this field is an integer ranging from 0 to 200. For drivers in different hosts, a smaller priority value of the host indicates a higher driver loading priority. For drivers in the same host, a smaller priority value of the driver indicates a higher driver loading priority. The default value of the **priority** field is 100. If this field is not set or set to the same value for different drivers, the driver loading sequence cannot be ensured. You should configure the **priority** field based on the service requirements to ensure the driver loading sequence. + +[Example] + +``` +root { + device_info { + sample_host0 { + priority = 100; + sample_device { + device0 { + preload = 0; // The driver is loaded by default. + priority = 100; // The HDF ensures that the driver is loaded before device1. + ... + } + device1 { + preload = 0; // The driver is loaded by default. + priority = 200; // The HDF ensures that the driver is loaded after device0. + ... + } + } + } + sample_host1 { + priority = 100; // The HDF does not ensure the loading sequence because this host has the same priority as sample_host0. + ... + } + } +} +``` + +**Private Configuration Information of the Driver** + +If a driver has private configurations, you can add a driver configuration file to fill in default configurations of the driver. When loading the driver, the HDF obtains the configuration information, saves it in the **property** field of **HdfDeviceObject**, and passes it to the driver through **Bind** and **Init**. + +#### [Rule] Store the private configuration files of the drivers in different directories according to the component type or module. + +[Description] You must properly plan the directory for storing private configuration files of drivers. Do not store them in the root directory. + +[Example] + +```bash +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf/sample/sample_config.hcs # Correct. The private configuration file is stored in the sample directory. + +$openharmony_src_root/vendor/hisilicon/Hi3516DV300/hdf_config/khdf/sample_config.hcs # Incorrect. The private configuration file is placed in the root directory. +``` + +#### [Rule] Add the private configuration file of a driver to the hdf.hcs file in the hdf_config directory. + +[Description] The **hdf.hcs** file summarizes the configuration information. The HDF parses the file content and loads the private configuration information of the driver to the device node during the build and runtime. Include the private configuration file of the driver in the **hdf.hcs** file to trigger driver initialization. + +[Example] + +```c +#include "device_info/device_info.hcs" +#include "sample/sample_config.hcs" // The file contains the private configuration file of a driver. + +root { + module = "hisilicon,hi35xx_chip"; +} +``` + +#### [Rule] The value of the matchAttr field in the private configuration file of the driver must be the same as that of the deviceMatchAttr field in device_info.hcs. + +[Description] The HDF associates with the driver device through the **match_attr** field. A mismatch causes a failure to obtain the private configuration information. + +[Example] + +``` +root { + sample_config { + ... + match_attr = "sample_config"; // The value of this field must be the same as that of deviceMatchAttr in device_info.hcs. + } +} +``` + +#### [Rule] Use underscores (_) in field names in the private configuration file. + +[Description] According to the naming rules in the C/C++ coding guide, use underscores (_) in field names in the private configuration file of a driver. In this way, the naming rule is satisfied during the definition of the private configuration data structure in the implementation code. It also makes unified management of the code and configuration files easier. + +[Example] + +``` +root { + sample_config { + sample_version = 1; // Use an underscore (_) in the field name. + sample_bus = "I2C_0"; + match_attr = "sample_config"; + } +} +``` + +### HCS Macros + +The private configuration information of a driver is loaded to **property** of **HdfDeviceObject**. This occupies memory space, which should be avoided for mini- and small-system devices. To minimize the memory usage, the HDF provides HCS macros to parse the private configuration information. + +#### [Rule] Use HCS macros to parse the private configuration information in memory-sensitive or cross-system scenario. + +[Description] You should specify the use cases of drivers. In memory-sensitive scenarios or if a driver needs to be used in mini-, small-, and standard-system devices, use HCS macros to parse the private configuration information for higher performance and portability. + +[Example] + +```c +#include + +#define SAMPLE_CONFIG_NODE HCS_NODE(HCS_ROOT, sample_config) + +ASSERT_EQ(HCS_PROP(SAMPLE_CONFIG_NODE, sampleVersion), 1); +ASSERT_EQ(HCS_PROP(SAMPLE_CONFIG_NODE, sample_bus), "I2C_0"); +ASSERT_EQ(HCS_PROP(SAMPLE_CONFIG_NODE, match_attr), "sample_config"); +``` + +### HDF Tools + +#### [Rule] Determine the communication scenario and HdfSbuf type. + +[Description] **HdfSbuf** is a data structure used for data transfer. This structure is classified into different types based on the communication scenario. These types are defined in the **hdf_sbuf.h** header file. + +```c +enum HdfSbufType { + SBUF_RAW = 0, /* SBUF used for communication between the user space and the kernel space. */ + SBUF_IPC, /* SBUF used for inter-process communication (IPC). */ + SBUF_IPC_HW, /* Reserved for extension. */ + SBUF_TYPE_MAX, /* Maximum value of the SBUF type. */ +}; +``` + +Determine whether the data transfer is IPC in the user space or between the user space and kernel space, and then create the corresponding **HdfSbuf** structure. + +[Example] + +```c +void SampleDispatchBetweenUserAndKernel() +{ + int32_t ret; + /* Communication between the user space and kernel space. */ + struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_RAW); + ... + ret = sample->dispatcher->Dispatch(&sample->object, CMD_SAMPLE_DISPATCH, data, NULL); + ... + HdfSBufRecycle(data); +} +``` + +[Example] + +```c++ +void SampleDispatchIpc() +{ + /* IPC */ + struct HdfSBuf *data = HdfSBufTypedObtain(SBUF_IPC); + ... + int ret = sample->dispatcher->Dispatch(sample, CMD_SAMPLE_DISPATCH, data, nullptr); + ... + HdfSBufRecycle(data); +} +``` + +#### [Rule] Define the HDF_LOG_TAG macro when using HDF logging. + +[Description] The HDF provides the **hdf_log.h** tool ,using which you can output driver run logs. The **HDF_LOG_TAG** macro specifies the log tag. You must define this macro before printing logs. + +[Example] + +```c +#include + +#define HDF_LOG_TAG sample_driver // Define the log tag. + +int32_t SampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + HDF_LOGI("sample driver is initialized"); // Use the tool to print logs. + return HDF_SUCCESS; +} +``` + +#### [Rule] Verify the return values of the HDF methods and use the error codes provided by the HDF. + +[Description] The HDF methods have specific return values. You should verify them rather than ignoring them. The return values correspond to error codes in the **hdf_base.h** header file. Use the error codes provided by the HDF when using the HDF or implementing custom methods. + +[Example] + +```c +int32_t SampleDriverInit(struct HdfDeviceObject *deviceObject) +{ + int32_t ret; + // Check whether the device type is successfully set. + if (!HdfDeviceSetClass(deviceObject, DEVICE_CLASS_DISPLAY)) { + HDF_LOGE("HdfDeviceSetClass failed"); + return HDF_FAILURE; + } + ret = InitDiver(); + // A custom method uses an error code provided by the HDF. + if (ret != HDF_SUCCESS) { + HDF_LOGE("init drvier is failed"); + return ret; + } + return HDF_SUCCESS; +} +``` + +### OSAL + +The HDF OSAL shields the interface differences between OpenHarmony subsystems and provides unified OS interfaces, including memory management, threads, mutexes, spin locks, semaphores, timers, files, IRQ, time, atoms, firmware, and I/O operation modules. + +#### [Rule] Use OS interfaces through the OSAL for drivers used across mini-, small-, and standard-system devices. + +[Description] The OSAL shields the differences between OS interfaces. You should operate these OS interfaces based on the OSAL to ensure that drivers can run on different types of systems. + +[Example] + +```c +#include +#include + +struct DevHandle *SampleInit(void) +{ + struct DevHandle *handle = (struct DevHandle *)OsalMemCalloc(sizeof(struct DevHandle)); + if (handle == NULL) { + HDF_LOGE("OsalMemCalloc handle failed"); + return NULL; + } + return handle; +} +``` + +[Example] + +```c +#include + +void SampleSleep(uint32_t timeMs) +{ + OsalMSleep(timeMs); +} +``` + +### PAL + +The HDF PAL abstracts platform drivers and provides unified operation interfaces for modules such as the GPIO, I2C, SPI, UART, RTC, SDIO, eMMC, DSI, PWM, and watchdog. + +#### [Rule] Use platform drivers across mini, small, and standard systems through the PAL. + +[Description] The PAL masks the differences between platform driver interfaces of different system types. You should operate these interfaces based on PAL to ensure that drivers can run on different types of systems. + +[Example] + +```c +#include +#include +#include +#include + +static uint32_t g_irqCnt; + +/* Sample function of the GPIO IRQ service */ +static int32_t SampleGpioIrqHandler(uint16_t gpio, void *data) +{ + HDF_LOGE("%s: irq triggered, on gpio:%u, data=%p", __func__, gpio, data); + g_irqCnt++; /* If the IRQ function is triggered, the number of global counters is incremented by 1. */ + return GpioDisableIrq(gpio); +} + +/* GPIO sample function */ +static int32_t SampleGpioIrqEdge(void) +{ + int32_t ret; + uint16_t valRead; + uint16_t mode; + uint16_t gpio = 83; // Number of the GPIO pin to test + uint32_t timeout; + + /* Set the output direction for the pin. */ + ret = GpioSetDir(gpio, GPIO_DIR_OUT); + ... + /* Disable the IRP of this pin. */ + ret = GpioDisableIrq(gpio); + ... + /* Set the IRR function for the pin. The trigger mode is both rising edge and falling edge. */ + mode = OSAL_IRQF_TRIGGER_RISING | OSAL_IRQF_TRIGGER_FALLING; + ret = GpioSetIrq(gpio, mode, SampleGpioIrqHandler, NULL); + ... + /* Enable the IRQ for this pin. */ + ret = GpioEnableIrq(gpio); + ... + g_irqCnt = 0; /* Reset the global counter. */ + timeout = 0; /* Reset the waiting time. */ + /* Wait for the IRQ function of this pin to trigger. The timeout duration is 1000 ms. */ + while (g_irqCnt <= 0 && timeout < 1000) { + ret = GpioRead(gpio, &valRead); + ... + ret = GpioWrite(gpio, (valRead == GPIO_VAL_LOW) ? GPIO_VAL_HIGH : GPIO_VAL_LOW); + ... + OsalMDelay(200); // Wait for an interrupt to be triggered. + timeout += 200; + } + ret = GpioUnSetIrq(gpio); + ... + return (g_irqCnt > 0) ? HDF_SUCCESS : HDF_FAILURE; +} +``` diff --git a/en/contribute/code-contribution.md b/en/contribute/code-contribution.md index 923c335c3754c54d8e82246eb1686ea2a69b9520..2b00657ca8b0fdf889c71e009b4968b06788d3f3 100644 --- a/en/contribute/code-contribution.md +++ b/en/contribute/code-contribution.md @@ -8,6 +8,8 @@ - [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md) +- [OpenHarmony Security Design Specifications](OpenHarmony-security-design-guide.md) + ### Code Style Develop, review, and test code following the OpenHarmony coding standards. Make sure code is written in the same style. @@ -17,6 +19,8 @@ Develop, review, and test code following the OpenHarmony coding standards. Make - [JavaScript Coding Style Guide](OpenHarmony-JavaScript-coding-style-guide.md) - [Python Coding Style Guide](https://pep8.org/) - [C&C++ Secure Coding Guide](OpenHarmony-c-cpp-secure-coding-guide.md) +- [HDF Driver Coding Guide](OpenHarmony-Java-secure-coding-guide.md) +- [32- and 64-Bit Portability Coding Guide](OpenHarmony-64bits-coding-guide.md) - [Java Secure Coding Guide](OpenHarmony-Java-secure-coding-guide.md) - [Logging Guide](OpenHarmony-Log-guide.md) @@ -28,6 +32,6 @@ For details, see [Contribution Process](contribution-process.md). - [Security Issue Handling and Release Processes](https://gitee.com/openharmony/security/blob/master/en/security-process/README.md) -- [OpenHarmony Security and Disclosure Statement](https://gitee.com/openharmony/security/blob/master/en/security-process/security-disclosure.md) +- [OpenHarmony Security Vulnerability Notice](https://gitee.com/openharmony/security/blob/master/en/security-process/security-disclosure.md) diff --git a/en/contribute/template/js-template.md b/en/contribute/template/js-template.md index e9075f5d26e5a2b454bf78e77a280c907355b307..4b1a5a913022a595fd16b25e36ac6249d1252972 100644 --- a/en/contribute/template/js-template.md +++ b/en/contribute/template/js-template.md @@ -67,6 +67,13 @@ Describe the module from its functionalities, use cases, and use suggestions in import call from '@ohos.telephony.call'; ``` +## System Capabilities +> *Writing Instructions* +> +> 3.1 - Mandatory. +> +Example: SystemCapability.BundleManager.BundleFramework + ## Attributes > *Writing Instructions* @@ -135,7 +142,7 @@ Required permission: ohos.permission.XXX (Delete this part if no permission is i | parameterOne | number \| string \| [CustomType](#CustomType) | Yes| Describe the parameter. Provide the value range and recommended value. If there is a fixed format, provide a format example, especially for the URI.
Provide a link for any custom parameter type.| | callback | Callback\> | No| Describe the parameter. For an optional parameter, describe the consequences if it is not specified.
Example: If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| -**Return values**: (Optional. Delete this heading if there is no return value.) +**Return value**: (Optional. Delete this heading if there is no return value.) | Type| Description| | ------------------------------------------ | -------------------------------------------- | @@ -199,7 +206,7 @@ Required permission: ohos.permission.XXX (Delete this part if no permission is i | parameterOne | number \| string \| [CustomType](#CustomType) | Yes| Describe the parameter. Provide the value range and recommended value. If there is a fixed format, provide a format example, especially for the URI.
Provide a link for any custom parameter type.| | callback | Callback\> | No| Describe the parameter. For an optional parameter, describe the consequences if it is not specified.
Example: If this parameter is not set, this method unsubscribes from all callbacks corresponding to **type**.| -**Return values**: (Optional. Delete this heading if there is no return value.) +**Return value**: (Optional. Delete this heading if there is no return value.) | Type| Description| | ------------------------------------------ | -------------------------------------------- | diff --git a/en/device-dev/get-code/gettools-acquire.md b/en/device-dev/get-code/gettools-acquire.md index 4b00335c966bbedd4be221e0aaab63d4212653d5..27055822bc419cf22a635389b6c3765a8a54b711 100644 --- a/en/device-dev/get-code/gettools-acquire.md +++ b/en/device-dev/get-code/gettools-acquire.md @@ -30,7 +30,7 @@ OpenHarmony provides the following two types of Docker environments for you to q

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

0.0.5

+

0.0.6

Standard system

@@ -60,6 +60,7 @@ OpenHarmony provides the following two types of Docker environments for you to q + ## Preparations Before using the Docker environment, perform the following operations: @@ -77,12 +78,10 @@ The Docker image of OpenHarmony is hosted on [HUAWEI CLOUD SWR](https://console ### Setting Up the Docker Environment for Mini-System Devices \(reference memory ≥ 128 KB\) and Small-System Devices \(reference memory ≥ 1 MB\) -**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR** - 1. Obtain the Docker image. ``` - docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker pull swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` 2. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: @@ -90,43 +89,13 @@ The Docker image of OpenHarmony is hosted on [HUAWEI CLOUD SWR](https://console Run the following command in Ubuntu: ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 - ``` - - Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\): - - ``` - docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 - ``` - - -**Method 2: Using the Dockerfile to Build a Local Docker Image** - -1. Obtain the Dockerfile script for a local Docker image. - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: - - ``` - cd docs/docker - ./build.sh - ``` - -3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: - - Run the following command in Ubuntu: - - ``` - docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v $(pwd):/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` Run the following command in Windows \(assuming that the source code directory is **D:\\OpenHarmony**\): ``` - docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.5 + docker run -it -v D:\OpenHarmony:/home/openharmony swr.cn-south-1.myhuaweicloud.com/openharmony-docker/openharmony-docker:0.0.6 ``` @@ -164,8 +133,6 @@ hb set ### Setting Up the Docker Environment for Standard-System Devices \(reference memory ≥ 128 MB\) -**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR** - 1. Obtain the Docker image. ``` @@ -179,28 +146,6 @@ hb set ``` -**Method 2: Using the Dockerfile to Build a Local Docker Image** - -1. Obtain the Dockerfile script for a local Docker image. - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: - - ``` - cd docs/docker/standard - ./build.sh - ``` - -3. Go to the root directory of OpenHarmony code and run the following command to access the Docker build environment: - - ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 - ``` - - ### Building for Standard-System Devices \(reference memory ≥ 128 MB\) Run the following script to start building for standard-system devices \(reference memory ≥ 128 MB\). @@ -209,7 +154,7 @@ Run the following script to start building for standard-system devices \(referen ./build.sh --product-name {product_name} --ccache ``` -**product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300 and RK3568. +**product\_name** indicates the platform supported by the current distribution, for example, Hi3516DV300 and rk3568. Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory. diff --git a/en/device-dev/quick-start/quickstart-standard-docker-environment.md b/en/device-dev/quick-start/quickstart-standard-docker-environment.md index 34d557772b9d5a80846bf587cd38348f57084abd..9374bb781fcdcd4c8a58d3070648e74756f3073c 100644 --- a/en/device-dev/quick-start/quickstart-standard-docker-environment.md +++ b/en/device-dev/quick-start/quickstart-standard-docker-environment.md @@ -61,8 +61,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. ## Obtaining the Docker Environment -**Method 1: Obtaining the Docker image from HUAWEI CLOUD SWR** - 1. Obtain the Docker image. ``` @@ -76,28 +74,6 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. ``` -**Method 2: Using the Dockerfile to Build a Local Docker Image** - -1. Obtain the Dockerfile script for a local Docker image. - - ``` - git clone https://gitee.com/openharmony/docs.git - ``` - -2. Go to the directory of the Dockerfile code and run the following command to build the Docker image: - - ``` - cd docs/docker/standard - ./build.sh - ``` - -3. Go to the root directory of source code and run the following command to access the Docker build environment: - - ``` - docker run -it -v $(pwd):/home/openharmony openharmony-docker-standard:0.0.7 - ``` - - ## Building Source Code 1. Run the following script to start building for standard-system devices \(reference memory ≥ 128 MB\). @@ -106,7 +82,7 @@ By default, the downloaded prebuilts binary file is stored in **OpenHarmony\_2. ./build.sh --product-name {product_name} --ccache ``` - **product\_name** indicates the platform supported by the current distribution, for example, Hi3516D V300, rk3568. + **product\_name** indicates the platform supported by the current distribution, for example, Hi3516DV300, rk3568. Files generated during building are stored in the **out/{device_name}/** directory, and the generated image is stored in the **out/{device_name}/packages/phone/images/** directory. diff --git a/en/device-dev/subsystems/subsys-data-relational-database-guide.md b/en/device-dev/subsystems/subsys-data-relational-database-guide.md index 44a0b1829249264fb99aff7cf998dd6a4de43b38..d668fc922079dfa5b38633d6c7a9c65a88351942 100644 --- a/en/device-dev/subsystems/subsys-data-relational-database-guide.md +++ b/en/device-dev/subsystems/subsys-data-relational-database-guide.md @@ -68,7 +68,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th Table 5 API for deleting data | Class| API| Description| | ---- | ---- | ---- | - | RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data.
  • **deletedRows**: specifies the number of rows to delete.
  • **predicates**: specifies the table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes:
    • **RdbPredicates**: specifies update conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.
| + | RdbStore | int Delete(int &deletedRows, const AbsRdbPredicates &predicates) | Deletes data.
  • **deletedRows**: specifies the number of rows to delete.
  • **predicates**: specifies the table name and conditions for deleting the data. **AbsRdbPredicates** has the following classes:
    • **RdbPredicates**: specifies delete conditions by calling its methods, such as **equalTo**.
    • **RawRdbPredicates**: specifies the table name, **whereClause** and **whereArgs** only.
| - Updating data diff --git a/en/readme/DeviceProfile.md b/en/readme/DeviceProfile.md new file mode 100644 index 0000000000000000000000000000000000000000..29653fb13b515c0c88d00f1ca819745f1a1a4397 --- /dev/null +++ b/en/readme/DeviceProfile.md @@ -0,0 +1,189 @@ +# DeviceProfile + +## Introduction + +DeviceProfile is used to manage device hardware capabilities and system software features. A typical device profile includes the device type, device name, OS type, and OS version. By allowing quick access to local and remote device profiles, DeviceProfile lays the foundation for initiating distributed services. It provides the following features: + +- Querying, inserting, and deleting local device profile information +- Querying remote device profile information +- Synchronizing profile information across devices +- Subscribing to remote device profile changes + +Below is the architecture of the DeviceProfile subsystem. + +## Architecture + +**Figure 1** Architecture of the DeviceProfile subsystem + +![](figures/dp-architecture.png) + +## Directory Structure + +The main code directory structure of DeviceProfile is as follows: + +``` +├── interfaces +│   └── innerkits +│ └── distributeddeviceprofile // Internal APIs +├── ohos.build +├── sa_profile // SAID profile +│   ├── 6001.xml +│   └── BUILD.gn +├── services +│   └── distributeddeviceprofile +│   ├── BUILD.gn +│   ├── include +│ │ ├── contentsensor // Header file for content sensor data collection +│ │ ├── dbstorage // Header file for database operations +│ │ ├── devicemanager // Header file for device management +│ │ └── subscribemanager // Header file for subscription management +│   ├── src +│ │ ├── contentsensor // Implementation of content sensor data collection +│ │ ├── dbstorage // Implementation of database operations +│ │ ├── devicemanager // Implementation of device management +│ │ ├── subscribemanager // Implementation of subscription management +│ └── test // Test cases +└── tools + └── dp // Auxiliary test tool +``` + +## Constraints + +- The devices between which you want to set up a connection must be in the same LAN. +- Before setting up a connection between two devices, you must bind the devices. For details about the binding process, see relevant descriptions in the Security subsystem readme file. + +## Usage + +### Querying Profile Information + +* Parameters of GetDeviceProfile + +| Name| Type| Mandatory| Description| +| --------- | ---------------------------- | ---- | ----------------------------------- | +| deviceId | std::string | Yes| ID of the device whose profile is to be queried. A null value indicates the local device.| +| serviceId | std::string | Yes| Service ID (ID of the service data record).| +| profile | ServiceCharacteristicProfile | Yes| Return value.| + +* Example + +```c++ +// Declare the return value. +ServiceCharacteristicProfile profile; +// Call GetDeviceProfile. +DistributedDeviceProfileClient::GetInstance().GetDeviceProfile(deviceId, serviceId, profile); +std::string jsonData = profile.GetCharacteristicProfileJson(); +result.append("jsonData:" + jsonData + "\n"); +``` + +### Inserting Profile Information + +* Parameters of PutDeviceProfile + +| Name| Type| Mandatory| Description| +| --------- | ---------------------------- | ---- | ----------------------------------- | +| profile | ServiceCharacteristicProfile | Yes| Profile information to insert.| + +* Example + +```c++ +// Declare and fill in the data to insert. +ServiceCharacteristicProfile profile; +profile.SetServiceId(serviceId); +profile.SetServiceType(serviceType); +nlohmann::json j; +j["testVersion"] = "3.0.0"; +j["testApiLevel"] = API_LEVEL; +profile.SetCharacteristicProfileJson(j.dump()); +// Call PutDeviceProfile. +DistributedDeviceProfileClient::GetInstance().PutDeviceProfile(profile); +``` + +### Deleting Profile Information + +* Parameters of DeleteDeviceProfile + +| Name| Type| Mandatory| Description| +| --------- | ---------------------------- | ---- | ----------------------------------- | +| serviceId | std::string | Yes| ID of the service record to delete.| + +* Example + +```c++ +// Declare and fill in the data to delete. +std::string serviceId = "test"; +// DeleteDeviceProfile +DistributedDeviceProfileClient::GetInstance().DeleteDeviceProfile(serviceId); +``` + +### Synchronizing Profile Information + +* Parameters of SyncDeviceProfile + +| Name| Type| Mandatory| Description| +| --------- | ---------------------------- | ---- | ----------------------------------- | +| syncOption| SyncOption | Yes| Synchronization mode and range.| +| syncCb | IProfileEventCallback | Yes| Callback used to return the synchronization result.| + +* Example + +```c++ +// Define the synchronization mode and range. +SyncOptions syncOption; +syncOption.SetSyncMode((OHOS::DistributedKv::SyncMode)atoi(mode.c_str())); +for (const auto& deviceId : deviceIds) { + syncOption.AddDevice(deviceId); +} +// Call SyncDeviceProfile. +DistributedDeviceProfileClient::GetInstance().SyncDeviceProfile(syncOption, + std::make_shared()); +``` + +### Subscribing to Profile Events (Synchronization and Change Events) + +* Parameters of SubscribeProfileEvents + +| Name| Type| Mandatory| Description| +| -------------- | ---------------------------- | ---- | ----------------------------------- | +| subscribeInfos | SubscribeInfo | Yes| Type of the event to subscribe to.| +| eventCb | IProfileEventCallback | Yes| Callback for the subscribed event.| +| failedEvents | ProfileEvent | Yes| Failure event.| + +* Example + +```c++ +auto callback = std::make_shared(); +std::list subscribeInfos; +ExtraInfo extraInfo; +extraInfo["deviceId"] = deviceId; +extraInfo["serviceIds"] = serviceIds; + +// Subscribe to the EVENT_PROFILE_CHANGED event. +SubscribeInfo info1; +info1.profileEvent = ProfileEvent::EVENT_PROFILE_CHANGED; +info1.extraInfo = std::move(extraInfo); +subscribeInfos.emplace_back(info1); + +// Subscribe to the EVENT_SYNC_COMPLETED event. +SubscribeInfo info2; +info2.profileEvent = ProfileEvent::EVENT_SYNC_COMPLETED; +info2.extraInfo = std::move(extraInfo); +subscribeInfos.emplace_back(info2); + +std::list failedEvents; +// Call SubscribeProfileEvents. +DistributedDeviceProfileClient::GetInstance().SubscribeProfileEvents(subscribeInfos, + callback, failedEvents); +sleep(SUBSCRIBE_SLEEP_TIME); +std::list profileEvents; +profileEvents.emplace_back(ProfileEvent::EVENT_PROFILE_CHANGED); +failedEvents.clear(); +// Cancel the subscription. +DistributedDeviceProfileClient::GetInstance().UnsubscribeProfileEvents(profileEvents, + callback, failedEvents); +``` + +## Repositories Involved + +**DeviceProfile subsystem** + +[device\_profile\_core](https://gitee.com/openharmony/device_profile_core) diff --git a/en/readme/figures/dp-architecture.png b/en/readme/figures/dp-architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..6d4573646c6b950b3e571d94ee09816397dd1d73 Binary files /dev/null and b/en/readme/figures/dp-architecture.png differ diff --git a/en/readme/figures/multimedia-architecture.png b/en/readme/figures/multimedia-architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..7c5341b63aa9ff48f3edfe48ed590a4cec8a3935 Binary files /dev/null and b/en/readme/figures/multimedia-architecture.png differ diff --git a/en/readme/multimedia.md b/en/readme/multimedia.md index c26c892898ccec4d4f1a442dc2a9e5abd623f27c..5c42b3425d8e33adb51ff38bb1e0ead7ec0ca8ea 100755 --- a/en/readme/multimedia.md +++ b/en/readme/multimedia.md @@ -8,23 +8,24 @@ This subsystem offers various media services covering audio, videos, and cameras - Audio playback and recording - Video playback and recording - - Photographing and recording \(with cameras\) -## Architecture - -**Figure 1** Common architecture of the multimedia subsystem - - -![](figures/en-us_image_0000001163462711.png) +## System Architecture -**Figure 2** Architecture of the multimedia subsystem suitable for the small system +**Figure 1** Architecture of the multimedia subsystem +![](figures/multimedia-architecture.png) -![](figures/multimedia-subsystem-architecture.png) - -**Figure 3** Multimedia service flow for the small system -![](figures/multimedia-service-flow-for-the-small-system.png "multimedia-service-flow-for-the-small-system") +- **Media**: provides playback and recording APIs for applications, and invokes the Gstreamer, Histreamer, or other engines through cross-process calling or direct calling. + - For the mini system, the media component invokes Histreamer to support audio playback. + - For the small system, the media component invokes recorder_lite to support audio/video recording and invokes player_lite by default to support audio/video playback. If the system variable **debug.media_service.histreamer** is set to **1**, the component invokes Histreamer to support audio/video playback. For details, see [syspara Module](https://device.harmonyos.com/en/docs/documentation/guide/subsys-boot-syspara-0000001063362360) or [syspara_lite](https://gitee.com/openharmony/startup_syspara_lite). + - For the standard system, the media component invokes Gstreamer to support audio/video playback and recording. +- **Audio**: supports audio input and output, policy management, and audio focus management. +- **Camera**: provides camera operation APIs for preview, photographing, and video recording. +- **Image**: supports encoding and decoding of common image formats. +- **MediaLibrary**: supports local and distributed media data access management. +- **Histreamer**: a lightweight media engine that supports file/network streaming media input, audio/video decoding and playback, audio/video encoding and recording, and plugin extension. +- **Gstreamer**: an open-source GStreamer engine that supports streaming media, audio and video playback, and recording. ## Directory Structure @@ -59,6 +60,13 @@ The structure of the repository directory is as follows: │ ├── figures # Architecture and process figures of the playback and recording module for the standard system │ ├── frameworks # Playback and recording framework implementation for the standard system │ └── interfaces # Playback and recording module APIs for the standard system +├── histreamer # Histreamer engine +│ └── engine # Media engine +│ ├── player # Encapsulated player +│ ├── foundation # Basic tools +│ ├── pipeline # Pipeline framework +│ └── plugin # Plugin framework +│ └── plugins # Platform software plugins └── utils # Subsystem utility module └── lite # Utility module for the small system ├── figures # Architecture and process figures of the utility module for the small system @@ -94,9 +102,10 @@ Load the kernel and related drivers before installing the repository. For detail [multimedia\_utils\_lite](https://gitee.com/openharmony/multimedia_utils_lite) +[multimedia\_histreamer](https://gitee.com/openharmony/multimedia_histreamer) + [multimedia\_camera\_standard](https://gitee.com/openharmony/multimedia_camera_standard) [multimedia\_audio\_standard](https://gitee.com/openharmony/multimedia_audio_standard) [multimedia\_media\_standard](https://gitee.com/openharmony/multimedia_media_standard) - diff --git a/en/release-notes/OpenHarmony-2-0-canary.md b/en/release-notes/OpenHarmony-2-0-Canary.md similarity index 100% rename from en/release-notes/OpenHarmony-2-0-canary.md rename to en/release-notes/OpenHarmony-2-0-Canary.md diff --git a/en/release-notes/OpenHarmony-v3.0.1-LTS.md b/en/release-notes/OpenHarmony-v3.0.1-LTS.md new file mode 100644 index 0000000000000000000000000000000000000000..93c97e5a99e41cfd30bc037c52959b655999d205 --- /dev/null +++ b/en/release-notes/OpenHarmony-v3.0.1-LTS.md @@ -0,0 +1,167 @@ +# OpenHarmony 3.0.1 LTS + +## Version Description + +OpenHarmony 3.0.1 LTS is a maintenance version with a tag of OpenHarmony 3.0 LTS. This version has rectified certain issues detected in OpenHarmony 3.0 LTS. + + +## Version Mapping + +**Table 1** Version mapping of software and tools + +| Software/Tool| Version| Remarks| +| -------- | -------- | -------- | +| OpenHarmony | 3.0.1 LTS | NA | +| SDK | 3.0.0.0 (API Version 7 release) | NA | +| (Optional) HUAWEI DevEco Studio| 3.0 Beta1 | Recommended for developing OpenHarmony applications| +| (Optional) HUAWEI DevEco Device Tool| 2.2 Beta2 | Recommended for developing OpenHarmony smart devices| + + +## Source Code Acquisition + + +### Acquiring Source Code Using the repo Tool + +Method 1 \(recommended\): Use the **repo** tool to download the source code over SSH. \(You must have an SSH public key for access to Gitee.\) + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.1-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +Method 2: Use the **repo** tool to download the source code over HTTPS. + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.1-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### Acquiring Source Code from Mirrors + +**Table 2** Mirrors for acquiring source code + +| LTS Code| Version| Mirror| SHA-256 Checksum| +| -------- | -------- | -------- | -------- | +| Full code base (for mini, small, and standard systems)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/code-v3.0.1-LTS.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/code-v3.0.1-LTS.tar.gz.sha256) | +| Standard system solution (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/standard.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/standard.tar.gz.sha256) | +| Hi3861 solution (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_pegasus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_pegasus.tar.gz.sha256) | +| Hi3518 solution (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_aries.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_aries.tar.gz.sha256) | +| Hi3516 solution-LiteOS (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_taurus.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_taurus.tar.gz.sha256) | +| Hi3516 solution-Linux (binary)| 3.0.1 | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_taurus_linux.tar.gz) | [Download](https://repo.huaweicloud.com/harmonyos/os/3.0.1/hispark_taurus_linux.tar.gz.sha256) | + + + +## What's New + +This version has the following updates to OpenHarmony 3.0 LTS. + + +### Feature Updates + +This version does not involve feature updates. + + +### API Updates + +This version does not involve API updates. + + +### Chip and Development Board Adaptation + +For details about the adaptation status, see [SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard.md). + + +## Resolved Issues + +**Table 3** Issues resolved for the mini and small systems + +| Issue No.| Description| +| -------- | -------- | +| [I4BJFU](https://gitee.com/openharmony/kernel_liteos_a/issues/I4BJFU) | An error occurs when the dyload_posix module removes a file.| +| [I42N33](https://gitee.com/openharmony/third_party_mksh/issues/I42N33) | During the integration test, the Ctrl+C operation does not function after the **cat** command is run. A device restart is required.| +| [I4C8BO](https://gitee.com/openharmony/docs/issues/I4C8BO?from=project-issue) | The basic functions of the media subsystem (on a mini- or small-system device) are abnormal when Hi3516D V300 or Hi3518E V300 is burnt and configured by following the instructions in the official website.| +| [I4BWKC](https://gitee.com/openharmony/drivers_framework/issues/I4BWKC) | The camera driver on the Hi3516D V300 board does not function properly in the pressure test.| +| [I4BW0G](https://gitee.com/openharmony/drivers_framework/issues/I4BW0G) | The **ResetDriver** interface of the Hi3516D V300 board fails to be called.| +| [I4C7ZK](https://gitee.com/openharmony/multimedia_camera_lite/issues/I4C7ZK) | For Hi3516D V300, the resident memory of the small system exceeds the baseline.| +| [I434P1](https://gitee.com/openharmony/multimedia_camera_lite/issues/I434P1) | For Hi3518E V300, the resident memory exceeds the baseline.| +| [I48IM7](https://gitee.com/openharmony/hiviewdfx_hilog/issues/I48IM7) | During the HiLog pressure test, the hilogd restarts unexpectedly, and the hilog commands cannot be used.| +| [I4EGMD](https://gitee.com/openharmony/aafwk_aafwk_lite/issues/I4EGMD) | The serialization and deserialization methods of **Want** are defective.| +| [I4CED3](https://gitee.com/openharmony/account_os_account/issues/I4CED3) | The JS API returns both "err" and "data" in one message.| +| [I4BXZ1](https://gitee.com/openharmony/app_samples/issues/I4BXZ1) | The **\** component does not respond to clicks.| +| [I4CMMH](https://gitee.com/openharmony/ace_ace_engine/issues/I4CMMH) | The display effect of the **\** component is abnormal.| +| [I4CE7D](https://gitee.com/openharmony/miscservices_inputmethod/issues/I4CE7D) | The response time of the edit box is inappropriate.| +| [I4HI4C](https://gitee.com/openharmony/ai_engine/issues/I4HI4C) | There is a failed item of the TDD test on a small-system device. This failure is caused by the inappropriate test case comparison time range.| +| [I4EUOW](https://gitee.com/openharmony/ai_engine/issues/I4EUOW) | The number of case execution threads is inappropriate.| +| [I4HTFS](https://gitee.com/openharmony/appexecfwk_appexecfwk_lite/issues/I4HTFS) | BMS adaptation for the mini system is not supported.| +| [I4C3BE](https://gitee.com/openharmony/communication_dsoftbus/issues/I4C3BE) | During passive Bluetooth Low Energy (BLE) discovery, the Bluetooth advertisement is frequently updated and, when the Bluetooth resources are used up, automatically disabled.| +| [I4I7QL](https://gitee.com/openharmony/developtools_packing_tool/issues/I4I7QL) | Packing fails when an ability has two widgets.| +| [I4BW0G](https://gitee.com/openharmony/drivers_framework/issues/I4BW0G) | There is a possibility that the Wi-Fi **ResetDriver** interface fails to be called.| +| [I4GBB6](https://gitee.com/openharmony/device_qemu/issues/I4GBB6) | The RISC-V QEMU emulator fails to run.| +| [I4CE7E](https://gitee.com/openharmony/kernel_liteos_a/issues/I4CE7E) | **drivers/mtd/multi_partition/** in the LiteOS-A kernel is implemented by using the driver functions in **device/hisilicon**.| +| [I4JBEH](https://gitee.com/openharmony/drivers_framework/issues/I4JBEH) | Memory leakage occurs when the DMA transmission interface of HDF is repeatedly used.| +| [I4IGQ0](https://gitee.com/openharmony/drivers_framework/issues/I4IGQ0) | Resources are released after component detection fails.| +| [I4JPCG](https://gitee.com/openharmony/drivers_framework/issues/I4JPCG) | The PWM backlight cannot be set to 0.| +| [I4ERM4](https://gitee.com/openharmony/drivers_peripheral/issues/I4ERM4) | A test case fails to be displayed.| +| [I4CMUY](https://gitee.com/openharmony/drivers_adapter_khdf_linux/issues/I4CMUY) | The hdf\_peripheral\_wlan\_test\_performance.bin test suite fails to run.| +| [I4FIP2](https://gitee.com/openharmony/kernel_liteos_a/issues/I4FIP2) | The **ioctl** function of the LiteOS_A kernel does not support the **SIOCGIFBRDADDR** option.| +| [I4GVF7](https://gitee.com/openharmony/kernel_liteos_a/issues/I4GVF7) | The permissions on the files and folders generated by the blackbox are inappropriate.| +| [I4EV8U](https://gitee.com/openharmony/kernel_liteos_a/issues/I4EV8U) | Three test cases, including IO_TEST_PPOLL_001, fail in the liteos\_a\_io\_unittest.bin\#IoTest module.| +| [I4EV3X](https://gitee.com/openharmony/kernel_liteos_a/issues/I4EV3X) | Seven test cases, including ItTestSys018, fail in the liteos\_a\_sys\_unittest.bin\#SysTest module.| +| [I4EVG0](https://gitee.com/openharmony/kernel_liteos_a/issues/I4EVG0) | The test case ItTestMisc009 fails in the liteos\_a\_misc\_unittest.bin\#MiscTest module.| +| [I4JYAX](https://gitee.com/openharmony/kernel_liteos_a/issues/I4JYAX) | The jffs2 adaptation layer incorrectly releases the lock.| +| [I4FIQW](https://gitee.com/openharmony/kernel_liteos_m/issues/I4FIQW) | The **ioctl** function of the LiteOS_M kernel does not support the **SIOCGIFBRDADDR** option.| +| [I4ELVA](https://gitee.com/openharmony/kernel_liteos_m/issues/I4ELVA) | The **read** interface at the VFS layer of the file system incorrectly determines whether **g_fs** is null.| +| [I4C6P2](https://gitee.com/openharmony/kernel_liteos_m/issues/I4C6P2) | The **LOS_QueueInfoGet** function incorrectly counts the tasks waiting to be read and written.| +| [I4C5RW](https://gitee.com/openharmony/kernel_liteos_m/issues/I4C5RW) | The error indicating that the **OS_TASK_STACK_PROTECT_SIZE** macro is not defined occurs when the MPU is enabled to protect the task stack.| +| [I4G4VK](https://gitee.com/openharmony/kernel_liteos_m/issues/I4G4VK) | Some macros are inappropriate. If they (for example, **inet_addr**) are changed to functions, the lwIP header file is not required for external calling.| +| [I4FVGV](https://gitee.com/openharmony/kernel_liteos_m/issues/I4FVGV) | The default lwIP configuration of the LiteOS_M kernel is inappropriate.| +| [I4CE7D](https://gitee.com/openharmony/miscservices_inputmethod/issues/I4CE7D) | There is no necessary to start the input method after a 3-second delay.| +| [I4CFOO](https://gitee.com/openharmony/multimedia_media_lite/issues/I4CFOO) | After an application running on the Linux system records videos for multiple times, the size of the last recording file is 0 when the system is restarted without exiting the application.| +| [I4CLGW](https://gitee.com/openharmony/kernel_liteos_a/issues/I4CLGW) | The page cache is inappropriate.| +| [I4HKQ2](https://gitee.com/openharmony/vendor_hisilicon/issues/I4HKQ2) | The mechanism for the LiteOS running on a mini-system board to obtain the UDID is inappropriate.| +| [I4FVJN](https://gitee.com/openharmony/startup_syspara_lite/issues/I4FVJN) | Mini system compilation fails because the dependency to mbedTLS is not added.| +| [I4CE7E](https://gitee.com/openharmony/kernel_liteos_a/issues/I4CE7E) | **drivers/mtd/multi_partition/** in the LiteOS-A kernel is implemented by using the driver functions in **device/hisilicon**.| + +**Table 4** Issues resolved for the standard system + +| Issue No.| Description| +| -------- | -------- | +| [I4BX4J](https://gitee.com/openharmony/hiviewdfx_hicollie/issues/I4BX4J?from=project-issue) | The Hi3516D V300 board fails to call the **hicollie** interface.| +| [I4BX1X](https://gitee.com/openharmony/hiviewdfx_hitrace/issues/I4BX1X?from=project-issue) | The Hi3516D V300 board fails to call the **hitrace** interface.| +| [I4BVUL](https://gitee.com/openharmony/communication_wifi/issues/I4BVUL?from=project-issue) | When access points (APs) are changed, the success rate for networking between standard-system devices and mobile phones is 91%, lower than the expected value (98%).| +| [I4BW6E](https://gitee.com/openharmony/security_deviceauth/issues/I4BW6E) | During the test for networking between standard-system devices and mobile phones, when the mobile phone disables and enables the network access repeatedly for around 30 times, the networking fails.| +| [I4BVVW](https://gitee.com/openharmony/communication_dsoftbus/issues/I4BVVW) | During the test for networking between standard-system devices and mobile phones, when the Wi-Fi switch is turned on and off repeatedly, the networking success rate is 97%, lower than the expected value.| +| [I48YPH](https://gitee.com/openharmony/security_deviceauth/issues/I48YPH?from=project-issue) | During the test for discovery and networking performance, 3 out of 110 networking attempts fails.| +| [I4492M](https://gitee.com/openharmony/communication_dsoftbus/issues/I4492M) | The offline device detection takes about 30s longer than the specifications.| +| [I44W7U](https://gitee.com/openharmony/graphic_standard/issues/I44W7U?from=project-issue) | The child window does not support zooming. As a result, the progress bar is hidden during video playback.| +| [I480Z1](https://gitee.com/openharmony/communication_dsoftbus/issues/I480Z1?from=project-issue) | Softbus_server crashes when executing **socketfuzz**.| +| [I4BGLS](https://gitee.com/openharmony/security_deviceauth/issues/I4BGLS?from=project-issue) | The key imported by using `import_signed_auth_info_hilink` is used for identifying the HiChain connection. After the key is imported, it is encrypted and stored in the file and is not cleared from the heap after being returned.| +| [I4A10Q](https://gitee.com/openharmony/startup_appspawn/issues/I4A10Q?from=project-issue) | The performance of Hi3516 3.0.0.6 static KPIs deteriorates severely.| +| [I4BXYT](https://gitee.com/openharmony/developtools_hdc_standard/issues/I4BXYT) | After device restart, developers must run the **hdc_std kill** command to discover the device again.| +| [I4KUTY](https://gitee.com/openharmony/ace_engine_lite/issues/I4KUTY) | There are invalid return values.| +| [I4DMFV](https://gitee.com/openharmony/ark_js_runtime/issues/I4DMFV) | The conversion from UTF-16 to UTF-8 is inappropriate.| +| [I4HGVM](https://gitee.com/openharmony/communication_dsoftbus/issues/I4HGVM) | The dependency on mbedTLS is missing for the standard system.| +| [I4DLV2](https://gitee.com/openharmony/drivers_framework/issues/I4DLV2) | An invalid memory access error occurs due to the HidInfo\* type.| +| [I4CIJJ](https://gitee.com/openharmony/third_party_flutter/issues/I4CIJJ) | ACE does not support GPU rendering.| +| [I4G31Z](https://gitee.com/openharmony/third_party_freetype/issues/I4G31Z) | An update for the font engine version from 2.10.1 to 2.10.4 is unavailable.| +| [I4H06M](https://gitee.com/openharmony/third_party_harfbuzz/issues/I4H06M) | An update for the OpenType text shaping engine from 2.6.1 to 2.8.1 is unavailable.| +| [I4FS7V](https://gitee.com/openharmony/third_party_lwip/issues/I4FS7V) | The **LWIP\_NETCONN\_FULLDUPLEX** macro is not used to control the initialization of **conn->mbox\_threads\_waiting**.| +| [I43KL7](https://gitee.com/openharmony/graphic_standard/issues/I43KL7) | The synthesizer does not support GPU synthesis.| + + +## Known Issues + +**Table 5** Known issues + +| Issue No.| Description| Impact| To Be Resolved On| +| -------- | -------- | -------- | -------- | +| [I4NMXQ](https://gitee.com/openharmony/xts_acts/issues/I4NMXQ?from=project-issue) | The XTS test suites storagefileioperformancejstest and storagefilestabilityjstest cannot be automatically executed on a standard-system device.| This issue is caused by the XTS test suite framework. The test suites can only be manually executed. This issue does not affect functions.| 2022/01/30 | +| [I4NU92](https://gitee.com/openharmony/communication_wifi/issues/I4NU92) | Mini-system Hi3516_Linux: The ActsLwipTest.bin test suite has a failed test item.| The automatic test case fails to invoke the kernel to read time_out. This issue does not affect the communication function.| 2022/01/15 | +| [I4NTKG](https://gitee.com/openharmony/xts_acts/issues/I4NTKG) | Two failed items are displayed when the XTS test suite WeekPluralNumberTest is executed.| This is a test case issue and does not affect functions.| 2022/01/15 | +| [I4OWWM](https://gitee.com/openharmony/xts_acts/issues/I4OWWM) | The JSON file corresponding to the WeekPluralNumbertest module is incorrectly configured. During case execution, the error message "required device does not exist" is displayed.| The JSON file configuration is incorrect. This issue does not affect functions.| 2022/01/15 | +| [I4MSVV](https://gitee.com/openharmony/xts_acts/issues/I4MSVV?from=project-issue) | During the XTS test on the standard system, there are three failed items of the HiCollieCppTest cases in the ActsHiCollieCppTest module.| The test suite name is changed. As a result, the test case with the text verification function fails. This issue does not affect functions.| 2022/01/15 | +| [I4MSWM](https://gitee.com/openharmony/xts_acts/issues/I4MSWM?from=project-issue) | During the XTS test on the standard system, there is one failed item for faultloggertest in the ActsFaultLoggerTest module.| The test suite name is changed. As a result, the test case with the text verification function fails. This issue does not affect functions.| 2022/01/15 | +| [I4NODO](https://gitee.com/openharmony/device_manager/issues/I4NODO) | During the test for the Hi3516 board running on a standard-system device, the E2E test of the distributed service hopping fails.| The DM component fails to repeatedly create a group. This issue affects the services that use hopping in the same way as that described in the issue details. Other services are not affected.| 2022/01/30 | diff --git a/en/release-notes/Readme.md b/en/release-notes/Readme.md index bc2cf67f424665d1346bfd1e4955ed8f56bbb2ee..1182087f12c19aff9aa3772fe559feed1ba534ef 100644 --- a/en/release-notes/Readme.md +++ b/en/release-notes/Readme.md @@ -1,11 +1,12 @@ # OpenHarmony Release Notes ## OpenHarmony 3.x Releases - [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md) +- [OpenHarmony v3.0.1 LTS (2022-01-12)](OpenHarmony-v3.0.1-LTS.md) - [OpenHarmony v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md) ## OpenHarmony 2.x Releases - [OpenHarmony v2.2 beta2 (2021-08-04)](OpenHarmony-v2.2-beta2.md) -- [OpenHarmony 2.0 Canary (2021-06-02)](OpenHarmony-2-0-canary.md) +- [OpenHarmony 2.0 Canary (2021-06-02)](OpenHarmony-2-0-Canary.md) ## OpenHarmony 1.x Releases - [OpenHarmony v1.1.3 LTS (2021-09-30)](OpenHarmony-v1-1-3-LTS.md) - [OpenHarmony v1.1.2 LTS (2021-08-04)](OpenHarmony-v1.1.2-LTS.md) diff --git a/zh-cn/application-dev/Readme-CN.md b/zh-cn/application-dev/Readme-CN.md index da4e7d1ccf044c6c683143eeaaa9385840bb0c11..46bc2b4a8691a43cbf65b5fa836580ed76e96204 100644 --- a/zh-cn/application-dev/Readme-CN.md +++ b/zh-cn/application-dev/Readme-CN.md @@ -8,10 +8,12 @@ - 方舟开发框架(ArkUI) - [基于JS扩展的类Web开发范式](ui/ui-arkui-js.md) - [基于TS扩展的声明式开发范式](ui/ui-arkui-ts.md) +- [后台代理提醒](background-agent-scheduled-reminder/Readme-CN.md) +- [后台任务管理](background-task-management/Readme-CN.md) - [媒体](media/Readme-CN.md) - [安全](security/Readme-CN.md) - [IPC与RPC通信](connectivity/ipc-rpc.md) -- [分布式数据服务](database/Readme-CN.md) +- [数据管理](database/Readme-CN.md) - [USB服务](usb/Readme-CN.md) - [DFX](dfx/Readme-CN.md) - [开发参考](reference/Readme-CN.md) diff --git a/zh-cn/application-dev/background-task-management/Readme-CN.md b/zh-cn/application-dev/background-task-management/Readme-CN.md new file mode 100644 index 0000000000000000000000000000000000000000..36178f390b77fbf8b4ed9abd5309c450f0fed3eb --- /dev/null +++ b/zh-cn/application-dev/background-task-management/Readme-CN.md @@ -0,0 +1,5 @@ +# 后台任务管理 + +- 后台任务 + - [后台任务概述](background-task-overview.md) + - [后台任务开发指导](background-task-dev-guide.md) \ No newline at end of file diff --git a/zh-cn/application-dev/background-task-management/background-task-dev-guide.md b/zh-cn/application-dev/background-task-management/background-task-dev-guide.md index 590eeaeb10e8fb8eef38659490aeaeb0f8badc0b..2047780916748df3d73dabb48f13df84c9960e32 100644 --- a/zh-cn/application-dev/background-task-management/background-task-dev-guide.md +++ b/zh-cn/application-dev/background-task-management/background-task-dev-guide.md @@ -7,10 +7,12 @@ ## 接口说明 -``` +```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; ``` +## 短时任务 + **表1** backgroundTaskManager主要接口 | 接口名 | 描述 | @@ -29,51 +31,221 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; ## 开发步骤 + 1. 申请延迟挂起 - ``` - import backgroundTaskManager from '@ohos.backgroundTaskManager'; - let myReason = 'test requestSuspendDelay'; - let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspend delay will time out."); - }); - var id = delayInfo.requestId;console.info("requestId is: " + id); - ``` + + ```js + 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. 获取进入挂起前的剩余时间 - ``` - backgroundTaskManager.getRemainingDelayTime(id).then( res => { - console.log('promise => Operation succeeded. Data: ' + JSON.stringify(res)); - }).catch( err => { - console.log('promise => Operation failed. Cause: ' + err.data); - }); - ``` + + ```js + 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. 取消延迟挂起 - ``` - backgroundTaskManager.cancelSuspendDelay(id); - ``` + + ```js + backgroundTaskManager.cancelSuspendDelay(id); + ``` ## 开发实例 -``` +```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; let myReason = 'test requestSuspendDelay'; + // 申请延迟挂起 let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspend delay will time out."); + console.info("Request suspension delay will time out."); }); + // 打印延迟挂起信息 var id = delayInfo.requestId; var time = delayInfo.actualDelayTime; console.info("The requestId is: " + id); console.info("The actualDelayTime is: " + time); + // 获取应用程序进入挂起状态前的剩余时间 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(id); ``` + +## 长时任务 + +### 权限 + +ohos.permission.KEEP_BACKGROUND_RUNNING + +**表3** 长时任务主要接口 + +| 接口名 | 描述 | +| -------- | -------- | +| function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void;
function startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>; | 服务启动后,向系统申请长时任务,使服务一直保持后台运行 | +| function stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void;
function stopBackgroundRunning(context: Context): Promise<void>; | 停止后台长时任务的运行 | + + +其中,wantAgent的信息详见([WantAgent](#zh-cn/application-dev/reference/apis/js-apis-notification.md#WantAgent接口)) + + +**表4** 后台模式类型 +| 参数名 | id值 | 描述 | +| -------- | -------- | -------- | +| DATA_TRANSFER | 1 | 数据传输 | +| AUDIO_PLAYBACK | 2 | 音频播放 | +| AUDIO_RECORDING | 3 | 录音 | +| LOCATION | 4 | 定位导航 | +| BLUETOOTH_INTERACTION | 5 | 蓝牙相关 | +| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 | +| WIFI_INTERACTION | 7 | WLAN相关(系统保留) | +| VOIP | 8 | 音视频通话(系统保留) | +| TASK_KEEPING | 9 | 计算任务(仅供PC使用) | + + +## 开发步骤 + +1. 在config.json文件中配置长时任务权限 + + ```json + "module": { + "package": "com.example.myapplication", + ..., + "reqPermissions": [ + { + "name": "ohos.permission.KEEP_BACKGROUND_RUNNING" + } + ] + } + ``` + +2. 申请长时任务 + + ```js + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); + }); + ``` + +3. 停止长时任务 + + ```js + import backgroundTaskManager from '@ohos.backgroundTaskManager'; + import featureAbility from '@ohos.ability.featureAbility'; + + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); + + ``` + +## 开发实例 + +当服务启动后,在serviceAbility的onStart回调方法中,调用长时任务的申请接口,声明此服务需要在后台长时运行。在onStop回调方法里,调用长时任务取消接口,声明取消长时任务。 +在service.js文件中: + +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; +import wantAgent from '@ohos.wantAgent'; + +function startBackgroundRunning() { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] + }; + + // 通过wantAgent模块的getWantAgent方法获取WantAgent对象 + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); + }); +} + +function stopBackgroundRunning() { + backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); +} + +export default { + onStart(want) { + console.info('ServiceAbility onStart'); + startBackgroundRunning(); + }, + onStop() { + console.info('ServiceAbility onStop'); + stopBackgroundRunning(); + }, + onConnect(want) { + console.info('ServiceAbility onConnect'); + return {}; + }, + onReconnect(want) { + console.info('ServiceAbility onReconnect'); + }, + onDisconnect() { + console.info('ServiceAbility onDisconnect'); + }, + onCommand(want, restart, startId) { + console.info('ServiceAbility onCommand'); + } +}; +``` \ No newline at end of file diff --git a/zh-cn/application-dev/background-task-management/background-task-overview.md b/zh-cn/application-dev/background-task-management/background-task-overview.md index f3cec92c4187b4a63b4ca35f787b37e37c0a71d5..fa4c7330628333de635df896851dbb1c04b5cf6f 100644 --- a/zh-cn/application-dev/background-task-management/background-task-overview.md +++ b/zh-cn/application-dev/background-task-management/background-task-overview.md @@ -1,4 +1,4 @@ -# 概述 +# 后台任务概述 对于有用户交互的OS来说,资源优先分配给与用户交互的业务进程,换句话说,在支撑OS运行的进程以外,用户能感知到的业务进程优先级最高,所以后台任务管理的范围是用户感知不到的业务进程。 @@ -33,3 +33,30 @@ - **取消时机**:任务完成后申请方应用主动取消延时申请,不要等到超时后被系统取消,否则会影响该应用的后台允许运行时长配额。 - **配额机制**:为了防止应用滥用保活,或者申请后不取消,每个应用每天都会有一定配额(会根据用户的使用习惯动态调整),配额消耗完就不再允许申请短时任务,所以应用完成短时任务后立刻取消延时申请,避免消耗配额。(注,这个配额指的是申请的时长,系统默认应用在后台运行的时间不计算在内)。 + +## 长时任务 +长时任务给用户能够直观感受到的且需要一直在后台运行的业务提供后台运行生命周期的保障。比如:业务需要在后台播放声音、需要在后台持续导航定位等。此类用户可以直观感知到的后台业务行为,可以通过使用长时任务对应的后台模式保障业务在后台的运行,支撑应用完成在后台的业务。 + +### 后台模式分类 +OpenHarmony提供了九种后台模式,供需要在后台做长时任务的业务使用,具体的后台模式类型如下: + +**表1** 长时任务种类 + +| BackgroundMode | 说明 | 通知栏显示提示 | 备注 | +| -------- | -------- | -------- | -------- | +| dataTransfer | 通过网络/对端设备进行数据下载、备份、分享、传输等 | 正在运行数据传输任务 | | +| audioPlayback | 音频输出 | 正在运行音频播放任务 | | +| audioRecording | 音频输入 | 正在运行录音任务 | | +| location | 定位、导航 | 正在运行定位任务 | | +| bluetoothInteraction | 蓝牙传输 | 正在运行蓝牙相关任务 | | +| multiDeviceConnection | 分布式互联任务 | 正在运行分布式任务 | | +| wifiInteraction | WLAN传输 | 正在运行WLAN相关任务 | SystemApi,仅对System权限应用开放 | +| voip | 音视频电话、VOIP | 正在运行通话相关任务 | SystemApi,仅对System权限应用开放 | +| taskKeeping | 计算任务 | 正在运行计算任务 | PC特有,仅在PC申请生效 | + +### 长时任务使用约束 +- 如果用户选择可感知业务(如播音、导航、上传下载等),触发对应后台模式,在任务启动时,系统会强制弹出通知提醒用户。 +- 如果任务结束,应用应主动退出后台模式。若在后台运行期间,系统检测到应用并未使用对应后台模式的资源,则会被挂起(Suspend)。 +- 避免不合理地申请后台长时任务,长时任务类型要与应用的业务类型匹配。如表1所示。如果执行的任务和申请的类型不匹配,也会被系统检测到并被挂起(Suspend)。 +- 长时任务是为了真正在后台长时间执行某个任务,如果一个应用申请了长时任务,但在实际运行过程中,并未真正运行或执行此类任务时,也会被系统检测到并被挂起(Suspend)。 +- 每个Ability同一时刻只能申请运行一个长时任务。 \ No newline at end of file diff --git a/zh-cn/application-dev/database/Readme-CN.md b/zh-cn/application-dev/database/Readme-CN.md index f6341aa680d95dc524fb2e1820f7b08b53ecc69d..c96d684813ae4d444503601e566f5e42061f552e 100644 --- a/zh-cn/application-dev/database/Readme-CN.md +++ b/zh-cn/application-dev/database/Readme-CN.md @@ -1,4 +1,11 @@ -# 分布式数据服务 +# 数据管理 -- [分布式数据服务概述](database-mdds-overview.md) -- [分布式数据服务开发指导](database-mdds-guidelines.md) +- 分布式数据服务 + - [分布式数据服务概述](database-mdds-overview.md) + - [分布式数据服务开发指导](database-mdds-guidelines.md) +- 关系型数据库 + - [关系型数据库概述](database-relational-overview.md) + - [分布式数据服务开发指导](database-relational-guidelines.md) +- 轻量级数据存储 + - [轻量级数据存储概述](database-preference-overview.md) + - [轻量级数据存储开发指导](database-preference-guidelines.md) diff --git a/zh-cn/application-dev/database/database-preference-guidelines.md b/zh-cn/application-dev/database/database-preference-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..93ae0313272e6599e0f12ce48cea14e4a47b042f --- /dev/null +++ b/zh-cn/application-dev/database/database-preference-guidelines.md @@ -0,0 +1,161 @@ +# 轻量级数据存储开发指导 + +## 场景介绍 + +轻量级数据存储功能通常用于保存应用的一些常用配置信息,并不适合需要存储大量数据和频繁改变数据的场景。应用的数据保存在文件中,这些文件可以持久化地存储在设备上。需要注意的是,应用访问的实例包含文件所有数据,这些数据会一直加载在设备的内存中,直到应用主动从内存中将其移除前,应用可以通过Storage的API进行数据操作。 + +## 接口说明 + +轻量级存储为应用提供key-value键值型的文件数据处理能力,支持应用对数据进行轻量级存储及查询。数据存储形式为键值对,键的类型为字符串型,值的存储数据类型包括数字型、字符型、布尔型。 + +**创建存储实例** + +读取指定文件,将数据加载到Storage实例,即可创建一个存储实例,用于数据操作。 + +**表1** 轻量级数据存储实例创建接口 + +| 包名 | 接口名 | 描述 | +| ----------------- | ------------------------------------------- | ------------------------------------------- | +| ohos.data.storage | getStorage(path: string): Promise\ | 获取文件对应的Storage单实例,用于数据操作。 | + +**存入数据** + +通过put系列方法,可以增加或修改Storage实例中的数据。 + +**表2** 轻量级数据存入接口 + +| 类名 | 接口名 | 描述 | +| ------- | -------------------------------------------------- | ----------------------------------------------- | +| Storage | put(key: string, value: ValueType): Promise\ | 支持值为number、string、boolean类型的数据存入。 | + +**读取数据** + +通过调用get系列方法,可以读取Storage中的数据。 + +**表3** 轻量级数据读取接口 + +| 类名 | 接口名 | 描述 | +| ------- | ---------------------------------------------------------- | ----------------------------------------------- | +| Storage | get(key: string, defValue: ValueType): Promise\ | 支持获取值为number、string、boolean类型的数据。 | + +**数据持久化** + +通过执行flush方法,应用可以将缓存的数据再次写回文本文件中进行持久化存储。 + +**表4** 轻量级数据持久化接口 + +| 类名 | 接口名 | 描述 | +| ------- | ----------------------- | --------------------------------------- | +| Storage | flush(): Promise\ | 将Storage实例通过异步线程回写入文件中。 | + +**订阅数据变化** + +订阅数据变化需要指定StorageObserver作为回调方法。订阅的key的值发生变更后,当执行flush方法时,StorageObserver被回调。 + +**表5** 轻量级数据变化订阅接口 + +| 类名 | 接口名 | 描述 | +| ------- | ------------------------------------------------------------ | -------------- | +| Storage | on(type: 'change', callback: Callback\): void | 订阅数据变化。 | +| Storage | off(type: 'change', callback: Callback\): void | 注销订阅。 | + +**删除数据文件** + +通过调用以下两种接口,可以删除数据实例或对应的文件。 + +**表6** 轻量级数据存储删除接口 + +| 包名 | 接口名 | 描述 | +| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ | +| ohos.data.storage | deleteStorage(path: string): Promise\ | 从缓存中移除已加载的Storage对象,同时从设备上删除对应的文件。 | +| ohos.data.storage | removeStorageFromCache(path: string): Promise\ | 仅从缓存中移除已加载的Storage对象,主要用于释放内存。 | + +## 开发步骤 + +1. 准备工作,导入@ohos.data.storage以及相关的模块到开发环境。 + + ``` + import dataStorage from '@ohos.data.storage' + import featureAbility from '@ohos.ability.featureAbility' // 用于获取文件存储路径 + ``` + +2. 获取Storage实例。 + + 读取指定文件,将数据加载到Storage实例,用于数据操作。 + ``` + var context = featureAbility.getContext() + var path = await context.getFilesDir() + let promise = dataStorage.getStorage(path + '/mystore') + ``` + +3. 存入数据。 + + 使用Storage put方法保存数据到缓存的实例中。 + + ``` + promise.then((storage) => { + let getPromise = storage.put('startup', 'auto') // 保存数据到缓存的storage示例中。 + 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") + }) + ``` + +4. 读取数据。 + + 使用Storage get方法读取数据。 + + ``` + 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")}) + ``` + +5. 数据持久化。 + + 应用存入数据到Storage实例后,可以通过flush或者flushSync方法将Storage实例回写到文件中。 + + ``` + storage.flush(); + ``` + +6. 订阅数据变化。 + + 应用订阅数据变化需要指定StorageObserver作为回调方法。订阅的key的值发生变更后,当执行flush方法时,StorageObserver被触发回调。不再需要StorageObserver时请注销。 + + ``` + promise.then((storage) => { + var observer = function (key) { + console.info("The key of " + key + " changed.") + } + storage.on('change', observer) + storage.putSync('startup', 'auto') // 修改storage存储数据 + storage.flushSync() // 触发订阅者回调方法 + + storage.off('change', observer) // 注销数据变化订阅 + }).catch((err) => { + console.info("Get the storage failed") + }) + ``` + +7. 删除指定文件。 + + 使用deleteStorage方法从内存中移除指定文件对应的Storage单实例,并删除指定文件及其备份文件、损坏文件。删除指定文件时,应用不允许再使用该实例进行数据操作,否则会出现数据一致性问题。删除后,数据及文件将不可恢复。 + + ``` + let promise = dataStorage.deleteStorage(path + '/mystore') + promise.then(() => { + console.info("Deleted successfully.") + }).catch((err) => { + console.info("Deleted failed with err: " + err)}) + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-preference-overview.md b/zh-cn/application-dev/database/database-preference-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..b906e9423d4b4f988a0d12d66167f0ec6f855047 --- /dev/null +++ b/zh-cn/application-dev/database/database-preference-overview.md @@ -0,0 +1,28 @@ +# 轻量级数据存储概述 + +轻量级数据存储适用于对Key-Value结构的数据进行存取和持久化操作。应用获取某个轻量级存储对象后,该存储对象中的数据将会被缓存在内存中,以便应用获得更快的数据存取速度。应用也可以将缓存的数据再次写回文本文件中进行持久化存储,由于文件读写将产生不可避免的系统资源开销,建议应用减少对持久化文件的读写频率。 + +## 基本概念 + +- **Key-Value数据结构** + + 一种键值结构数据类型。Key是不重复的关键字,Value是数据值。 + +- **非关系型数据库** + + 区别于关系数据库,不保证遵循ACID(Atomic、Consistency、Isolation及Durability)特性,不采用关系模型来组织数据,数据之间无关系。 + +## 运作机制 + +1. 应用通过指定Storage文件将其中的数据加载到Storage实例,系统会通过静态容器将该实例存储在内存中,同一应用或进程中每个文件仅存在一个Storage实例,直到应用主动从内存中移除该实例或者删除该Storage文件。 +2. 应用获取到Storage文件对应的实例后,可以从Storage实例中读取数据,或者将数据存入Storage实例中。通过调用flush或者flushSync方法可以将Storage实例中的数据回写到文件里。 + +**图1** 轻量级数据存储运作机制 + +![zh-cn_image_0000001199139454](figures/zh-cn_image_0000001199139454.png) + +## 约束与限制 + +- 因Storage实例会加载到内存中,建议存储的数据不超过一万条,并及时清理不再使用的实例,以便减少非内存开销。 +- 数据中的key为string类型,要求非空且字符长度不超过80个。 +- 当数据中的value为string类型时,允许为空,字符长度不超过8192个。 \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..127fa0bae8e4a437f27d02262d388d22ff7a1ba5 --- /dev/null +++ b/zh-cn/application-dev/database/database-relational-guidelines.md @@ -0,0 +1,200 @@ +# 关系型数据库开发指导 + +## 场景介绍 + +关系型数据库是在SQLite基础上实现的本地数据操作机制,提供给用户无需编写原生SQL语句就能进行数据增删改查的方法,同时也支持原生SQL语句操作。 + + +## 接口说明 + +**数据库的创建和删除** + +关系型数据库提供了数据库创建方式,以及对应的删除接口,涉及的API如下所示。 + +**表1** 数据库创建和删除API + +| 类名 | 接口名 | 描述 | +| -------- | -------- | -------- | +| dataRdb | getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void | 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,结果以callback形式返回。
- config:与此RDB存储相关的数据库配置。
- version:数据库版本。
- callback:指定callback回调函数。返回一个RdbStore。 | +| dataRdb | getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> | 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,结果以Promise形式返回。
- config:与此RDB存储相关的数据库配置。
- version:数据库版本。 | +| dataRdb | deleteRdbStore(name: string, callback: AsyncCallback<void>): void | 删除数据库,结果以callback形式返回。
- name:数据库名称。
- callback:指定callback回调函数。如果数据库已删除,则为true;否则返回false。 | +| dataRdb | deleteRdbStore(name: string): Promise<void> | 使用指定的数据库文件配置删除数据库,结果以Promise形式返回。
- name:数据库名称。 | + +**数据库的增删改查** + +关系型数据库提供对本地数据增删改查操作的能力,相关API如下所示。 + +- **新增** + 关系型数据库提供了插入数据的接口,通过ValuesBucket输入要存储的数据,通过返回值判断是否插入成功,插入成功时返回最新插入数据所在的行号,失败时则返回-1。 + **表2** 数据库插入API + + | 类名 | 接口名 | 描述 | + | -------- | -------- | -------- | + | RdbStore | insert(name: string, values: ValuesBucket, callback: AsyncCallback<number>):void | 向目标表中插入一行数据,结果以callback形式返回。
- name:指定的目标表名。
- values:表示要插入到表中的数据行。
- callback:指定callback回调函数。如果操作成功,返回行ID;否则返回-1。 | + | RdbStore | insert(name: string, values: ValuesBucket): Promise<number> | 向目标表中插入一行数据,结果以Promise形式返回。
- name:指定的目标表名。
- values:表示要插入到表中的数据行。 | + +- **更新** + 调用更新接口,传入要更新的数据,并通过RdbPredicates指定更新条件。该接口的返回值表示更新操作影响的行数。如果更新失败,则返回0。 + + **表3** 数据库更新API + + | 类名 | 接口名 | 描述 | + | -------- | -------- | -------- | + | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | 根据RdbPredicates的指定实例对象更新数据库中的数据,结果以callback形式返回。
- values:以ValuesBucket存储的要更新的数据。
- rdbPredicates:表示RdbPredicates的实例对象指定的更新条件。
- callback:指定的callback回调方法。返回受影响的行数。 | + | RdbStore | update(values: ValuesBucket, rdbPredicates: RdbPredicates): Promise | 根据RdbPredicates的指定实例对象更新数据库中的数据,结果以Promise形式返回。
- values:以ValuesBucket存储的要更新的数据。
- rdbPredicates:表示RdbPredicates的实例对象指定的更新条件。 | + +- **删除** + 调用删除接口,通过RdbPredicates指定删除条件。该接口的返回值表示删除的数据行数,可根据此值判断是否删除成功。如果删除失败,则返回0。 + + **表4** 数据库删除API + + | 类名 | 接口名 | 描述 | + | -------- | -------- | -------- | + | RdbStore | delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void | 根据rdbPredicates的指定实例对象从数据库中删除数据,结果以callback形式返回。
- rdbPredicates:RdbPredicates的实例对象指定的删除条件。
- callback:指定callback回调函数。返回受影响的行数。 | + | RdbStore | delete(rdbPredicates: RdbPredicates): Promise | 根据rdbPredicates的指定实例对象从数据库中删除数据,结果以Promise形式返回。
- rdbPredicates:RdbPredicates的实例对象指定的删除条件。 | + +- **查询** + 关系型数据库提供了两种查询数据的方式: + + - 直接调用查询接口。使用该接口,会将包含查询条件的谓词自动拼接成完整的SQL语句进行查询操作,无需用户传入原生的SQL语句。 + - 执行原生的SQL语句进行查询操作。 + + **表5** 数据库查询API + + | 类名 | 接口名 | 描述 | + | -------- | -------- | -------- | + | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array, callback: AsyncCallback<ResultSet>): void | 根据指定条件查询数据库中的数据,结果以callback形式返回。
- rdbPredicates:表示RdbPredicates的实例对象指定的查询条件。
- columns:表示要查询的列。如果值为空,则查询应用于所有列。
- callback:指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + | RdbStore | query(rdbPredicates: RdbPredicates, columns: Array): Promise<ResultSet> | 根据指定条件查询数据库中的数据,结果以Promise形式返回。
- rdbPredicates:表示RdbPredicates的实例对象指定的查询条件。
- columns:表示要查询的列。如果值为空,则查询应用于所有列。 | + | RdbStore | querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void | 根据指定SQL语句查询数据库中的数据,结果以callback形式返回。
- sql:指定要查询的SQL语句。
- bindArgs:SQL语句中参数的值。
- callback:指定callback回调函数。如果操作成功,则返回ResultSet对象。 | + | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>):Promise<ResultSet> | 根据指定SQL语句查询数据库中的数据,结果以Promise形式返回。
- sql:指定要查询的SQL语句。
- bindArgs:SQL语句中参数的值。 | + +**数据库谓词的使用** + +关系型数据库提供了用于设置数据库操作条件的谓词RdbPredicates,该类确定RDB中条件表达式的值是true还是false。 + +**表6** 数据库谓词API + +| 类名 | 接口名 | 描述 | +| -------- | -------- | -------- | +| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值等于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且值不等于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | beginWrap(): RdbPredicates | 向谓词添加左括号。
- RdbPredicates:返回带有左括号的谓词。 | +| RdbPredicates | endWrap(): RdbPredicates | 向谓词添加右括号。
- RdbPredicates:返回带有右括号的谓词。 | +| RdbPredicates | or(): RdbPredicates | 将或条件添加到谓词中。
- RdbPredicates:返回带有或条件的谓词。 | +| RdbPredicates | and(): RdbPredicates | 向谓词添加和条件。
- RdbPredicates:返回带有和条件的谓词。 | +| RdbPredicates | contains(field: string, value: string): RdbPredicats | 配置谓词以匹配数据字段为String且value包含指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回带有包含条件的谓词。 | +| RdbPredicates | beginsWith(field: string, value: string): RdbPredicates | 配置谓词以匹配数据字段为String且值以指定字符串开头的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | endsWith(field: string, value: string): RdbPredicates | 配置谓词以匹配数据字段为String且值以指定字符串结尾的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | isNull(field: string): RdbPredicates | 配置谓词以匹配值为null的字段。
- field:数据库表中的列名。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | isNotNull(field: string): RdbPredicates | 配置谓词以匹配值不为null的指定字段。
- field:数据库表中的列名。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | like(field: string, value: string): RdbPredicates | 配置谓词以匹配数据字段为String且值类似于指定字符串的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | glob(field: string, value: string): RdbPredicates | 配置RdbPredicates匹配数据字段为String的指定字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | between(field: string, low: ValueType, high: ValueType): RdbPredicates | 将谓词配置为匹配数据字段为ValueType且value在给定范围内的指定字段。
- field:数据库表中的列名。
- low:指示与谓词匹配的最小值。
- high:指示与谓词匹配的最大值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates | 配置RdbPredicates以匹配数据字段为ValueType且value超出给定范围的指定字段。
- field:数据库表中的列名。
- low:指示与谓词匹配的最小值。
- high:指示与谓词匹配的最大值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | greaterThan(field: string, value: ValueType): RdbPredicatesgr | 配置谓词以匹配数据字段为ValueType且值大于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | lessThan(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为valueType且value小于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且value大于或等于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates | 配置谓词以匹配数据字段为ValueType且value小于或等于指定值的字段。
- field:数据库表中的列名。
- value:指示要与谓词匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | orderByAsc(field: string): RdbPredicates | 配置谓词以匹配其值按升序排序的列。
- field:数据库表中的列名。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | orderByDesc(field: string): RdbPredicates | 配置谓词以匹配其值按降序排序的列。
- field:数据库表中的列名。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | distinct(): RdbPredicates | 配置谓词以过滤重复记录并仅保留其中一个。
- RdbPredicates:返回可用于过滤重复记录的谓词。 | +| RdbPredicates | limitAs(value: number): RdbPredicates | 设置最大数据记录数的谓词。
- value:最大数据记录数。
- RdbPredicates:返回可用于设置最大数据记录数的谓词。 | +| RdbPredicates | offsetAs(rowOffset: number): RdbPredicates | 配置RdbPredicates以指定返回结果的起始位置。
- rowOffset:返回结果的起始位置,取值为正整数。
- RdbPredicates:返回具有指定返回结果起始位置的谓词。 | +| RdbPredicates | groupBy(fields: Array<string>): RdbPredicates | 配置RdbPredicates按指定列分组查询结果。
- fields:指定分组依赖的列名。
- RdbPredicates:返回分组查询列的谓词。 | +| RdbPredicates | indexedBy(indexName: string): RdbPredicates | 配置RdbPredicates以指定索引列。
- indexName:索引列的名称。
- RdbPredicates:返回具有指定索引列的RdbPredicates。 | +| RdbPredicates | in(field: string, value: Array<ValueType>): RdbPredicates | 配置RdbPredicates以匹配数据字段为ValueType数组且值在给定范围内的指定字段。
- field:数据库表中的列名。
- value:以ValueType型数组形式指定的要匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | +| RdbPredicates | notIn(field: string, value: Array<ValueType>): RdbPredicates | 将RdbPredicates配置为匹配数据字段为ValueType且值超出给定范围的指定字段。
- field:数据库表中的列名。
- value:以ValueType型数组形式指定的要匹配的值。
- RdbPredicates:返回与指定字段匹配的谓词。 | + +**查询结果集的使用** + +关系型数据库提供了查询返回的结果集ResultSet,其指向查询结果中的一行数据,供用户对查询结果进行遍历和访问。ResultSet对外API如下所示。 + +> ![icon-notice.gif](public_sys-resources/icon-notice.gif) **须知:** +> **注:结果集使用完后,请一定要调用close方法显式关闭。** + +**表7** 结果集API + +| 类名 | 接口名 | 描述 | +| -------- | -------- | -------- | +| ResultSet | goTo(offset:number): boolean | 从结果集当前位置移动指定偏移量。 | +| ResultSet | goToRow(position: number): boolean | 将结果集移动到指定位置。 | +| ResultSet | goToNextRow(): boolean | 将结果集向后移动一行。 | +| ResultSet | goToPreviousRow(): boolean | 将结果集向前移动一行。 | +| ResultSet | getColumnIndex(columnName: string): number | 根据指定的列名获取列索引。 | +| ResultSet | getColumnName(columnIndex: number): string | 根据指定的列索引获取列名。 | +| ResultSet | goToFirstRow(): boolean | 判断结果集当前位置是否在第一行。 | +| ResultSet | goToLastRow(): boolean | 判断结果集当前位置是否在最后一行。 | +| ResultSet | getString(columnIndex: number): string | 获取当前行指定列的值,以String类型返回。 | +| ResultSet | getBlob(columnIndex: number): Uint8Array | 获取当前行指定列的值,以字节数组形式返回。 | +| ResultSet | getDouble(columnIndex: number): number | 获取当前行指定列的值,以double型返回。 | +| ResultSet | isColumnNull(columnIndex: number): boolean | 检查当前行中指定列的值是否为null。 | +| ResultSet | close(): void | 关闭结果集。 | + +**数据库更改秘钥** + +用户可以对当前数据库进行加密。 + +数据库的加密仅限于初始使用一个数据库时就进行加密,使用过程中进行秘钥的变更,但不支持取消秘钥。 + +数据库初始时为加密库,则一直为加密库;初始时为未加密库,则一直为未加密库。 + +**表8** 数据库更改秘钥 + +| 类名 | 接口名 | 描述 | +| -------- | -------- | -------- | +| RdbStore | changeEncryptKey(newEncryptKey:Uint8Array, callback: AsyncCallback<number>):void; | 数据库更改秘钥接口,通过callback 可以异步处理返回结果。返回结果0成功,非0失败。 | +| RdbStore | changeEncryptKey(newEncryptKey:Uint8Array): Promise<number>; | 数据库更改秘钥接口,通过await 可以同步处理返回结果。返回结果0成功,非0失败。 | + + +## 开发步骤 + +1. 创建数据库。 + 1. 配置数据库相关信息,包括数据库的名称、存储模式、是否为只读模式等。 + 2. 初始化数据库表结构和相关数据。 + 3. 创建数据库。 + + 示例代码如下: + + ``` + import dataRdb from '@ohos.data.rdb'; + + const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; + const STORE_CONFIG = {name: "rdbstore.db",} + + let rdbStore = await dataRdb.getRdbStore(STORE_CONFIG, 1); + await rdbStore.executeSql(CREATE_TABLE_TEST); + ``` + +2. 插入数据。 + 1. 构造要插入的数据,以ValuesBucket形式存储。 + 2. 调用关系型数据库提供的插入接口。 + + 示例代码如下: + + ``` + var u8 = new Uint8Array([1, 2, 3]) + const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8,} + let insertPromise = rdbStore.insert("test", valueBucket) + ``` + +3. 查询数据。 + 1. 构造用于查询的谓词对象,设置查询条件。 + 2. 调用查询接口查询数据。 + 3. 调用结果集接口,返回查询结果。 + + 示例代码如下: + + ``` + let predicates = new dataRdb.RdbPredicates("test"); + predicates.equalTo("name", "Tom") + let resultSet = await rdbStore.query(predicates) + + resultSet.goToFirstRow() + const id = await resultSet.getLong(resultSet.getColumnIndex("id")) + const name = await resultSet.getString(resultSet.getColumnIndex("name")) + const age = await resultSet.getLong(resultSet.getColumnIndex("age")) + const salary = await resultSet.getDouble(resultSet.getColumnIndex("salary")) + const blobType = await resultSet.getBlob(resultSet.getColumnIndex("blobType")) + + resultSet.close() + ``` diff --git a/zh-cn/application-dev/database/database-relational-overview.md b/zh-cn/application-dev/database/database-relational-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..f9a84f85a03efcda86bac16424ecb82bfbe108de --- /dev/null +++ b/zh-cn/application-dev/database/database-relational-overview.md @@ -0,0 +1,41 @@ +# 关系型数据库概述 + +关系型数据库(Relational Database,RDB)是一种基于关系模型来管理数据的数据库。关系型数据库基于SQLite组件提供了一套完整的对本地数据库进行管理的机制,对外提供了一系列的增、删、改、查等接口,也可以直接运行用户输入的SQL语句来满足复杂的场景需要。 + +## 基本概念 + +- **关系型数据库** + + 基于关系模型来管理数据的数据库,以行和列的形式存储数据。 + +- **谓词** + + 数据库中用来代表数据实体的性质、特征或者数据实体之间关系的词项,主要用来定义数据库的操作条件。 + +- **结果集** + + 指用户查询之后的结果集合,可以对数据进行访问。结果集提供了灵活的数据访问方式,可以更方便的拿到用户想要的数据。 + +- **SQLite数据库** + + 一款遵守ACID的轻型开源关系型数据库管理系统。 + +## 运作机制 + +关系型数据库对外提供通用的操作接口,底层使用SQLite作为持久化存储引擎,支持SQLite具有的所有数据库特性,包括但不限于事务、索引、视图、触发器、外键、参数化查询和预编译SQL语句。 + +**图1** 关系型数据库运作机制 + +![how-rdb-works](figures/how-rdb-works.png) + +## 默认配置 + +- 如果不指定数据库的日志模式,那么系统默认日志方式是WAL(Write Ahead Log)模式。 +- 如果不指定数据库的落盘模式,那么系统默认落盘方式是FULL模式。 +- OpenHarmony数据库使用的共享内存默认大小是2MB。 + +## 约束与限制 + +- 数据库中连接池的最大数量是4个,用以管理用户的读操作。 + +- 为保证数据的准确性,数据库同一时间只能支持一个写操作。 \ No newline at end of file diff --git a/zh-cn/application-dev/database/figures/how-rdb-works.png b/zh-cn/application-dev/database/figures/how-rdb-works.png new file mode 100644 index 0000000000000000000000000000000000000000..e85411eef39281e3213d6b4697a8d32d2cecd9a2 Binary files /dev/null and b/zh-cn/application-dev/database/figures/how-rdb-works.png differ diff --git a/zh-cn/application-dev/database/figures/zh-cn_image_0000001199139454.png b/zh-cn/application-dev/database/figures/zh-cn_image_0000001199139454.png new file mode 100644 index 0000000000000000000000000000000000000000..5a6f6879944d0fda3cc24d7e726c842c74476728 Binary files /dev/null and b/zh-cn/application-dev/database/figures/zh-cn_image_0000001199139454.png differ diff --git a/zh-cn/application-dev/media/figures/zh-ch_image_20220117.jpg b/zh-cn/application-dev/media/figures/zh-ch_image_20220117.jpg index bc56b9d8395873193bbad2b3faf7340c6728af60..8fba3a7beeb4efc7599dde3f32b228135ed92fce 100644 Binary files a/zh-cn/application-dev/media/figures/zh-ch_image_20220117.jpg and b/zh-cn/application-dev/media/figures/zh-ch_image_20220117.jpg differ diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 5557c9c32d412e58e064db9b9592e65f7e15019c..16286defa11112818f3dac92860a7e2004849493 100644 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -32,6 +32,9 @@ - [文件管理](js-apis-fileio.md) - [Statfs](js-apis-statfs.md) - [目录环境](js-apis-environment.md) + - [公共文件访问与管理](js-apis-filemanager.md) + - [应用空间统计](js-apis-storage-statistics.md) + - [卷管理](js-apis-volumemanager.md) - 账号管理 - [分布式帐号管理](js-apis-distributed-account.md) - [应用帐号管理](js-apis-appAccount.md) @@ -69,6 +72,7 @@ - [性能打点](js-apis-hitracemeter.md) - [故障日志获取](js-apis-faultLogger.md) - [分布式跟踪](js-apis-hitracechain.md) + - [日志打印](js-apis-hilog.md) - 语言基础类库 - [获取进程相关的信息](js-apis-process.md) - [URL字符串解析](js-apis-url.md) @@ -77,4 +81,18 @@ - [xml解析与生成](js-apis-xml.md) - [xml转换JavaScript](js-apis-convertxml.md) - [启动一个worker](js-apis-worker.md) + - [线性容器ArrayList](js-apis-arraylist.md) + - [线性容器Deque](js-apis-deque.md) + - [线性容器List](js-apis-list.md) + - [线性容器LinkedList](js-apis-linkedlist.md) + - [线性容器Queue](js-apis-queue.md) + - [线性容器Stack](js-apis-stack.md) + - [线性容器Vector](js-apis-vector.md) + - [非线性容器HashSet](js-apis-hashset.md) + - [非线性容器HashMap](js-apis-hashmap.md) + - [非线性容器PlainArray](js-apis-plainarray.md) + - [非线性容器TreeMap](js-apis-treemap.md) + - [非线性容器TreeSet](js-apis-treeset.md) + - [非线性容器LightWeightMap](js-apis-lightweightmap.md) + - [非线性容器LightWeightSet](js-apis-lightweightset.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md index 537dc263d18ec8b7359b849a063d4f133774a305..38e22506315711bdc156e56523ad76a3998d0ac8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md @@ -11,6 +11,11 @@ import account_appAccount from '@ohos.account.appAccount'; ``` +## 系统能力 + +SystemCapability.Account.AppAccount + + ## account_appAccount.createAppAccountManager createAppAccountManager(): AppAccountManager; @@ -114,6 +119,47 @@ addAccount(name: string, extraInfo?: string): Promise<void>; }); ``` +### addAccountImplicitly8+ + +addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void; + +根据指定的帐号所有者、鉴权类型和可选项,隐式地添加应用帐号,并使用callback回调异步返回结果。 + +需要权限:无。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | --------------------- | --- | -------------------------- | + | owner | string | 是 | 要添加的应用帐户的所有者包名。 | + | authType | string | 是 | 要添加的应用帐户的鉴权类型。 | + | options | {[key: string]: any} | 是 | 鉴权所需要的可选项。 | + | callback | AuthenticatorCallback | 是 | 认证器回调,用于返回鉴权结果。 | + +- 示例: + + ``` + import featureAbility from '@ohos.ability.featureAbility'; + + function onResultCallback(code, result) { + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); + } + + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err)=>{ + console.log("startAbility err: " + JSON.stringify(err)); + }); + } + + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccountImplicitly("LiSi", "readAge", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + ``` + ### deleteAccount deleteAccount(name: string, callback: AsyncCallback<void>): void; @@ -872,12 +918,739 @@ off(type: 'change', callback?: Callback<void>): void; } ``` +### authenticate8+ + +authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void; + +鉴权应用帐户以获取OAuth令牌,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | --------------------- | ---- | --------------------------- | + | name | string | 是 | 要鉴权的应用帐户的名称。 | + | owner | string | 是 | 要鉴权的应用帐户的所有者包名。 | + | authType | string | 是 | 鉴权类型。 | + | options | {[key: string]: any} | 是 | 鉴权所需的可选项。 | + | callback | AuthenticatorCallback | 是 | 认证器回调,用于返回鉴权结果。 | + +- 示例: + + ``` + import featureAbility from '@ohos.ability.featureAbility'; + + function onResultCallback(code, result) { + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); + } + + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err)=>{ + console.log("startAbility err: " + JSON.stringify(err)); + }); + } + + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "readAge", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + ``` + +### getOAuthToken8+ + +getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void; + +获取指定应用帐户和鉴权类型的OAuth令牌,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | --------------------------- | ---- | -------------------- | + | name | string | 是 | 应用帐户的名称。 | + | owner | string | 是 | 应用帐户的所有者包名。 | + | authType | string | 是 | 鉴权类型。 | + | callback | AsyncCallback<string> | 是 | 查询结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", (err, data) => { + console.log('getOAuthToken err: ' + JSON.stringify(err)); + console.log('getOAuthToken token: ' + data); + }); + ``` + +### getOAuthToken8+ + +getOAuthToken(name: string, owner: string, authType: string): Promise<string>; + +获取指定应用帐户和鉴权类型的OAuth令牌,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------ | ---- | -------------------- | + | name | string | 是 | 应用帐户的名称。 | + | owner | string | 是 | 应用帐户的所有者包名。 | + | authType | string | 是 | 鉴权类型。 | + +- 参数: + + | 类型 | 说明 | + | --------------------- | -------------------------------- | + | Promise<string> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge").then((data) => { + console.log('getOAuthToken token: ' + data); + }).catch((err) => { + console.log("getOAuthToken err: " + JSON.stringify(err)); + }); + ``` + +### setOAuthToken8+ + +setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void; + +设置指定应用帐户和鉴权类型的OAuth令牌,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------------- | ---- | ------------- | + | name | string | 是 | 应用帐户的名称。 | + | authType | string | 是 | 鉴权类型。 | + | token | string | 是 | OAuth令牌。 | + | callback | AsyncCallback<void> | 是 | 设置结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx", (err) => { + console.log('setOAuthToken err: ' + JSON.stringify(err)); + }); + ``` + +### setOAuthToken8+ + +setOAuthToken(name: string, authType: string, token: string): Promise<void>; + +设置指定应用帐户和鉴权类型的OAuth令牌,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------ | ---- | ------------- | + | name | string | 是 | 应用帐户的名称。 | + | authType | string | 是 | 鉴权类型。 | + | token | string | 是 | OAuth令牌。 | + +- 参数: + + | 类型 | 说明 | + | ------------------- | -------------------------------- | + | Promise<void> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthToken("LiSi", "readAge", "xxxx").then(() => { + console.log('setOAuthToken successfully'); + }).catch((err) => { + console.log('setOAuthToken err: ' + JSON.stringify(err)); + }); + ``` + +### deleteOAuthToken8+ + +deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void; + +删除指定应用帐户和鉴权类型的OAuth令牌,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------------- | ---- | ------------------ | + | name | string | 是 | 应用帐户的名称。 | + | owner | string | 是 | 应用帐户的所有者包名。 | + | authType | string | 是 | 鉴权类型。 | + | token | string | 是 | 要删除的OAuth令牌。 | + | callback | AsyncCallback<void> | 是 | 删除结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx", (err) => { + console.log('deleteOAuthToken err: ' + JSON.stringify(err)); + }); + ``` + +### deleteOAuthToken8+ + +deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void>; + +删除指定应用帐户和鉴权类型的OAuth令牌,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------ | ---- | ------------------ | + | name | string | 是 | 应用帐户的名称。 | + | owner | string | 是 | 应用帐户的所有者包名。 | + | authType | string | 是 | 鉴权类型。 | + | token | string | 是 | 要删除的OAuth令牌。 | + +- 参数: + + | 类型 | 说明 | + | ------------------------------ | --------------------- | + | Promise<void> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "readAge", "xxxxx").then(() => { + console.log('deleteOAuthToken successfully'); + }).catch((err) => { + console.log("deleteOAuthToken err: " + JSON.stringify(err)); + }); + ``` + +### setOAuthTokenVisibility8+ + +setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void; + +设置指定鉴权类型的OAuth令牌对特定应用的可见性,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ------------------------- | ---- | ------------------- | + | name | string | 是 | 应用帐户的名称。 | + | authType | string | 是 | 鉴权类型。 | + | bundleName | string | 是 | 被设置可见性的应用包名。| + | isVisible | boolean | 是 | 是否可见。 | + | callback | AsyncCallback<void> | 是 | 设置结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err) => { + console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); + }); + ``` + +### setOAuthTokenVisibility8+ + +setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void>; + +设置指定鉴权类型的OAuth令牌对特定应用的可见性,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ------------------------- | ---- | ------------------- | + | name | string | 是 | 应用帐户的名称。 | + | authType | string | 是 | 鉴权类型。 | + | bundleName | string | 是 | 被设置可见性的应用包名。| + | isVisible | boolean | 是 | 是否可见。 | + +- 参数: + + | 类型 | 说明 | + | ------------------------------ | --------------------- | + | Promise<void> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then(() => { + console.log('setOAuthTokenVisibility successfully'); + }).catch((err) => { + console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); + }); + ``` + +### checkOAuthTokenVisibility8+ + +checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void; + +检查指定鉴权类型的OAuth令牌对特定应用的可见性,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ---------------------------- | ---- | ---------------------- | + | name | string | 是 | 应用帐户的名称。 | + | authType | string | 是 | 鉴权类型。 | + | bundleName | string | 是 | 用于检查可见性的应用包名。 | + | callback | AsyncCallback<boolean> | 是 | 检查结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true, (err, data) => { + console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log('checkOAuthTokenVisibility isVisible: ' + data); + }); + ``` + +### checkOAuthTokenVisibility8+ + +checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean>; + +检查指定鉴权类型的OAuth令牌对特定应用的可见性,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ------------------------- | ---- | ---------------------- | + | name | string | 是 | 应用帐户的名称。 | + | authType | string | 是 | 鉴权类型。 | + | bundleName | string | 是 | 用于检查可见性的应用包名。 | + +- 参数: + + | 类型 | 说明 | + | ------------------------------ | ------------------------ | + | Promise<boolean> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkOAuthTokenVisibility("LiSi", "readAge", "com.example.ohos.accountjsdemo", true).then((data) => { + console.log('checkOAuthTokenVisibility isVisible: ' + data); + }).catch((err) => { + console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); + }); + ``` + +### getAllOAuthTokens8+ + +getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void; + +获取指定应用对调用方全部可见的OAuth令牌,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------------------------------------ | ---- | ------------------- | + | name | string | 是 | 应用帐户的名称。 | + | owner | string | 是 | 应用帐户的所有者包名。 | + | callback | AsyncCallback<Array<OAuthTokenInfo>> | 是 | 查询结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo", (err, data) => { + console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); + }); + ``` + +### getAllOAuthTokens8+ + +getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>>; + +获取指定应用帐户对调用方可见的全部OAuth令牌,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------ | ---- | ------------------- | + | name | string | 是 | 应用帐户的名称。 | + | owner | string | 是 | 应用帐户的所有者包名。 | + +- 参数: + + | 类型 | 说明 | + | ------------------------------ | ----------------------------------- | + | Promise<Array<OAuthTokenInfo>> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + }); + ``` + +### getOAuthList8+ + +getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void; + +获取指定应用帐户和鉴权类型的OAuth令牌的授权列表,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ---------------------------------------- | ---- | ------------------ | + | name | string | 是 | 应用帐户的名称。 | + | owner | string | 是 | 应用帐户的所有者包名。 | + | callback | AsyncCallback<Array<string>> | 是 | 查询结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge", (err, data) => { + console.log('getOAuthList err: ' + JSON.stringify(err)); + console.log('getOAuthList data: ' + JSON.stringify(data)); + }); + ``` + +### getOAuthList8+ + +getOAuthList(name: string, authType: string): Promise<Array<string>>; + +获取指定应用帐户和鉴权类型的OAuth令牌的授权列表,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------ | ---- | ------------------- | + | name | string | 是 | 应用帐户的名称。 | + | owner | string | 是 | 应用帐户的所有者包名。 | + +- 参数: + + | 类型 | 说明 | + | ------------------------------ | ------------------------------------ | + | Promise<Array<string>> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "readAge").then((data) => { + console.log('getOAuthList data: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getOAuthList err: " + JSON.stringify(err)); + }); + ``` + +### getAuthenticatorCallback8+ + +getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<AuthenticatorCallback>): void; + +获取鉴权会话的认证器回调,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | --------- | ------------------------------------------ | ---- | -------------- | + | sessionId | string | 是 | 鉴权会话的标识。 | + | callback | AsyncCallback<AuthenticatorCallback> | 是 | 查询结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant((err, want) => { + var sessionId = want.parameters[Constants.KEY_SESSION_ID]; + appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { + if (err.code != ResultCode.SUCCESS) { + console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + return; + } + var result = {Constants.KEY_NAME: "LiSi", Constants.KEY_OWNER: "com.example.ohos.accountjsdemo", + Constants.KEY_AUTH_TYPE: "readAge", Constants.KEY_TOKEN: "xxxxxx"}; + callback.OnResult(ResultCode.SUCCESS, result); + }); + }); + ``` + +### getAuthenticatorCallback8+ + +getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback>; + +获取鉴权会话的认证器回调,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ------ | ---- | -------------- | + | sessionId | string | 是 | 鉴权会话的标识。 | + +- 参数: + + | 类型 | 说明 | + | ------------------------------------ | -------------------------------- | + | Promise<AuthenticatorCallback> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant().then((want) => { + var sessionId = want.parameters[Constants.KEY_SESSION_ID]; + appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { + var result = {Constants.KEY_NAME: "LiSi", Constants.KEY_OWNER: "com.example.ohos.accountjsdemo", + Constants.KEY_AUTH_TYPE: "readAge", Constants.KEY_TOKEN: "xxxxxx"}; + callback.OnResult(ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + }); + }).catch((err) => { + console.log("getWant err: " + JSON.stringify(err)); + }); + ``` + +### getAuthenticatorInfo8+ + +getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void; + +获取指定应用帐户的认证器信息,使用callback回调异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------------------------------------- | ---- | ------------------- | + | owner | string | 是 | 应用帐户的所有者包名。 | + | callback | AsyncCallback<AuthenticatorInfo> | 是 | 查询结果的回调。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo", (err, data) => { + console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); + }); + ``` + +### getAuthenticatorInfo8+ + +getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo>; + +获取指定应用帐户的认证器信息,使用Promise方式异步返回结果。 + +- 参数: + + | 参数名 | 类型 | 必填 | 说明 | + | ----- | ------ | ---- | -------------------- | + | owner | string | 是 | 应用帐户的所有者包名。 | + +- 参数: + + | 类型 | 说明 | + | ------------------------------ | ----------------------------------- | + | Promise<AuthenticatorInfo> | Promise实例,用于获取异步返回结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { + console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + }); + ``` + ## AppAccountInfo +表示应用帐号信息。 + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ---------------- | +| owner | string | 是 | 应用帐户的所有者包名。 | +| name | string | 是 | 应用帐户的名称。 | + +## OAuthTokenInfo8+ + +表示OAuth令牌信息。 + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | -------------- | +| authType | string | 是 | 令牌的鉴权类型。 | +| token | string | 是 | 令牌的取值。 | + +## AuthenticatorInfo8+ + +表示OAuth认证器信息。 + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | ------ | ---- | ------------------ | +| owner | string | 是 | 认证器的所有者包名。 | +| iconId | string | 是 | 认证器的图标标识。 | +| labelId | string | 是 | 认证器的标签标识。 | + +## Constants8+ + +表示常量的枚举。 + +| 名称 | 默认值 | 描述 | +| ----------------------------- | ---------------------- | ----------------------- | +| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | 表示操作_隐式添加帐号。 | +| ACTION_AUTHENTICATE | "authenticate" | 表示操作_鉴权。 | +| KEY_NAME | "name" | 表示键名_应用帐户名称。 | +| KEY_OWNER | "owner" | 表示键名_应用帐户所有者。 | +| KEY_TOKEN | "token" | 表示键名_令牌。 | +| KEY_ACTION | "action" | 表示键名_操作。 | +| KEY_AUTH_TYPE | "authType" | 表示键名_鉴权类型。 | +| KEY_SESSION_ID | "sessionId" | 表示键名_会话标识。 | +| KEY_CALLER_PID | "callerPid" | 表示键名_调用方PID。 | +| KEY_CALLER_UID | "callerUid" | 表示键名_调用方UID。 | +| KEY_CALLER_BUNDLE_NAME | "callerBundleName" | 表示键名_调用方包名。 | + +## ResultCode8+ +表示返回码的枚举。 -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------ | ---- | ------------------ | -| owner | string | 是 | 所有者是应用帐户。 | -| name | string | 是 | 应用帐户的名称。 | +| 名称 | 默认值 | 描述 | +| ----------------------------------- | ----- | ---------------------- | +| SUCCESS | 0 | 表示操作成功。 | +| ERROR_ACCOUNT_NOT_EXIST | 10001 | 表示应用帐户不存在。 | +| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | 表示应用帐户服务异常。 | +| ERROR_INVALID_PASSWORD | 10003 | 表示密码无效。 | +| ERROR_INVALID_REQUEST | 10004 | 表示请求无效。 | +| ERROR_INVALID_RESPONSE | 10005 | 表示响应无效。 | +| ERROR_NETWORK_EXCEPTION | 10006 | 表示网络异常。 | +| ERROR_OAUTH_AUTHENTICATOR_NOT_EXIST | 10007 | 表示认证器不存在。 | +| ERROR_OAUTH_CANCELED | 10008 | 表示鉴权取消。 | +| ERROR_OAUTH_LIST_TOO_LARGE | 10009 | 表示开放授权列表过大。 | +| ERROR_OAUTH_SERVICE_BUSY | 10010 | 表示开放授权服务忙碌。 | +| ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | 表示开放授权服务异常。 | +| ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | 表示鉴权会话不存在。 | +| ERROR_OAUTH_TIMEOUT | 10013 | 表示鉴权超时。 | +| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | 表示开放授权令牌不存在。 | +| ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | 表示开放授权令牌过多。 | +| ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | 表示不支持的鉴权操作。 | +| ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | 表示不支持的鉴权类型。 | +| ERROR_PERMISSION_DENIED | 10018 | 表示权限不足。 | +## AuthenticatorCallback8+ + +OAuth认证器回调接口。 + +### onResult8+ + +onResult: (code: number, result: {[key: string]: any}) => void; + +通知鉴权结果。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | ------ | -------------------- | ---- | ----------- | + | code | number | 是 | 鉴权结果码。 | + | result | {[key: string]: any} | 是 | 鉴权结果。 | + +- 示例: + + ``` + const appAccountManager = account_appAccount.createAppAccountManager(); + var sessionId = "1234"; + appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { + var result = {Constants.KEY_NAME: "LiSi", Constants.KEY_OWNER: "com.example.ohos.accountjsdemo", + Constants.KEY_AUTH_TYPE: "readAge", Constants.KEY_TOKEN: "xxxxxx"}; + callback.OnResult(ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + }); + ``` + +### onRequestRedirected8+ + +onRequestRedirected: (request: Want) => void; + +通知鉴权请求被跳转。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | ------- | ---- | ---- | ------------------ | + | request | Want | 是 | 用于跳转的请求信息。 | + +- 示例: + + ``` + class MyAuthenticator extends account_appAccount.Authenticator { + addAccountImplicitly(authType, callerBundleName, options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.ohos.accountjsdemo", + abilityName: "com.example.ohos.accountjsdemo.LoginAbility", + }); + } + + authenticate(name, authType, callerBundleName, options, callback) { + var result = {Constants.KEY_NAME: name, Constants.KEY_AUTH_TYPE: authType, Constants.KEY_TOKEN: "xxxxxx"}; + callback.onResult(ResultCode.SUCCESS, result); + } + } + ``` + +## Authenticator8+ + +OAuth认证器基类。 + +### addAccountImplicitly8+ + +addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void; + +根据指定的鉴权类型和可选项,隐式地添加应用帐户,并使用callback回调异步返回结果。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | ---------------- | --------------------- | --- | -------------------------- | + | authType | string | 是 | 应用帐户的鉴权类型。 | + | callerBundleName | string | 是 | 鉴权请求方的包名。 | + | options | {[key: string]: any} | 是 | 鉴权所需要的可选项。 | + | callback | AuthenticatorCallback | 是 | 认证器回调,用于返回鉴权结果。 | + +### authenticate8+ + +authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void; + +对应用帐户进行鉴权,获取OAuth令牌,并使用callback回调异步返回结果。 + +- 参数: + | 接口名 | 类型 | 必填 | 说明 | + | ---------------- | --------------------- | ---- | -------------------------- | + | name | string | 是 | 应用帐户的名称。 | + | authType | string | 是 | 应用帐户的鉴权类型。 | + | callerBundleName | string | 是 | 鉴权请求方的包名。 | + | options | {[key: string]: any} | 是 | 鉴权所需要的可选项。 | + | callback | AuthenticatorCallback | 是 | 认证器回调,用于返回鉴权结果。 | + +- 示例: + + ``` + class MyAuthenticator extends account_appAccount.Authenticator { + addAccountImplicitly(authType, callerBundleName, options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.ohos.accountjsdemo", + abilityName: "com.example.ohos.accountjsdemo.LoginAbility", + }); + } + + authenticate(name, authType, callerBundleName, options, callback) { + var result = {Constants.KEY_NAME: name, Constants.KEY_AUTH_TYPE: authType, Constants.KEY_TOKEN: "xxxxxx"}; + callback.onResult(ResultCode.SUCCESS, result); + } + } + + export default { + onConnect(want) { + return new MyAuthenticator(); + } + } + ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-arraylist.md b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md new file mode 100644 index 0000000000000000000000000000000000000000..059e706a5eda43e0590af517bfd71fea862efb07 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-arraylist.md @@ -0,0 +1,518 @@ +# 线性容器ArrayList + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +``` +import ArrayList from '@ohos.util.ArrayList' +``` + +## 权限 + +无 + +## ArrayList + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | ArrayList的元素个数 | + + +### constructor + +constructor(); + +ArrayList的构造函数。 + +- 示例: + ``` + let arrayList = new ArrayList(); + ``` + + +### add + +add(element: T): boolean; + +在ArrayList尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add("a"); + arrayList.add(1); + let b = [1, 2, 3]; + arrayList.add(b); + let c = {name: "lala", age: "13"}; + arrayList.add(false); + ``` + +### insert + +insert(element: T, index: number): void; + +在长度范围内任意位置插入指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 被插入的元素 | + | index | number | 是 | 被插入的位置索引 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.insert("A", 0); + arrayList.insert(0, 1); + arrayList.insert(true, 2); + ``` + +### has + +has(element: T): boolean; + +判断此ArrayList中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + arrayList.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + arrayList.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + +### getIndexOf + +getIndexOf(element: T): number; + +返回指定元素第一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(2); + arrayList.add(1); + arrayList.add(2); + arrayList.add(4); + arrayList.getIndexOf(2); + ``` +### getLastIndexOf + +getLastIndexOf(element: T): number; + +返回指定元素最后一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素最后一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(2); + arrayList.add(1); + arrayList.add(2); + arrayList.add(4); + arrayList.getLastIndexOf(2); + ``` +### removeByIndex + +removeByIndex(index: number): T; + +根据元素的下标值查找元素,返回元素后将其删除。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定元素的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(2); + arrayList.add(4); + arrayList.removeByIndex(2); + ``` + +### remove + +remove(element: T): boolean; + +删除查找到的第一个指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.remove(2); + ``` + +### removeByRange + +removeByRange(fromIndex: number, toIndex: number): void; + +从一段范围内删除元素,包括起始值但不包括终止值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.removeByRange(2, 4); + arrayList.removeByRange(4, 3); + arrayList.removeByRange(2, 6); + ``` +### replaceAllElements +replaceAllElements(callbackfn: (value: T, index?: number, arraylist?: ArrayList<T>) => T, +thisArg?: Object): void; + +用户操作ArrayList中的元素,用操作后的元素替换原元素并返回操作后的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | arraylist | ArrayList<T> | 否 | 当前调用replaceAllElements方法的实例对象 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.replaceAllElements((value, index) => { + return value = 2 * value; + }); + arrayList.replaceAllElements((value, index) => { + return value = value - 2; + }); + ``` +### forEach +forEach(callbackfn: (value: T, index?: number, arraylist?: ArrayList<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历ArrayList实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数。 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素。 | + | index | number | 否 | 当前遍历到的下标值。 | + | arraylist | ArrayList<T> | 否 | 当前调用forEach方法的实例对象。 | + + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.forEach((value, index) => { + console.log(value, index); + }); + ``` +### sort +sort(comparator?: (firstValue: T, secondValue: T) => number): void; + +对ArrayList中的元素进行一个排序操作 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 否 | 回调函数 | + +- comparator的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | firstValue | T | 是 | 前一项元素 | + | secondValue | T | 是 | 后一项元素 | + + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.sort(a, (b => a - b)); + arrayList.sort(a, (b => b - a)); + arrayList.sort(); + ``` +### subArrayList +subArrayList(fromIndex: number, toIndex: number): ArrayList<T>; + +根据下标截取ArrayList中的一段元素,并返回这一段ArrayList实例, 包括起始值但不包括终止值 +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | ArrayList<T> | 返回ArrayList对象实例 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.subArrayList(2, 4); + arrayList.subArrayList(4, 3); + arrayList.subArrayList(2, 6); + ``` + +### clear +clear(): void; + +清除ArrayList中的所有元素,并把length置为0。 + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.clear(); + ``` +### clone +clone(): ArrayList<T> ; + +克隆一个与ArrayList一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | ArrayList<T> | 返回ArrayList对象实例 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.clone(); + ``` +### getCapacity +getCapacity(): number; + +获取当前实例的容量大小。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回arraylist的容量大小 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.getCapacity(); + ``` +### convertToArray +convertToArray(): Array<T>; + +把当前ArrayList实例转换成数组,并返回转换后的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回数组类型 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.convertToArray(); + ``` +### isEmpty +isEmpty(): boolean; + +判断该ArrayList是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.isEmpty(); + ``` +### increaseCapacityTo +increaseCapacityTo(newCapacity: number): void; + +如果传入的新容量大于或等于ArrayList中的元素个数,将容量变更为新容量。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | newCapacity | number | 是 | 新容量 | + + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.increaseCapacityTo(2); + arrayList.increaseCapacityTo(8); + ``` +### trimToCurrentLength +trimToCurrentLength(): void; + +把容量限制为当前的length大小。 + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + arrayList.trimToCurrentLength(2); + ``` +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let arrayList = new ArrayList(); + arrayList.add(2); + arrayList.add(4); + arrayList.add(5); + arrayList.add(4); + + // 使用方法一: + for (let item of arrayList) { + console.log(item); + } + + // 使用方法二: + let iter = arrayList[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 636afc455eb984765269155842edec14c2cfbda5..4369e06d5710ff9b4fcefec08576015c83ebba7b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -7,11 +7,6 @@ import audio from '@ohos.multimedia.audio'; ``` -## 权限 - -无 - - ## getAudioManager getAudioManager(): AudioManager @@ -115,6 +110,7 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err)=>{ if (err) { console.error('Failed to set the volume. ${err.message}'); @@ -146,6 +142,7 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(()=> console.log('Promise returned to indicate a successful volume setting.'); ) @@ -167,6 +164,7 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): v **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the volume. ${err.message}'); @@ -197,6 +195,7 @@ getVolume(volumeType: AudioVolumeType): Promise<number> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => console.log('Promise returned to indicate that the volume is obtained.' + value); ) @@ -218,6 +217,7 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the minimum volume. ${err.message}'); @@ -248,6 +248,7 @@ getMinVolume(volumeType: AudioVolumeType): Promise<number> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => console.log('Promised returned to indicate that the minimum volume is obtained.' + value); ) @@ -269,6 +270,7 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the maximum volume. ${err.message}'); @@ -299,6 +301,7 @@ getMaxVolume(volumeType: AudioVolumeType): Promise<number> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data)=> console.log('Promised returned to indicate that the maximum volume is obtained.'); ) @@ -321,6 +324,7 @@ mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { console.error('Failed to mute the stream. ${err.message}'); @@ -353,6 +357,7 @@ mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> ``` +var audioManager = audio.getAudioManager(); audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => console.log('Promise returned to indicate that the stream is muted.'); ) @@ -375,6 +380,7 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): voi **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the mute status. ${err.message}'); @@ -406,6 +412,7 @@ isMute(volumeType: AudioVolumeType): Promise<boolean> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => console.log('Promise returned to indicate that the mute status of the stream is obtained.' + value); ) @@ -427,6 +434,7 @@ isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): v **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error('Failed to obtain the active status of the stream. ${err.message}'); @@ -457,6 +465,7 @@ isActive(volumeType: AudioVolumeType): Promise<boolean> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => console.log('Promise returned to indicate that the active status of the stream is obtained.' + value); ) @@ -478,6 +487,7 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { console.error('Failed to set the ringer mode.​ ${err.message}'); @@ -508,6 +518,7 @@ setRingerMode(mode: AudioRingMode): Promise<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => console.log('Promise returned to indicate a successful setting of the ringer mode.'); ) @@ -529,6 +540,7 @@ getRingerMode(callback: AsyncCallback<AudioRingMode>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getRingerMode((err, value) => { if (err) { console.error('Failed to obtain the ringer mode.​ ${err.message}'); @@ -554,6 +566,7 @@ getRingerMode(): Promise<AudioRingMode> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getRingerMode().then((value) => console.log('Promise returned to indicate that the ringer mode is obtained.' + value); ) @@ -576,6 +589,7 @@ setAudioParameter(key: string, value: string, callback: AsyncCallback<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setAudioParameter('PBits per sample', '8 bit', (err) => { if (err) { console.error('Failed to set the audio parameter. ${err.message}'); @@ -607,6 +621,7 @@ setAudioParameter(key: string, value: string): Promise<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setAudioParameter('PBits per sample', '8 bit').then(() => console.log('Promise returned to indicate a successful setting of the audio parameter.'); ) @@ -628,6 +643,7 @@ getAudioParameter(key: string, callback: AsyncCallback<string>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getAudioParameter('PBits per sample', (err, value) => { if (err) { console.error('Failed to obtain the value of the audio parameter. ${err.message}'); @@ -658,6 +674,7 @@ getAudioParameter(key: string): Promise<string> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getAudioParameter('PBits per sample').then((value) => console.log('Promise returned to indicate that the value of the audio parameter is obtained.' + value); ) @@ -678,6 +695,7 @@ getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescrip **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{ if (err) { console.error('Failed to obtain the device list. ${err.message}'); @@ -708,6 +726,7 @@ audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value)=>{ **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data)=> console.log('Promise returned to indicate that the device list is obtained.'); ) @@ -730,6 +749,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean, callback: AsyncCallback **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true, (err)=> { if (err) { console.error('Failed to set the active status of the device. ${err.message}'); @@ -762,6 +782,7 @@ setDeviceActive(deviceType: DeviceType, active: boolean): Promise<void> ``` +var audioManager = audio.getAudioManager(); audioManager.setDeviceActive(audio.DeviceType.SPEAKER, true).then(()=> console.log('Promise returned to indicate that the device is set to the active status.'); ) @@ -783,6 +804,7 @@ isDeviceActive(deviceType: DeviceType, callback: AsyncCallback<boolean>): **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isDeviceActive(audio.DeviceType.SPEAKER, (err, value) => { if (err) { console.error('Failed to obtain the active status of the device. ${err.message}'); @@ -814,6 +836,7 @@ isDeviceActive(deviceType: DeviceType): Promise<boolean> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isDeviceActive(audio.DeviceType.SPEAKER).then((value) => console.log('Promise returned to indicate that the active status of the device is obtained.' + value); ) @@ -835,6 +858,7 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setMicrophoneMute(true, (err) => { if (err) { console.error('Failed to mute the microphone. ${err.message}'); @@ -865,6 +889,7 @@ setMicrophoneMute(mute: boolean): Promise<void> **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.setMicrophoneMute(true).then(() => console.log('Promise returned to indicate that the microphone is muted.'); ) @@ -885,6 +910,7 @@ isMicrophoneMute(callback: AsyncCallback<boolean>): void **示例:** ``` +var audioManager = audio.getAudioManager(); audioManager.isMicrophoneMute((err, value) => { if (err) { console.error('Failed to obtain the mute status of the microphone. ${err.message}'); @@ -910,6 +936,7 @@ isMicrophoneMute(): Promise<boolean> ``` +var audioManager = audio.getAudioManager(); audioManager.isMicrophoneMute().then((value) => console.log('Promise returned to indicate that the mute status of the microphone is obtained.', + value); ) diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index 6054f6d62100b455a5abc2092bae1ac30dd957a5..fb4a41f4bbd0ba63a5088ad0a75c2c6677a1ee81 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -10,10 +10,15 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; ``` +## 系统能力 +SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask +SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask -## 权限 +## 权限列表 -无 +长时任务需要申请如下权限: + +ohos.permission.KEEP_BACKGROUND_RUNNING ## backgroundTaskManager.requestSuspendDelay @@ -39,7 +44,7 @@ requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspen ``` let myReason = 'test requestSuspendDelay'; let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { - console.info("Request suspend delay will time out."); + console.info("Request suspension delay will time out."); }) ``` @@ -122,3 +127,168 @@ cancelSuspendDelay(requestId: number): void | requestId | number | 是 | 延迟挂起的请求ID。 | | actualDelayTime | number | 是 | 应用的实际挂起延迟时间,以毫秒为单位。
一般情况下默认值为180000,低电量(依据系统低电量广播)时默认值为60000。 | +## backgroundTaskManager.startBackgroundRunning + +[8] startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void; + +向系统申请长时任务,使用callback形式返回结果。 + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用运行的上下文 | + | bgMode | BackgroundMode | 是 | 向系统申请的后台模式 | + | wantAgent | WantAgent | 是 | 通知参数,用于指定长时任务通知点击跳转的界面。使用方式参考:[8] | + | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | + +- **示例**: +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; +import wantAgent from '@ohos.wantAgent'; + +function callback(err, data) { + if (err) { + console.error("Operation failed Cause: " + err); + } else { + console.info("Operation succeeded"); + } +} + +let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] +}; + +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj, callback) +}); + +``` + +## backgroundTaskManager.startBackgroundRunning + +[8] startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> + +向系统申请长时任务,使用promise形式返回结果。 + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用运行的上下文 | + | bgMode | BackgroundMode | 是 | 向系统申请的后台模式 | + | wantAgent | WantAgent | 是 | 通知参数,用于指定长时任务通知点击跳转的界面 | + +- **返回值** + | 类型 | 说明 | + | -------------- | ------------------------- | + | Promise\ | 使用Promise形式返回结果。 | + +- **示例**: +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; +import wantAgent from '@ohos.wantAgent'; + +let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] +}; + +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), + backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); +}); + +``` + +## backgroundTaskManager.stopBackgroundRunning + +[8] stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void; + +向系统申请取消长时任务,使用callback形式返回结果。 + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用运行的上下文 | + | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | + +- **示例**: +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; + +function callback(err, data) { + if (err) { + console.error("Operation failed Cause: " + err); + } else { + console.info("Operation succeeded"); + } +} + +backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callback); + +``` + +## backgroundTaskManager.stopBackgroundRunning + +[8] stopBackgroundRunning(context: Context): Promise<void>; + +向系统申请取消长时任务,使用promise形式返回结果。 + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用运行的上下文 | + +- **返回值** + | 类型 | 说明 | + | -------------- | ------------------------- | + | Promise\ | 使用Promise形式返回结果。 | + +- **示例**: +```js +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import featureAbility from '@ohos.ability.featureAbility'; + +backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() => { + console.info("Operation succeeded"); +}).catch((err) => { + console.error("Operation failed Cause: " + err); +}); + +``` + +## [8] BackgroundMode + +| 参数名 | 参数 | 描述 | +| ----------------------- | -------- | -------- | +| DATA_TRANSFER | 1 | 数据传输 | +| AUDIO_PLAYBACK | 2 | 音频播放 | +| AUDIO_RECORDING | 3 | 录音 | +| LOCATION | 4 | 定位导航 | +| BLUETOOTH_INTERACTION | 5 | 蓝牙相关 | +| MULTI_DEVICE_CONNECTION | 6 | 多设备互联 | +| WIFI_INTERACTION | 7 | WLAN相关(系统保留) | +| VOIP | 8 | 音视频通话(系统保留) | +| TASK_KEEPING | 9 | 计算任务(仅供PC使用) | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-battery-info.md b/zh-cn/application-dev/reference/apis/js-apis-battery-info.md index 57a8070f4f4d702331a2c2fbb1868f0f44e30fdd..c9a4b11914a4240013c0475d85a6aaa5acab39b3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-battery-info.md +++ b/zh-cn/application-dev/reference/apis/js-apis-battery-info.md @@ -10,6 +10,9 @@ import batteryInfo from '@ohos.batteryInfo'; ``` +## 系统能力 + +SystemCapability.PowerManager.BatteryManager ## 属性 diff --git a/zh-cn/application-dev/reference/apis/js-apis-brightness.md b/zh-cn/application-dev/reference/apis/js-apis-brightness.md index 1825ff78c9b0b02223f4aecd41ddafe9575fde44..9692cb136f5ac05ef9fe2152f8ce73297994a074 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-brightness.md +++ b/zh-cn/application-dev/reference/apis/js-apis-brightness.md @@ -10,6 +10,9 @@ import brightness from '@ohos.brightness'; ``` +## 系统能力 + +SystemCapability.PowerManager.DisplayPowerManager ## brightness.setValue diff --git a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md index 80f4570493b387bd947dfcd5ffdd7d7a7319600a..31d716c34984355e71aa62bc1fb41c3fd453c390 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @@ -116,7 +116,11 @@ import CommonEvent from '@ohos.commonevent'; ``` +## 系统能力 +```js +SystemCapability.Notification.CommonEvent +``` ## CommonEvent.publish diff --git a/zh-cn/application-dev/reference/apis/js-apis-convertxml.md b/zh-cn/application-dev/reference/apis/js-apis-convertxml.md index 6b5edb199d7c4f174d49dadf620a640afff7bf60..1520b77763fb5d845d153beb3b12acd0a9d2c276 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-convertxml.md +++ b/zh-cn/application-dev/reference/apis/js-apis-convertxml.md @@ -7,14 +7,9 @@ ## 导入模块 ``` -import convertxml from '@ohos.convertxml' +import convertxml from '@ohos.convertxml'; ``` - -## 权限 - -无 - ## ConvertXML @@ -48,7 +43,7 @@ convert(xml: string, options?: ConvertOptions) : Object ' Work' + ' Play' + ''; - var conv= new convertxml.ConvertXML(); + var conv = new convertxml.ConvertXML(); var result1 = conv.convert(xml, {trim: false, ignoreDeclaration: false}); console.log(result1) ``` @@ -63,7 +58,7 @@ convert(xml: string, options?: ConvertOptions) : Object | ignoreInstruction | boolean | 否 | 是否忽略xml的写入处理指令,默认false。 | | ignoreAttributes | boolean | 否 | 是否跨多行打印属性并缩进属性,默认false。 | | ignoreComment | boolean | 否 | 是否忽略元素的注释信息,默认false。 | -| ignoreCdata | boolean | 否 | 是否忽略元素的CData信息,默认false。 | +| ignoreCDATA | boolean | 否 | 是否忽略元素的CDATA信息,默认false。 | | ignoreDoctype | boolean | 否 | 是否忽略元素的Doctype信息,默认false。 | | ignoreText | boolean | 否 | 是否忽略元素的文本信息,默认false。 | | declarationKey | string | 否 | 用于输出对象中declaration的属性键的名称,默认_declaration。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-ability.md b/zh-cn/application-dev/reference/apis/js-apis-data-ability.md index 7b82a0b98d1008b2badae7cdbdf58305cdad6481..20029605f35b85f37dfa652abef620d20836aceb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-ability.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-ability.md @@ -622,7 +622,7 @@ distinct(): DataAbilityPredicates ``` let predicates = new dataAbility.DataAbilityPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").distinct("NAME") - let resultSet = await rdbStore.query(predicates, ["NAME"]) + rdbStore.query(predicates, ["NAME"]) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md index 44c6e7089da9a60bd84c70afd3d4278222343a43..0bfbca177757860cc989587e2bdf7386e30d0a69 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @@ -7,7 +7,7 @@ ## 导入模块 ``` -import dataRdb from '@ohos.data.rdb' +import data_rdb from '@ohos.data.rdb' ``` @@ -16,40 +16,44 @@ import dataRdb from '@ohos.data.rdb' 无 -## dataRdb.getRdbStore +## data_rdb.getRdbStore -getRdbStore(config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void +getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,结果以callback形式返回。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用程序或功能的上下文 | | config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | | version | number | 是 | 数据库版本。 | | callback | AsyncCallback<[RdbStore](#rdbstore)> | 是 | 指定callback回调函数。返回一个RdbStore。 | - 示例: ``` - import dataRdb from '@ohos.data.rdb' - const STORE_CONFIG = { name: "RdbTest.db"} - const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" - dataRdb.getRdbStore(STORE_CONFIG, 1, function (err, rdbStore) { - rdbStore.executeSql(SQL_CREATE_TABLE) - console.info(TAG + 'create table done.') - }) + import Ability from '@ohos.application.Ability' + import data_rdb from '@ohos.data.rdb' + export default class MainAbility extends Ability { + const STORE_CONFIG = { name: "RdbTest.db"} + const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" + data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { + rdbStore.executeSql(SQL_CREATE_TABLE) + console.info(TAG + 'create table done.') + }) + } ``` +## data_rdb.getRdbStore -## dataRdb.getRdbStore - -getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> +getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> 获得一个相关的RdbStore,操作关系型数据库,用户可以根据自己的需求配置RdbStore的参数,然后通过RdbStore调用相关接口可以执行相关的数据操作,结果以Promise形式返回。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用程序或功能的上下文 | | config | [StoreConfig](#storeconfig) | 是 | 与此RDB存储相关的数据库配置。 | | version | number | 是 | 数据库版本。 | @@ -60,47 +64,53 @@ getRdbStore(config: StoreConfig, version: number): Promise<RdbStore> - 示例: ``` - import dataRdb from '@ohos.data.rdb' - const STORE_CONFIG = { name: "RdbTest.db" } - const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" - let promise = dataRdb.getRdbStore(STORE_CONFIG, 1); - promise.then(async (rdbStore) => { - await rdbStore.executeSql(SQL_CREATE_TABLE, null) - }).catch((err) => { - expect(null).assertFail(); - }) + import Ability from '@ohos.application.Ability' + import data_rdb from '@ohos.data.rdb' + export default class MainAbility extends Ability { + const STORE_CONFIG = { name: "RdbTest.db" } + const SQL_CREATE_TABLE = "CREATE TABLE IF NOT EXISTS EMPLOYEE (ID INTEGER PRIMARY KEY AUTOINCREMENT, NAME TEXT NOT NULL, AGE INTEGER, SALARY REAL, CODES BLOB)" + let promise = data_rdb.getRdbStore(this.context, STORE_CONFIG, 1); + promise.then(async (rdbStore) => { + await rdbStore.executeSql(SQL_CREATE_TABLE, null) + }).catch((err) => { + expect(null).assertFail(); + }) + } ``` +## data_rdb.deleteRdbStore -## dataRdb.deleteRdbStore - -deleteRdbStore(name: string, callback: AsyncCallback<void>): void +deleteRdbStore(context: Context, name: string, callback: AsyncCallback<void>): void 删除数据库,结果以callback形式返回。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用程序或功能的上下文 | | name | string | 是 | 数据库名称。 | | callback | AsyncCallback<void> | 是 | 指定callback回调函数。如果数据库已删除,则为true;否则返回false。 | - 示例: ``` - import dataRdb from '@ohos.data.rdb' - dataRdb.deleteRdbStore("RdbTest.db", function (err, rdbStore) { - console.info(TAG + 'delete store done.')}) + import Ability from '@ohos.application.Ability' + import data_rdb from '@ohos.data.rdb' + export default class MainAbility extends Ability { + data_rdb.deleteRdbStore(this.context, "RdbTest.db", function (err, rdbStore) { + console.info(TAG + 'delete store done.')}) + } ``` +## data_rdb.deleteRdbStore -## dataRdb.deleteRdbStore - -deleteRdbStore(name: string): Promise<void> +deleteRdbStore(context: Context, name: string): Promise<void> 使用指定的数据库文件配置删除数据库,结果以Promise形式返回。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | + | context | Context | 是 | 应用程序或功能的上下文 | | name | string | 是 | 数据库名称。 | - 返回值: @@ -110,14 +120,16 @@ deleteRdbStore(name: string): Promise<void> - 示例: ``` - import dataRdb from '@ohos.data.rdb' - let promise = dataRdb.deleteRdbStore("RdbTest.db") - promise.then(()=>{ - console.info(TAG + 'delete store done.') - }) + import Ability from '@ohos.application.Ability' + import data_rdb from '@ohos.data.rdb' + export default class MainAbility extends Ability { + let promise = data_rdb.deleteRdbStore(this.context, "RdbTest.db") + promise.then(()=>{ + console.info(TAG + 'delete store done.') + }) + } ``` - ## RdbPredicates 表示关系型数据库(RDB)的谓词。该类确定RDB中条件表达式的值是true还是false。 @@ -138,8 +150,7 @@ constructor(name: string) - 示例: ``` - import dataRdb from '@ohos.data.rdb' - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") ``` @@ -164,7 +175,7 @@ equalTo(field: string, value: ValueType): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") ``` @@ -190,7 +201,7 @@ notEqualTo(field: string, value: ValueType): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notEqualTo("NAME", "lisi") ``` @@ -210,7 +221,7 @@ beginWrap(): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) @@ -235,7 +246,7 @@ endWrap(): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "lisi") .beginWrap() .equalTo("AGE", 18) @@ -260,7 +271,7 @@ or(): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") .or() .equalTo("NAME", "Rose") @@ -282,7 +293,7 @@ and(): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") .and() .equalTo("SALARY", 200.5) @@ -310,7 +321,7 @@ contains(field: string, value: string): RdbPredicat - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.contains("NAME", "os") ``` @@ -336,7 +347,7 @@ beginsWith(field: string, value: string): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.beginsWith("NAME", "os") ``` @@ -362,7 +373,7 @@ endsWith(field: string, value: string): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.endsWith("NAME", "se") ``` @@ -387,7 +398,7 @@ isNull(field: string): RdbPredicates - 示例 ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.isNull("NAME") ``` @@ -412,7 +423,7 @@ isNotNull(field: string): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.isNotNull("NAME") ``` @@ -438,7 +449,7 @@ like(field: string, value: string): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.like("NAME", "%os%") ``` @@ -464,7 +475,7 @@ glob(field: string, value: string): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.glob("NAME", "?h*g") ``` @@ -491,7 +502,7 @@ between(field: string, low: ValueType, high: ValueType): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.between("AGE", 10, 50) ``` @@ -518,7 +529,7 @@ notBetween(field: string, low: ValueType, high: ValueType): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notBetween("AGE", 10, 50) ``` @@ -544,7 +555,7 @@ greaterThan(field: string, value: ValueType): RdbPredicatesgr - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThan("AGE", 18) ``` @@ -570,7 +581,7 @@ lessThan(field: string, value: ValueType): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThan("AGE", 20) ``` @@ -597,7 +608,7 @@ greaterThanOrEqualTo(field: string, value: ValueType): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.greaterThanOrEqualTo("AGE", 18) ``` @@ -624,7 +635,7 @@ lessThanOrEqualTo(field: string, value: ValueType): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.lessThanOrEqualTo("AGE", 20) ``` @@ -650,7 +661,7 @@ orderByAsc(field: string): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByAsc("NAME") ``` @@ -676,7 +687,7 @@ orderByDesc(field: string): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.orderByDesc("AGE") ``` @@ -696,9 +707,9 @@ distinct(): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").distinct("NAME") - let resultSet = await rdbStore.query(predicates, ["NAME"]) + rdbStore.query(predicates, ["NAME"]) ``` @@ -722,7 +733,7 @@ limitAs(value: number): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").limitAs(3) ``` @@ -747,7 +758,7 @@ offsetAs(rowOffset: number): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose").offsetAs(3) ``` @@ -772,7 +783,7 @@ groupBy(fields: Array<string>): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.groupBy(["AGE", "NAME"]) ``` @@ -797,7 +808,7 @@ indexedBy(indexName: string): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.indexedBy("SALARY_INDEX") ``` @@ -824,7 +835,7 @@ in(field: string, value: Array<ValueType>): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.in("AGE", [18, 20]) ``` @@ -851,7 +862,7 @@ notIn(field: string, value: Array<ValueType>): RdbPredicates - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.notIn("NAME", ["Lisa", "Rose"]) ``` @@ -941,7 +952,7 @@ update(values: ValuesBucket, rdbPredicates: RdbPredicates, callback: AsyncCallba "SALARY": 200.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") rdbStore.update(valueBucket, predicates, function (err, ret) { console.log(TAG + "updated row count: " + changedRows)}) @@ -973,7 +984,7 @@ update(values: ValuesBucket, rdbPredicates: RdbPredicates):Promise<number> "SALARY": 200.5, "CODES": new Uint8Array([1, 2, 3, 4, 5]), } - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") let promise = rdbStore.update(valueBucket, predicates) promise.then(async (ret) => { @@ -998,7 +1009,7 @@ delete(rdbPredicates: RdbPredicates, callback: AsyncCallback<number>):void - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") rdbStore.delete(predicates, function (err, rows) { console.log(TAG + "delete rows: " + rows)}) @@ -1023,7 +1034,7 @@ delete(rdbPredicates: RdbPredicates):Promise<number> - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") let promise = rdbStore.delete(predicates) promise.then((rows) => { @@ -1047,7 +1058,7 @@ query(rdbPredicates: RdbPredicates, columns: Array<string>, callback: Asyn - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { console.log(TAG + "resultSet column names:" + resultSet.columnNames) @@ -1074,7 +1085,7 @@ query(rdbPredicates: RdbPredicates, columns?: Array<string>):Promise<Re - 示例: ``` - let predicates = new dataRdb.RdbPredicates("EMPLOYEE") + let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Rose") let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) promise.then((resultSet) => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md index b2bd32db35fd9af1347a6abd2f1539e5b82d8fb2..88409ad69ff346cf0bfb97df2cdf9f1ab00be16c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @@ -14,8 +14,9 @@ let predicates = new dataRdb.RdbPredicates("EMPLOYEE") predicates.equalTo("AGE", 18) let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) promise.then((resultSet) => { - await console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); - await console.log(TAG + "resultSet columnCount:" + resultSet.columnCount);}) + console.log("resultSet columnNames:" + resultSet.columnNames); + console.log("resultSet columnCount:" + resultSet.columnCount); +}) ``` @@ -114,10 +115,11 @@ goTo(offset:number): boolean - 示例: ``` let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - resultSet.goTo(1) - resultSet.close() - resultSet = null + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { + resultSet.goTo(1); + resultSet.close(); + resultSet = null; + }) ``` @@ -140,10 +142,11 @@ goToRow(position: number): boolean - 示例: ``` let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - resultSet.goToRow(1) - resultSet.close() - resultSet = null + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { + resultSet.goToRow(1); + resultSet.close(); + resultSet = null + }) ``` @@ -163,10 +166,11 @@ goToFirstRow(): boolean - 示例: ``` let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - resultSet.goToFirstRow() - resultSet.close() - resultSet = null; + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { + resultSet.goToFirstRow(); + resultSet.close(); + resultSet = null; + }) ``` @@ -184,10 +188,11 @@ goToLastRow(): boolean - 示例: ``` let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - resultSet.goToLastRow() - resultSet.close() - resultSet = null; + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { + resultSet.goToLastRow(); + resultSet.close(); + resultSet = null; + }) ``` @@ -205,10 +210,11 @@ goToNextRow(): boolean - 示例: ``` let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - resultSet.goToNextRow() - resultSet.close() - resultSet = null; + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { + resultSet.goToNextRow() + resultSet.close() + resultSet = null; + }) ``` @@ -226,10 +232,11 @@ goToPreviousRow(): boolean - 示例: ``` let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - resultSet.goToPreviousRow() - resultSet.close() - resultSet = null + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { + resultSet.goToPreviousRow(); + resultSet.close(); + resultSet = null + }) ``` @@ -353,7 +360,8 @@ close(): void - 示例: ``` let predicates = new dataRdb.RdbPredicates("EMPLOYEE") - let resultSet = await rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) - resultSet.close() - resultSet = null + rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]).then((resultSet) => { + resultSet.close(); + resultSet = null + }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md index 37f09d0cbf171c0ec304b5934d8be0c23ac3a91f..ffe1f1bf2719bc6e8e0fc9628725a653e5cb71a6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-data-storage.md +++ b/zh-cn/application-dev/reference/apis/js-apis-data-storage.md @@ -48,11 +48,13 @@ getStorageSync(path: string): Storage import dataStorage from '@ohos.data.storage' import featureAbility from '@ohos.ability.featureAbility' - var context = featureAbility.getContext() - var path = await context.getFilesDir() - let storage = dataStorage.getStorageSync(path + '/mystore') - storage.putSync('startup', 'auto') - storage.flushSync() + (async () => { + var context = featureAbility.getContext() + var path = await context.getFilesDir() + let storage = dataStorage.getStorageSync(path + '/mystore') + storage.putSync('startup', 'auto') + storage.flushSync() + })() ``` @@ -73,16 +75,18 @@ getStorage(path: string, callback: AsyncCallback<Storage>): void import dataStorage from '@ohos.data.storage' import featureAbility from '@ohos.ability.featureAbility' - var context = featureAbility.getContext() - var path = await context.getFilesDir() - dataStorage.getStorage(path + '/mystore', function (err, storage) { - if (err) { - console.info("Get the storage failed, path: " + path + '/mystore') - return; - } - storage.putSync('startup', 'auto') - storage.flushSync() - }) + (async () => { + var context = featureAbility.getContext() + var path = await context.getFilesDir() + dataStorage.getStorage(path + '/mystore', function (err, storage) { + if (err) { + console.info("Get the storage failed, path: " + path + '/mystore') + return; + } + storage.putSync('startup', 'auto') + storage.flushSync() + }) + })() ``` @@ -107,15 +111,17 @@ getStorage(path: string): Promise<Storage> import dataStorage from '@ohos.data.storage' import featureAbility from '@ohos.ability.featureAbility' - var context = featureAbility.getContext() - var path = await context.getFilesDir() - let promise = dataStorage.getStorage(path + '/mystore') - promise.then((storage) => { - storage.putSync('startup', 'auto') - storage.flushSync() - }).catch((err) => { - console.info("Get the storage failed, path: " + path + '/mystore') - }) + (async () => { + var context = featureAbility.getContext() + var path = await context.getFilesDir() + let promise = dataStorage.getStorage(path + '/mystore') + promise.then((storage) => { + storage.putSync('startup', 'auto') + storage.flushSync() + }).catch((err) => { + console.info("Get the storage failed, path: " + path + '/mystore') + }) + }() ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-deque.md b/zh-cn/application-dev/reference/apis/js-apis-deque.md new file mode 100644 index 0000000000000000000000000000000000000000..6ef3ab95b545c41765e72178de06a080fbc82c08 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-deque.md @@ -0,0 +1,251 @@ +# 线性容器Deque + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import Deque from '@ohos.util.Deque' +``` + +## 权限 + +无 + +## Deque + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | Deque的元素个数 | + +### constructor + +constructor(); + +Deque的构造函数。 + +- 示例: + ``` + let deque = new Deque(); + ``` + +### insertFront + +insertFront(element: T): void; + +在deque头部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 示例: + ``` + let deque = new Deque; + deque.insertFront("a"); + deque.insertFront(1); + let b = [1, 2, 3]; + deque.insertFront(b); + let c = {name : "lala", age : "13"}; + deque.insertFront(false); + ``` +### insertEnd + +insertEnd(element: T): void; + +在deque尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 示例: + ``` + let deque = new Deque; + deque.insertEnd("a"); + deque.insertEnd(1); + let b = [1, 2, 3]; + deque.insertEnd(b); + let c = {name : "lala", age : "13"}; + deque.insertEnd(false); + ``` +### has + +has(element: T): boolean; + +判断此Deque中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let deque = new Deque(); + deque.has("Ahfbrgrbgnutfodgorrogorg"); + deque.insertFront("Ahfbrgrbgnutfodgorrogorg"); + deque.has("Ahfbrgrbgnutfodgorrogorg"); + ``` +### popFirst + +popFirst(): T; + +删除并返回双端队列的首元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertFront(4); + deque.insertEnd(5); + deque.insertFront(2); + deque.insertFront(4); + deque.popFirst(); + ``` +### popLast + +popLast(): T; + +删除并返回双端队列的尾元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertEnd(4); + deque.insertFront(5); + deque.insertFront(2); + deque.insertFront(4); + deque.popLast(); + ``` + +### forEach +forEach(callbackfn: (value: T, index?: number, deque?: Deque<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历Deque实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | deque | Deque<T> | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertEnd(4); + deque.insertFront(5); + deque.insertEnd(4); + deque.forEach((value, index) => { + console.log(value, index); + }); + ``` + +### getFirst + +getFirst(): T; +获取Deque实例中的头元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let deque = new Deque(); + deque.insertEnd(2); + deque.insertEnd(4); + deque.insertFront(5); + deque.insertFront(4); + deque.getFirst(); + ``` +### getLast + +getLast(): T; +获取Deque实例中的尾元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertFront(4); + deque.insertFront(5); + deque.insertFront(4); + deque.getLast(); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器。 | + + +- 示例: + ``` + let deque = new Deque(); + deque.insertFront(2); + deque.insertFront(4); + deque.insertFront(5); + deque.insertFront(4); + + // 使用方法一: + for (let item of deque) { + console.log(item); + } + + // 使用方法二: + let iter = deque[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md index e61397cf8b0820b160081327b319b3ca18ea93a5..33ba4d7b94fc998cd072365f1045cc351ca1670a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @@ -11,6 +11,11 @@ import account_distributedAccount from '@ohos.account.distributedAccount'; ``` +## 系统能力 + +SystemCapability.Account.OsAccount + + ## account_distributedAccount.getDistributedAccountAbility getDistributedAccountAbility(): DistributedAccountAbility diff --git a/zh-cn/application-dev/reference/apis/js-apis-emitter.md b/zh-cn/application-dev/reference/apis/js-apis-emitter.md index afed141714bfb8aa6a9868998b94a59b3236d8ee..dfaab6b7681fd39ac27cb3607b52078f02f1320d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-emitter.md +++ b/zh-cn/application-dev/reference/apis/js-apis-emitter.md @@ -8,6 +8,12 @@ import emitter from '@ohos.events.emitter' ``` +## 系统能力 + +```javascript +SystemCapability.Notification.Emitter +``` + ## 权限列表 无 diff --git a/zh-cn/application-dev/reference/apis/js-apis-environment.md b/zh-cn/application-dev/reference/apis/js-apis-environment.md index 2d38edd1d107c7713d9ef9e6815710e403650ecc..21898fc226a0b375069d5a3d6776d2e2d75acc12 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-environment.md +++ b/zh-cn/application-dev/reference/apis/js-apis-environment.md @@ -1,18 +1,17 @@ # 目录环境能力 - +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 -``` +```js import environment from '@ohos.environment'; ``` +## 系统能力 - -## 权限列表 - -无 +SystemCapability.FileManagement.File.Environment ## environment.getStorageDataDir @@ -28,11 +27,11 @@ getStorageDataDir():Promise<string> - 示例: - ``` + ```js environment.getStorageDataDir().then(function(path){ - // do something + console.info("getStorageDataDir successfully:"+ path); }).catch(function(error){ - + console.info("getStorageDataDir failed with error:"+ error); }); ``` @@ -50,7 +49,7 @@ getStorageDataDir(callback:AsyncCallback<string>):void - 示例: - ``` + ```js environment.getStorageDataDir(function(error, path){ // do something }); @@ -70,11 +69,11 @@ getUserDataDir():Promise<string> - 示例: - ``` + ```js environment.getUserDataDir().then(function(path){ - // do something + console.info("getUserDataDir successfully:"+ path); }).catch(function(error){ - + console.info("getUserDataDir failed with error:"+ error); }); ``` @@ -92,7 +91,7 @@ getUserDataDir(callback:AsyncCallback<string>): void - 示例: - ``` + ```js environment.getUserDataDir(function(error, path){ // do something }); diff --git a/zh-cn/application-dev/reference/apis/js-apis-fileio.md b/zh-cn/application-dev/reference/apis/js-apis-fileio.md index f868fc0ef78fb7bc0034a9e49a0f73b864603e8b..00845ba0ef6afa8ff0fa3df97f9b74f51fe28814 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-fileio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-fileio.md @@ -5,7 +5,7 @@ ## 导入模块 -``` +```js import fileio from '@ohos.fileio'; ``` @@ -23,7 +23,7 @@ import fileio from '@ohos.fileio'; 通过上述接口获取到应用目录路径dir,文件名为“xxx.txt”,文件所在绝对路径为: -``` +```js let path = dir + "/xxx.txt"; ``` @@ -31,7 +31,7 @@ let path = dir + "/xxx.txt"; 文件描述符fd: -``` +```js let fd = fileio.openSync(path); ``` @@ -53,9 +53,12 @@ stat(path: string): Promise<Stat> | Promise<[Stat](#stat)> | 表示文件的具体信息。 | - 示例: - ``` - let stat = await fileio.stat(path); - // example code in Stat + ```js + fileio.stat(path).then(function(stat){ + console.info("getFileInfo successfully:"+ JSON.stringify(stat)); + }).catch(function(err){ + console.info("getFileInfo failed with error:"+ err); + }); ``` @@ -72,9 +75,9 @@ stat(path:string, callback:AsyncCallback<Stat>): void | callback | AsyncCallback<[Stat](#stat)> | 是 | 异步获取文件的信息之后的回调。 | - 示例: - ``` + ```js fileio.stat(path, function (err, stat) { - // example code in Stat + // example code in Stat }); ``` @@ -97,7 +100,7 @@ statSync(path:string): Stat | [Stat](#stat) | 表示文件的具体信息。 | - 示例: - ``` + ```js let stat = fileio.statSync(path); // example code in Stat ``` @@ -120,9 +123,12 @@ opendir(path: string): Promise<Dir> | Promise<[Dir](#dir)> | 返回Dir对象。 | - 示例: - ``` - let dir = fileio.opendir(path); - // example code in Dir + ```js + fileio.opendir(path).then(function(dir){ + console.info("opendir successfully:"+ JSON.stringify(dir)); + }).catch(function(err){ + console.info("opendir failed with error:"+ err); + }); ``` @@ -139,10 +145,10 @@ opendir(path: string, callback: AsyncCallback<Dir>): void | callback | AsyncCallback<[Dir](#dir)> | 是 | 异步打开文件目录之后的回调。 | - 示例: - ``` + ```js fileio.opendir(path, function (err, dir) { - // example code in Dir struct - // use read/readSync/close + // example code in Dir struct + // use read/readSync/close }); ``` @@ -165,7 +171,7 @@ opendirSync(path: string): Dir | [Dir](#dir) | 返回Dir对象。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(path); // example code in Dir struct // use read/readSync/close @@ -190,12 +196,11 @@ access(path: string, mode?: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - fileio.access(path) - .then(function(err) { - // 文件存在,do something - }).catch(function(e) { - //若不符合条件则进入 + ```js + fileio.access(path).then(function() { + console.info("access successfully"); + }).catch(function(err){ + console.info("access failed with error:"+ err); }); ``` @@ -214,8 +219,9 @@ access(path: String, mode?: number, callback: AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步检查当前进程是否可访问某文件之后的回调。 | - 示例: - ``` + ```js fileio.access(path, function (err) { + // do something }); ``` @@ -234,11 +240,11 @@ accessSync(path: string, mode?: number): void | mode | number | 否 | 访问文件时的选项,可给定如下选项,以按位或的方式使用多个选项,默认给定0。
确认当前进程是否具有对应权限:
- 0:确认文件是否存在。
- 1:确认当前进程是否具有可执行权限。
- 2:确认当前进程是否具有写权限。
- 4:确认当前进程是否具有读权限。 | - 示例: - ``` + ```js try { fileio.accessSync(path); - } catch(e) { - //不符合条件则进入 + } catch(err) { + console.info("accessSync failed with error:"+ err); } ``` @@ -260,9 +266,13 @@ close(fd: number):Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` + ```js let fd = fileio.openSync(path); - await fileio.close(fd); + fileio.close(fd).then(function(){ + console.info("close file successfully"); + }).catch(function(err){ + console.info("close file failed with error:"+ err); + }); ``` @@ -279,9 +289,10 @@ close(fd: number, callback:AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步关闭文件之后的回调。 | - 示例: - ``` + ```js let fd = fileio.openSync(path); - await fileio.close(fd, function (err) { + fileio.close(fd, function (err) { + // do something }); ``` @@ -298,7 +309,7 @@ closeSync(fd: number): void | fd | number | 是 | 待关闭文件的文件描述符。 | - 示例: - ``` + ```js fileio.closeSync(fd); ``` @@ -315,8 +326,12 @@ close(): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - fileio.close(); + ```js + fileio.close().then(function(){ + console.info("close file stream successfully"); + }).catch(function(err){ + console.info("close file stream failed with error:"+ err); + }); ``` @@ -332,8 +347,9 @@ close(callback: AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步关闭文件流之后的回调。 | - 示例: - ``` - await fileio.close(function(err){ + ```js + fileio.close(function(err){ + // do something }); ``` @@ -357,8 +373,12 @@ copyFile(src:string | number, dest:string | number, mode?:number):Promise<voi | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - await fileio.copyFile(src, dest); + ```js + fileio.copyFile(src, dest).then(function(){ + console.info("copyFile successfully"); + }).catch(function(err){ + console.info("copyFile failed with error:"+ err); + }); ``` @@ -377,8 +397,9 @@ copyFile(src:string | number, dest:string | number, mode?: number, callback: Asy | callback | AsyncCallback<void> | 是 | 异步复制文件之后的回调。 | - 示例: - ``` - await fileio.copyFile(src, dest, function (err) { + ```js + fileio.copyFile(src, dest, function (err) { + // do something }); ``` @@ -397,7 +418,7 @@ fileio.copyFileSync(src:string | number, dest:string | number, mode?:number): vo | mode | number | 否 | mode提供覆盖文件的选项,当前仅支持0,且默认为0。
0:完全覆盖目标文件,未覆盖部分将被裁切掉。 | - 示例: - ``` + ```js fileio.copyFileSync(src, dest); ``` @@ -421,12 +442,12 @@ mkdir(path:string, mode?: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - await fileio.mkdir(path) - .then(function(err) { - // 目录创建成功,do something - }).catch(function (e){ - }); + ```js + fileio.mkdir(path).then(function() { + console.info("mkdir successfully"); + }).catch(function (error){ + console.info("mkdir failed with error:"+ error); + }); ``` @@ -444,8 +465,8 @@ mkdir(path:string, mode?:number, callback:AsyncCallbak<void>): void | callback | AsyncCallback<void> | 是 | 异步创建目录操作完成之后的回调。 | - 示例: - ``` - await fileio.mkdir(path, function(err) { + ```js + fileio.mkdir(path, function(err) { if (!err) { // do something } @@ -466,7 +487,7 @@ fileio.mkdirSync(path: string, mode?: number): void | mode | number | 否 | 创建目录的权限,可给定如下权限,以按位或的方式追加权限,默认给定0o775。
- 0o775:所有者具有读、写及可执行权限,其余用户具有读及可执行权限。
- 0o700:所有者具有读、写及可执行权限。
- 0o400:所有者具有读权限。
- 0o200:所有者具有写权限。
- 0o100:所有者具有可执行权限。
- 0o070:所有用户组具有读、写及可执行权限。
- 0o040:所有用户组具有读权限。
- 0o020:所有用户组具有写权限。
- 0o010:所有用户组具有可执行权限。
- 0o007:其余用户具有读、写及可执行权限。
- 0o004:其余用户具有读权限。
- 0o002:其余用户具有写权限。
- 0o001:其余用户具有可执行权限。 | - 示例: - ``` + ```js fileio.mkdirSync(path); ``` @@ -490,8 +511,12 @@ open(path: string, flags?: number, mode?: number): Promise<number> | Promise<number> | 打开文件的文件描述符。 | - 示例: - ``` - let fd = await fileio.open(path, 0o1, 0o0200); + ```js + fileio.open(path, 0o1, 0o0200).then(function(number){ + console.info("open file successfully"); + }).catch(function(error){ + console.info("open file failed with error:"+ err); + }); ``` @@ -510,8 +535,9 @@ open(path: string, flags: number, mode: number, callback: AsyncCallback<numbe | callback | AsyncCallback <void> | 是 | 异步打开文件之后的回调。 | - 示例: - ``` - await fileio.open(path, 0, function(err, fd) { + ```js + fileio.open(path, 0, function(err, fd) { + // do something }); ``` @@ -535,7 +561,7 @@ openSync(path:string, flags?:number, mode?:number): number | number | 打开文件的文件描述符。 | - 示例: - ``` + ```js let fd = fileio.openSync(path); ``` @@ -559,10 +585,14 @@ read(fd: number, buffer: ArrayBuffer, options?: Object): Promise<Readout> | Promise<[Readout](#readout)> | 读取的结果。 | - 示例: - ``` + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); - let res = await fileio.read(fd, buf); + fileio.read(fd, buf).then(function(readout){ + console.info("read file data successfully:"+ JSON.stringify(readout)); + }).catch(function(error){ + console.info("read file data failed with error:"+ error); + }); ``` @@ -581,10 +611,10 @@ read(fd: number, buffer: ArrayBuffer, options?: Object, callback: AsyncCallback& | callback | AsyncCallback<[Readout](#readout)> | 是 | 异步读取数据之后的回调。 | - 示例: - ``` + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); - await fileio.read(fd, buf, function (err, readOut) { + fileio.read(fd, buf, function (err, readOut) { if (!err) { console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))) } @@ -611,7 +641,7 @@ readSync(fd: number, buffer: ArrayBuffer, options?: Object): number | number | 实际读取的长度。 | - 示例: - ``` + ```js let fd = fileio.openSync(path, 0o2); let buf = new ArrayBuffer(4096); let num = fileio.readSync(fd, buf); @@ -635,11 +665,11 @@ rmdir(path: string): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - fileio.rmdir(path) - .then(function(err) { - // 删除目录成功,do something - }).catch(function(e){ + ```js + fileio.rmdir(path).then(function() { + console.info("rmdir successfully"); + }).catch(function(err){ + console.info("rmdir failed with error:"+ err); }); ``` @@ -657,8 +687,9 @@ rmdir(path: string, callback:AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步删除目录之后的回调。 | - 示例: - ``` - fileio.rmdir(path, function(err){ + ```js + fileio.rmdir(path, function(err){ + // do something }); ``` @@ -675,7 +706,7 @@ rmdirSync(path:string) | path | string | 是 | 待删除目录的绝对路径。 | - 示例: - ``` + ```js fileio.rmdirSync(path); ``` @@ -697,8 +728,12 @@ unlink(path:string): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - await fileio.unlink(path); + ```js + fileio.unlink(path).then(function(){ + console.info("remove file successfully"); + }).catch(function(error){ + console.info("remove file failed with error:"+ error); + }); ``` @@ -715,8 +750,8 @@ unlink(path:string, callback:AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步删除文件之后的回调。 | - 示例: - ``` - await fileio.unlink(path, function(err) { + ```js + fileio.unlink(path, function(err) { if (!err) { // do something } @@ -736,7 +771,7 @@ unlinkSync(path: string): void | path | string | 是 | 待删除文件的绝对路径。 | - 示例: - ``` + ```js fileio.unlinkSync(path); ``` @@ -760,9 +795,13 @@ write(fd: number, buffer: ArrayBuffer | string, options?: Object): Promise<nu | Promise<number> | 实际写入的长度。 | - 示例: - ``` + ```js let fd = fileio.openSync(fpath, 0o100 | 0o2, 0o666); - let num = await fileio.write(fd, "hello, world"); + fileio.write(fd, "hello, world").then(function(number){ + console.info("write data to file successfully:"+ number); + }).catch(function(err){ + console.info("write data to file failed with error:"+ err); + }); ``` @@ -781,7 +820,7 @@ write(fd:number, buffer:ArrayBuffer | string,options?:Object, callback:AsyncCall | callback | AsyncCallback<number> | 是 | 异步将数据写入完成后执行的回调函数。 | - 示例: - ``` + ```js let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world", function (err, bytesWritten) { if (!err) { @@ -810,7 +849,7 @@ writeSync(fd: number, buffer: ArrayBuffer | string, options?:Object): number | number | 实际写入的长度。 | - 示例: - ``` + ```js let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); let num = fileio.writeSync(fd, "hello, world"); ``` @@ -834,8 +873,12 @@ hash(path: string, algorithm: string): Promise<string> | Promise<string> | 文件的哈希值。表示为十六进制数字串,所有字母均大写。 | - 示例: - ``` - let hashStr = await fileio.hash(path, "sha256"); + ```js + fileio.hash(path, "sha256").then(function(str){ + console.info("calculate file hash successfully:"+ str); + }).catch(function(error){ + console.info("calculate file hash failed with error:"+ err); + }); ``` @@ -853,7 +896,7 @@ hash(psth:string, algorithm:string, callback:AsyncCallback<string>): void | callback | AsyncCallback<string> | 是 | 异步计算文件哈希操之后的回调函数(其中给定文件哈希值表示为十六进制数字串,所有字母均大写)。 | - 示例: - ``` + ```js fileio.hash(fpath, "sha256", function(err, hashStr) { if (!err) { console.log(hashStr) @@ -880,11 +923,11 @@ chmod(path: string, mode: number):Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - fileio.chmod(path, mode) - .then(function(err) { - // 改变文件权限成功,do something - }).catch(function(e){ + ```js + fileio.chmod(path, mode).then(function() { + console.info("chmod successfully"); + }).catch(function(err){ + console.info("chmod failed with error:"+ err); }); ``` @@ -903,8 +946,9 @@ chmod(path: string, mode: number, callback: AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步改变文件权限之后的回调。 | - 示例: - ``` - fileio.chmod(path, mode, function (err) { + ```js + fileio.chmod(path, mode, function (err) { + // do something }); ``` @@ -922,7 +966,7 @@ chmodSync(path: string, mode: number): void | mode | number | 是 | 改变文件权限,可给定如下权限,以按位或的方式追加权限。
- 0o700:所有者具有读、写及可执行权限。
- 0o400:所有者具有读权限。
- 0o200:所有者具有写权限。
- 0o100:所有者具有可执行权限。
- 0o070:所有用户组具有读、写及可执行权限。
- 0o040:所有用户组具有读权限。
- 0o020:所有用户组具有写权限。
- 0o010:所有用户组具有可执行权限。
- 0o007:其余用户具有读、写及可执行权限。
- 0o004:其余用户具有读权限。
- 0o002:其余用户具有写权限。
- 0o001:其余用户具有可执行权限。 | - 示例: - ``` + ```js fileio.chmodSync(fpath, mode); ``` @@ -944,8 +988,12 @@ fstat(fd: number): Promise<Stat> | Promise<[Stat](#stat)> | 表示文件的具体信息。 | - 示例: - ``` - let stat = await fileio.fstat(fd); + ```js + fileio.fstat(fd).then(function(stat){ + console.info("fstat successfully:"+ JSON.stringify(stat)); + }).catch(function(err){ + console.info("fstat failed with error:"+ err); + }); ``` @@ -962,9 +1010,10 @@ fstat(fd: number, callback: AsyncCallback<Stat>): void | callback | AsyncCallback<[Stat](#stat)> | 是 | 异步获取文件状态信息之后的回调。 | - 示例: - ``` + ```js let fd = fileio.openSync(path); - fileio.fstat(fd, function (err) { + fileio.fstat(fd, function (err) { + // do something }); ``` @@ -986,7 +1035,7 @@ fstatSync(fd: number): Stat | [Stat](#stat) | 表示文件的具体信息。 | - 示例: - ``` + ```js let fd = fileio.openSync(path); let stat = fileio.fstatSync(fd); ``` @@ -1010,12 +1059,12 @@ ftruncate(fd: number, len: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` + ```js let fd = fileio.openSync(path); - fileio.ftruncate(fd, 5) - .then(function(err) { - // 截断文件成功, do something - }).catch(function(e){ + fileio.ftruncate(fd, 5).then(function(err) { + console.info("truncate file successfully"); + }).catch(function(err){ + console.info("truncate file failed with error:"+ err); }); ``` @@ -1034,8 +1083,9 @@ ftruncate(fd: number, len: number, callback:AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步截断文件的信息之后的回调。 | - 示例: - ``` - fileio.ftruncate(fd, len, function(err){ + ```js + fileio.ftruncate(fd, len, function(err){ + // do something }); ``` @@ -1053,8 +1103,8 @@ ftruncateSync(fd: number, len?: number): void | len | number | 否 | 文件截断后的长度,以字节为单位。 | - 示例: - ``` - fileio.ftruncate(fd, len); + ```js + fileio.ftruncate(fd, len); ``` @@ -1076,11 +1126,11 @@ truncate(path: string, len: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - fileio.truncate(path, len) - .then(function(err) { - // 截断文件成功,do something - }).catch(function(e){ + ```js + fileio.truncate(path, len).then(function(){ + console.info("truncate file successfully"); + }).catch(function(err){ + console.info("truncate file failed with error:"+ err); }); ``` @@ -1099,8 +1149,9 @@ truncate(path: string, len: number, callback:AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步截断文件的信息之后的回调。 | - 示例: - ``` - fileio.truncate(path, len, function(err){ + ```js + fileio.truncate(path, len, function(err){ + // do something }); ``` @@ -1118,7 +1169,7 @@ truncateSync(fpath: string, len?: number): void | len | number | 否 | 文件截断后的长度,以字节为单位。 | - 示例: - ``` + ```js fileio.ftruncate(path, len); ``` @@ -1141,11 +1192,11 @@ readText(filePath: string, options?:Object): Promise<string> | Promise<string> | 返回读取文件的内容。 | - 示例: - ``` - fileio.readText(path) - .then(function(str) { - // 读取文件成功,do something - }).catch(function(e){ + ```js + fileio.readText(path).then(function(str) { + console.info("readText successfully:"+ str); + }).catch(function(err){ + console.info("readText failed with error:"+ err); }); ``` @@ -1164,8 +1215,9 @@ readText(filePath: string, options?:Object, callback:AsyncCallback<string> | callback | AsyncCallback<string> | 是 | 异步通过文本方式读取文件之后的回调。 | - 示例: - ``` + ```js fileio.readText(path, function(err, str){ + // do something }); ``` @@ -1188,8 +1240,8 @@ readTextSync(filePath: string, options?:Object): string | Promise<string> | 返回读取文件的内容。 | - 示例: - ``` - let str = fileio.readTextSync(path, {position: pos, length: len}); + ```js + let str = fileio.readTextSync(path, {position: 1, length: 3}); ``` @@ -1210,8 +1262,12 @@ lstat(path: string): Promise<Stat> | Promise<[Stat](#stat)> | 表示文件的具体信息。 | - 示例: - ``` - let stat = await fileio.lstat(path); + ```js + fileio.lstat(path).then(function(stat){ + console.info("get link status successfully:"+ number); + }).catch(function(err){ + console.info("get link status failed with error:"+ err); + }); ``` @@ -1228,8 +1284,9 @@ lstat(path:string, callback:AsyncCallback<Stat>): void | callback | AsyncCallback<[Stat](#stat)> | 是 | 异步获取链接状态信息之后的回调。 | - 示例: - ``` - fileio.lstat(path, function (err, stat) { + ```js + fileio.lstat(path, function (err, stat) { + // do something )); ``` @@ -1251,7 +1308,7 @@ lstatSync(path:string): Stat | [Stat](#stat) | 表示文件的具体信息。 | - 示例: - ``` + ```js let stat = fileio.lstatSync(path); ``` @@ -1274,8 +1331,12 @@ read(buffer: ArrayBuffer, options?: Object): Promise<Readout> | Promise<[Readout](#readout)> | 读取的结果。 | - 示例: - ``` - let readout = await fileio.read(new ArrayBuffer(4096)); + ```js + fileio.read(new ArrayBuffer(4096)).then(function(readout){ + console.info("read file data successfully:"+ String.fromCharCode.apply(null, new Uint8Array(readout.buffer))); + }).catch(function(err){ + console.info("read file data failed with error:"+ err); + }); ``` @@ -1293,7 +1354,7 @@ read(buffer: ArrayBuffer, options?: Object, callback: AsyncCallback<Readout&g | callback | AsyncCallback<[Readout](#readout)> | 是 | 异步从文件读取数据之后的回调。 | - 示例 - ``` + ```js let buf = new ArrayBuffer(4096); fileio.read(buf, function (err, readOut) { if (!err) { @@ -1321,12 +1382,11 @@ rename(oldPath: string, newPath: string): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - fileio.rename(oldPath, Newpath) - .then(function(err) { - // 重命名文件成功,do something - }).catch(function(e){ - + ```js + fileio.rename(oldPath, Newpath).then(function() { + console.info("rename successfully"); + }).catch(function(err){ + console.info("rename failed with error:"+ err); }); ``` @@ -1345,7 +1405,7 @@ rename(oldPath: string, newPath: string, callback: AsyncCallback<void>): v | Callback | AsyncCallback<void> | 是 | 异步重命名文件之后的回调。 | - 示例: - ``` + ```js fileio.rename(oldpath, Newpath, function(err){ }); ``` @@ -1364,7 +1424,7 @@ renameSync(oldPath: string, newPath: string): void | Newpath | String | 是 | 目标文件的新绝对路径。 | - 示例: - ``` + ```js fileio.renameSync(oldpath, newpath); ``` @@ -1386,8 +1446,12 @@ fsync(fd: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` - await fileio.fsync(fd); + ```js + fileio.fsync(fd).then(function(){ + console.info("sync data successfully"); + }).catch(function(err){ + console.info("sync data failed with error:"+ err); + }); ``` @@ -1404,8 +1468,9 @@ fsync(fd: number, callback: AsyncCallback<void>): void | Callback | AsyncCallback<void> | 是 | 异步将文件数据同步之后的回调。 | - 示例: - ``` + ```js fileio.fsync(fd, function(err){ + // do something }); ``` @@ -1422,7 +1487,7 @@ fsyncSync(fd: number): void | fd | number | 是 | 待同步文件的文件描述符。 | - 示例: - ``` + ```js fileio.fyncsSync(fd); ``` @@ -1444,11 +1509,11 @@ fdatasync(fd: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果,本调用将返回空值。 | - 示例: - ``` - fileio.fdatasync(fd) - .then(function(err) { - // 数据同步成功,do something - }).catch(function(e){ + ```js + fileio.fdatasync(fd).then(function(err) { + console.info("sync data successfully"); + }).catch(function(err){ + console.info("sync data failed with error:"+ err); }); ``` @@ -1466,8 +1531,9 @@ fdatasync(fd: number, callback:AsyncCallback<void>): void | callback | AsyncCallback <void> | 是 | 异步将文件内容数据同步之后的回调。 | - 示例: - ``` + ```js fileio.fdatasync (fd, function (err) { + // do something }); ``` @@ -1484,7 +1550,7 @@ fdatasyncSync(fd: number): void | fd | number | 是 | 待同步文件的文件描述符。 | - 示例: - ``` + ```js let stat = fileio.fdatasyncSync(fd); ``` @@ -1507,12 +1573,11 @@ symlink(target: string, srcPath: string): Promise<void> | Promise<void> | Promise实例,用于异步获取结果,本调用将返回空值。 | - 示例: - ``` - fileio.symlink(target, srcPath) - .then(function(err) { - // 创建符号链接成功,do something - }).catch(function(e){ - + ```js + fileio.symlink(target, srcPath).then(function() { + console.info("symlink successfully"); + }).catch(function(err){ + console.info("symlink failed with error:"+ err); }); ``` @@ -1531,8 +1596,9 @@ symlink(target: string, srcPath: string, callback: AsyncCallback<void>): v | callback | AsyncCallback<void> | 是 | 异步创建符号链接信息之后的回调。 | - 示例: - ``` - fileio.symlink(target, srcPath, function (err) { + ```js + fileio.symlink(target, srcPath, function (err) { + // do something }); ``` @@ -1550,7 +1616,7 @@ symlinkSync(target: string, srcPath: string): void | srcPath | string | 是 | 符号链接文件的绝对路径。 | - 示例: - ``` + ```js fileio.symlinkSync(target, srcPath); ``` @@ -1574,9 +1640,13 @@ chown(path: string, uid: number, gid: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果,本调用将返回空值。 | - 示例: - ``` + ```js let stat = fileio.statSync(path); - await fileio.chown(path, stat.uid, stat.gid)); + fileio.chown(path, stat.uid, stat.gid)).then(function(){ + console.info("chown successfully"); + }).catch(function(err){ + console.info("chown failed with error:"+ err); + }); ``` @@ -1595,9 +1665,10 @@ chown(path: string, uid: number, gid: number, callback: AsyncCallback<void> | callback | AsyncCallback<void> | 是 | 异步改变文件所有者之后的回调。 | - 示例: - ``` + ```js let stat = fileio.statSync(fpath) fileio.chown(path, stat.uid, stat.gid, function (err){ + // do something }); ``` @@ -1616,7 +1687,7 @@ chownSync(path: string, uid: number, gid: number): void | gid | number | 是 | 新的GID。 | - 示例: - ``` + ```js let stat = fileio.statSync(fpath) fileio.chownSync(path, stat.uid, stat.gid); ``` @@ -1639,8 +1710,12 @@ mkdtemp(prefix: string): Promise<string> | Promise<string> | 生成的唯一目录路径。 | - 示例: - ``` - let res = await fileio.mkdtempSync(path + "XXXX"); + ```js + fileio.mkdtemp(path + "XXXX").then(function(path){ + console.info("mkdtemp successfully:"+ path); + }).catch(function(err){ + console.info("mkdtemp failed with error:"+ err); + }); ``` @@ -1657,8 +1732,9 @@ mkdtemp(prefix: string, callback: AsyncCallback<string>): void | callback | AsyncCallback<string> | 是 | 异步创建临时目录之后的回调。 | - 示例: - ``` + ```js fileio.mkdtemp(path + "XXXX", function (err, res) { + // do something }); ``` @@ -1680,7 +1756,7 @@ mkdtempSync(prefix: string): string | string | 产生的唯一目录路径。 | - 示例: - ``` + ```js let res = fileio.mkdtempSync(path + "XXXX"); ``` @@ -1703,12 +1779,11 @@ fchmod(fd: number, mode: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果,本调用将返回空值。 | - 示例: - ``` - fileio.fchmod(fd, mode) - .then(function(err) { - // 改变文件权限成功,do something - }).catch(function(e){ - + ```js + fileio.fchmod(fd, mode).then(function() { + console.info("chmod successfully"); + }).catch(function(err){ + console.info("chmod failed with error:"+ err); }); ``` @@ -1727,8 +1802,9 @@ fchmod(fd: number, mode: number, callback: AsyncCallback<void>): void | callback | AsyncCallback <void> | 是 | 异步改变文件权限之后的回调。 | - 示例: - ``` + ```js fileio.fchmod(fd, mode, function (err) { + // do something }); ``` @@ -1746,7 +1822,7 @@ fchmodSync(existingPath: string, newPath: string): void | mode | number | 是 | 若创建文件,则指定文件的权限,可给定如下权限,以按位或的方式追加权限。
- 0o700:所有者具有读、写及可执行权限。
- 0o400:所有者具有读权限。
- 0o200:所有者具有写权限。
- 0o100:所有者具有可执行权限。
- 0o070:所有用户组具有读、写及可执行权限。
- 0o040:所有用户组具有读权限。
- 0o020:所有用户组具有写权限。
- 0o010:所有用户组具有可执行权限。
- 0o007:其余用户具有读、写及可执行权限。
- 0o004:其余用户具有读权限。
- 0o002:其余用户具有写权限。
- 0o001:其余用户具有可执行权限。 | - 示例: - ``` + ```js fileio.fchmodSync(fd, mode); ``` @@ -1769,8 +1845,12 @@ createStream(path: string, mode: string): Promise<Stream> | Promise<[Stream](#stream7)> | 返回文件流的结果。 | - 示例: - ``` - let ss = filrio.createStream(path, "r+"); + ```js + fileio.createStream(path, "r+").then(function(stream){ + console.info("createStream successfully"); + }).catch(function(err){ + console.info("createStream failed with error:"+ err); + }); ``` @@ -1788,8 +1868,9 @@ createStream(path: string, mode: string, callback: AsyncCallback<Stream>): | callback | AsyncCallback<[Stream](#stream7)> | 是 | 异步打开文件流之后的回调。 | - 示例: - ``` - fileio.createStream(path, mode, function(err, stream){ + ```js + fileio.createStream(path, mode, function(err, stream){ + // do something }); ``` @@ -1812,7 +1893,7 @@ createStreamSync(path: string, mode: string): Stream | [Stream](#stream7) | 返回文件流的结果。 | - 示例: - ``` + ```js let ss = fileio.createStreamSync(path, "r+"); ``` @@ -1835,8 +1916,12 @@ fdopenStream(fd: number, mode: string): Promise<Stream> | Promise<[Stream](#stream7)> | 返回文件流的结果。 | - 示例: - ``` - let fp = await fileio.fdopenStream(fd, mode); + ```js + fileio.fdopenStream(fd, mode).then(function(stream){ + console.info("openStream successfully"+); + }).catch(function(err){ + console.info("openStream failed with error:"+ err); + }); ``` @@ -1854,8 +1939,9 @@ fdopenStream(fd: number, mode: string, callback: AsyncCallback<Stream>): v | callback | AsyncCallback <[Stream](#stream7)> | 是 | 异步打开文件流之后的回调。 | - 示例: - ``` - fileio.fdopenStream(fd, mode, function (err, fp) { + ```js + fileio.fdopenStream(fd, mode, function (err, stream) { + // do something }); ``` @@ -1878,7 +1964,7 @@ fdopenStreamSync(fd: number, mode: string): Stream | [Stream](#stream7) | 返回文件流的结果。 | - 示例: - ``` + ```js let ss = fileio.fdopenStreamSync(fd, "r+"); ``` @@ -1902,13 +1988,12 @@ fchown(fd: number, uid: number, gid: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` + ```js let stat = fileio.statSync(path); - fileio.fchown(fd, stat.uid, stat.gid) - .then(function(err) { - // 改变文件所有者成功,do something - }).catch(function(e){ - + fileio.fchown(fd, stat.uid, stat.gid).then(function() { + console.info("chown successfully"); + }).catch(function(err){ + console.info("chown failed with error:"+ err); }); ``` @@ -1928,9 +2013,10 @@ fchown(fd: number, uid: number, gid: number, callback: AsyncCallback<void> | callback | AsyncCallback<void> | 是 | 异步改变文件所有者之后的回调。 | - 示例: - ``` + ```js let stat = fileio.statSync(fpath); fileio.fchown(fd, stat.uid, stat.gid, function (err){ + // do something }); ``` @@ -1949,7 +2035,7 @@ fchownSync(fd: number, uid: number, gid: number): void | gid | number | 是 | 文件所有组的GID。 | - 示例: - ``` + ```js let stat = fileio.statSync(fpath); fileio.fchownSync(fd, stat.uid, stat.gid); ``` @@ -1974,14 +2060,13 @@ lchown(path: string, uid: number, gid: number): Promise<void> | Promise<void> | Promise实例,用于异步获取结果。本调用将返回空值。 | - 示例: - ``` + ```js let stat = fileio.statSync(path); - fileio.lchown(path, stat.uid, stat.gid) - .then(function(err) { - // 改变文件所有者,do something - }).catch(function(e){ - - }); + fileio.lchown(path, stat.uid, stat.gid).then(function() { + console.info("chown successfully"); + }).catch(function(err){ + console.info("chown failed with error:"+ err); + }); ``` @@ -2000,9 +2085,10 @@ lchown(path: string, uid: number, gid: number, callback: AsyncCallback<void&g | callback | AsyncCallback<void> | 是 | 异步改变文件所有者之后的回调。 | - 示例: - ``` + ```js let stat = fileio.statSync(path); fileio.lchown(path, stat.uid, stat.gid, function (err){ + // do something }); ``` @@ -2021,7 +2107,7 @@ lchownSync(path: string, uid: number, gid: number): void | gid | number | 是 | 新的GID。 | - 示例: - ``` + ```js let stat = fileio.statSync(path); fileio.lchownSync(path, stat.uid, stat.gid); ``` @@ -2046,8 +2132,9 @@ createWatcher(filename: string, events: number, callback: AsyncCallback<numbe | [Watcher](#watcher7) | 文件变化监听的实例。 | - 示例: - ``` - let ob = await fileio.createWatcher(filename, events, function(event){ + ```js + fileio.createWatcher(filename, events, function(watcher){ + // do something }); ``` @@ -2098,7 +2185,7 @@ isBlockDevice(): boolean | boolean | 表示当前目录项是否是块特殊设备。 | - 示例: - ``` + ```js let isBLockDevice = fileio.statSync(path).isBlockDevice(); ``` @@ -2115,7 +2202,7 @@ isCharacterDevice(): boolean | boolean | 表示当前目录项是否是字符特殊设备。 | - 示例: - ``` + ```js let isCharacterDevice = fileio.statSync(path).isCharacterDevice(); ``` @@ -2132,7 +2219,7 @@ isDirectory(): boolean | boolean | 表示当前目录项是否是目录。 | - 示例: - ``` + ```js let isDirectory = fileio.statSync(path).isDirectory(); ``` @@ -2149,7 +2236,7 @@ isFIFO(): boolean | boolean | 表示当前目录项是否是 FIFO。 | - 示例: - ``` + ```js let isFIFO = fileio.statSync(path).isFIFO(); ``` @@ -2166,7 +2253,7 @@ isFile(): boolean | boolean | 表示当前目录项是否是普通文件。 | - 示例: - ``` + ```js let isFile = fileio.statSync(fpath).isFile(); ``` @@ -2183,7 +2270,7 @@ isSocket(): boolean | boolean | 表示当前目录项是否是套接字。 | - 示例: - ``` + ```js let isSocket = fileio.statSync(path).isSocket(); ``` @@ -2200,7 +2287,7 @@ isSymbolicLink(): boolean | boolean | 表示当前目录项是否是符号链接。 | - 示例: - ``` + ```js let isSymbolicLink = fileio.statSync(path).isSymbolicLink(); ``` @@ -2217,7 +2304,7 @@ stop(): void 以异步方法关闭watcher监听,使用promise形式返回结果。 - 示例: - ``` + ```js fileio.stop(); ``` @@ -2234,8 +2321,9 @@ stop(callback: AsyncCallback): void | callback | AsyncCallback<void> | 是 | 以异步方法关闭watcher监听之后的回调。 | - 示例: - ``` + ```js fileio.stop(function(err){ + // do something }); ``` @@ -2257,9 +2345,13 @@ close(): Promise<void> | Promise<void> | 表示异步关闭文件流的结果。 | - 示例: - ``` + ```js let ss= fileio.createStreamSync(path); - await ss.close(); + ss.close().then(function(){ + console.info("close fileStream successfully"); + }).catch(function(err){ + console.info("close fileStream failed with error:"+ err); + }); ``` @@ -2275,9 +2367,10 @@ close(callback: AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步关闭文件流之后的回调。 | - 示例: - ``` + ```js let ss= fileio.createStreamSync(path); ss.close(function (err) { + // do something }); ``` @@ -2289,7 +2382,7 @@ closeSync(): void 同步关闭文件流。 - 示例: - ``` + ```js let ss= fileio.createStreamSync(path); ss.closeSync(); ``` @@ -2307,9 +2400,13 @@ flush(): Promise<void> | Promise<void> | 表示异步刷新文件流的结果。 | - 示例: - ``` + ```js let ss= fileio.createStreamSync(path); - await ss.flush(); + ss.flush().then(function (){ + console.info("flush successfully"); + }).catch(function(err){ + console.info("flush failed with error:"+ err); + }); ``` @@ -2325,10 +2422,10 @@ flush(callback: AsyncCallback<void>): void | callback | AsyncCallback<void> | 是 | 异步刷新文件流后的回调函数。 | - 示例: - ``` + ```js let ss= fileio.createStreamSync(path); ss.flush(function (err) { - expect(fileio.unlinkSync(fpath)).assertNull(); + // do something }); ``` @@ -2340,7 +2437,7 @@ flushSync(): void 同步刷新文件流。 - 示例: - ``` + ```js let ss= fileio.createStreamSync(path); ss.flushSync(); ``` @@ -2364,9 +2461,13 @@ write(buffer: ArrayBuffer | string, options?: Object): Promise<number> | Promise<number> | 实际写入的长度。 | - 示例: - ``` + ```js let ss= fileio.createStreamSync(fpath, "r+"); - let num = await ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}); + ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ + console.info("write successfully:"+ number); + }).catch(function(err){ + console.info("write failed with error:"+ err); + }); ``` @@ -2384,11 +2485,12 @@ write(buffer:ArrayBuffer | string,options?:Object, callback:AsyncCallback<num | callback | AsyncCallback<number> | 是 | 异步写入完成后执行的回调函数。 | - 示例: - ``` + ```js let ss= fileio.createStreamSync(fpath, "r+"); ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { if (!err) { - console.log(bytesWritten) + // do something + console.log(bytesWritten); } }); ``` @@ -2412,7 +2514,7 @@ writeSync(buffer: ArrayBuffer | string, options?:Object): number | number | 实际写入的长度。 | - 示例: - ``` + ```js let ss= fileio.createStreamSync(fpath,"r+"); let num = ss.writeSync("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}); ``` @@ -2436,9 +2538,13 @@ read(buffer: ArrayBuffer, options?: Object): Promise<Readout> | Promise<[Readout](#readout)> | 读取的结果。 | - 示例: - ``` + ```js let ss = fileio.createStreamSync(fpath, "r+"); - let readOut = await ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}); + ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readout){ + console.info("read data successfully"); + }).catch(function(err){ + console.info("read data failed with error:"+ err); + }); ``` @@ -2456,11 +2562,11 @@ read(buffer: ArrayBuffer, options?: Object, callback: AsyncCallback<Readout&g | callback | AsyncCallback<[Readout](#readout)> | 是 | 异步从流文件读取数据之后的回调。 | - 示例: - ``` + ```js let ss = fileio.createStreamSync(fpath, "r+"); ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { if (!err) { - console.log(readOut) + // do something } }); ``` @@ -2484,7 +2590,7 @@ readSync(buffer: ArrayBuffer, options?: Object): number | number | 实际读取的长度。 | - 示例: - ``` + ```js let ss = fileio.createStreamSync(fpath, "r+"); let num = ss.readSync(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}); ``` @@ -2507,9 +2613,13 @@ read(): Promise<Dirent> | Promise<[Dirent](#dirent)> | 表示异步读取目录项的结果。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); - let dirent = await dir.read(); + dir.read().then(function (dirent){ + console.info("read successfully:"+ dirent.name); + }).catch(function(err){ + console.info("read failed with error:"+ err); + }); ``` @@ -2525,10 +2635,11 @@ read(callback: AsyncCallback<Dirent>): void | callback | AsyncCallback<[Dirent](#dirent)> | 是 | 异步读取下一个目录项之后的回调。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); dir.read(function (err, dirent) { if (!err) { + // do something console.log(dirent.name) } }); @@ -2547,7 +2658,7 @@ readSync(): Dirent | [Dirent](#dirent) | 表示一个目录项。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); let dirent = dir.readSync(); ``` @@ -2560,7 +2671,7 @@ closeSync(): void 用于关闭目录。目录被关闭后,Dir中持有的文件描述将被释放,后续将无法从Dir中读取目录项。 - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); dir.closeSync(); ``` @@ -2590,7 +2701,7 @@ isBlockDevice(): boolean | boolean | 表示当前目录项是否是块特殊设备。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); let isBLockDevice = dir.readSync().isBlockDevice(); ``` @@ -2608,7 +2719,7 @@ isCharacterDevice(): boolean | boolean | 表示当前目录项是否是字符特殊设备。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); let isCharacterDevice = dir.readSync().isCharacterDevice(); ``` @@ -2626,7 +2737,7 @@ isDirectory(): boolean | boolean | 表示当前目录项是否是目录。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); let isDirectory = dir.readSync().isDirectory(); ``` @@ -2644,7 +2755,7 @@ isFIFO(): boolean | boolean | 表示当前目录项是否是FIFO。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); let isFIFO = dir.readSync().isFIFO(); ``` @@ -2662,7 +2773,7 @@ isFile(): boolean | boolean | 表示当前目录项是否是普通文件。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); let isFile = dir.readSync().isFile(); ``` @@ -2680,7 +2791,7 @@ isSocket(): boolean | boolean | 表示当前目录项是否是套接字。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); let isSocket = dir.readSync().isSocket(); ``` @@ -2698,7 +2809,7 @@ isSymbolicLink(): boolean | boolean | 表示当前目录项是否是符号链接。 | - 示例: - ``` + ```js let dir = fileio.opendirSync(dpath); let isSymbolicLink = dir.readSync().isSymbolicLink(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-filemanager.md b/zh-cn/application-dev/reference/apis/js-apis-filemanager.md index 897f1063eadeedf1ce2acfbb392f85139d4e959a..5c520aef02ef740eb995f5deaaf250815dd969c6 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-filemanager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-filemanager.md @@ -1,16 +1,18 @@ # 公共文件访问与管理 - +>![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +>本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 -``` -import filemanager from 'ohos.filemanager' +```js +import filemanager from 'ohos.filemanager'; ``` -## 权限 +## 系统能力 -应用需要拥有SystemCapability.FileManagement.FileManagerService权限 +SystemCapability.FileManagement.FileManagerService ## filemanager.getRoot + getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> 以异步方法获取第一层相册,目录信息。使用promise形式返回结果。 @@ -18,28 +20,26 @@ getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> - 参数 | 参数名 | 类型 | 必填 | 说明 | | --- | --- | --- | -- | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | - 返回值 | 类型 | 说明 | | --- | -- | - | Promise<FileInfo[]> | 第一层目录相册信息 | + | Promise<[FileInfo](#fileinfo)[]> | 第一层目录相册信息 | - 示例 ```js -filemanager.getRoot() -.then((fileInfo) => { +filemanager.getRoot().then((fileInfo) => { if(Array.isArray(fileInfo)) { for (var i = 0; i < fileInfo.length; i++) { console.log(JSON.Stringify(fileInfo)) } } -}) -.catch((err) => { +}).catch((err) => { console.log(err) -}) +}); ``` ## filemanager.getRoot @@ -52,8 +52,8 @@ getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback<FileInfo[]>) | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ----------------------------- | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | - | callback | AsyncCallback<FileInfo[]> | 是 | 异步获取文件的信息之后的回调 | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | + | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - 示例 @@ -78,10 +78,10 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num | --- | --- | --- | -- | | type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" | | path | string | 是 | 待查询目录uri | - | dev | DevInfo | 是 | 设备名, 当前仅支持设备'local' | + | dev | [DevInfo](#devinfo) | 是 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | | offset | number | 否 | 待查询文件偏移 | | count | number | 否 | 待查询文件个数 | - + - 返回值 | 类型 | 说明 | @@ -123,10 +123,10 @@ listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : num | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" | | path | string | 是 | 待查询目录uri | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | | offset | number | 否 | 待查询文件偏移 | | count | number | 否 | 待查询文件个数 | - | callback | AsyncCallback<FileInfo[]> | 是 | 异步获取文件的信息之后的回调 | + | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - 异常 | 错误名称 | 错误类型 | 错误码 | 说明 | @@ -158,7 +158,7 @@ filemanager.createFile(path : string, filename : string, options? : {dev? : DevI | --- | --- | --- | -- | | filename | string | 是 | 待创建的文件名 | | path | string | 是 | 待保存目的相册uri | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | - 返回值 @@ -199,8 +199,8 @@ createFile(path : string, filename: string, options? : {dev? : DevInfo}, callbac | -------- | ------------------------- | ---- | ----------------------------- | | filename | string | 是 | 待创建的文件名 | | path | string | 是 | 待保存目的相册uri | - | dev | DevInfo | 否 | 设备名, 当前仅支持设备'local' | - | callback | AsyncCallback<FileInfo[]> | 是 | 异步获取文件的信息之后的回调 | + | dev | [DevInfo](#devinfo) | 否 | 设备名, 不填为默认值dev = {name: "local"}, 当前仅支持设备'local' | + | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - 异常 @@ -225,6 +225,8 @@ filemanager.createFile(media_path, name, (err, uri) => { ## FileInfo 文件信息类型,通过getRoot, listFile等接口返回的类型。 +### 属性 + | 参数名 | 类型 | 可读 | 可写 | 说明 | | --- | -- | -- | -- | -- | | name | string | 是 | 否 | 文件名称 | @@ -237,6 +239,8 @@ filemanager.createFile(media_path, name, (err, uri) => { ## DevInfo 设备类型,配置接口访问的设备类型。 +### 属性 + | 参数名 | 类型 | 可读 | 可写 | 说明 | | --- | -- | -- | -- | -- | | name | string | 是 | 是 | 设备名称 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashmap.md b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md new file mode 100644 index 0000000000000000000000000000000000000000..751642a8acf530c77a123ecedf14d96d947e14a1 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-hashmap.md @@ -0,0 +1,380 @@ +# 非线性容器HashMap + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import HashMap from '@ohos.util.HashMap' +``` + + +## 权限 + +无 + +## HashMap + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | HashMap的元素个数 | + + +### constructor + +constructor(); + +HashMap的构造函数。 + +- 示例: + ``` + let hashMap = new HashMap(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该HashMap是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const hashMap = new HashMap(); + hashMap.isEmpty(); + ``` + + +### hasKey + +hasKey(key: K): boolean; + +判断此HashMap中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### hasValue + +hasValue(value: V): boolean; + +判断此HashMap中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.hasValue(123); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.hasValue(123); + ``` + + +### get + +get(key: K): V; + +获取指定key所对应的value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回key映射的value值 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + hashMap.get("sdfs"); + ``` + + +### setAll + +setAll(map: HashMap): void; + +将一个HashMap中的所有元素组添加到另一个hashmap中。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | map | HashMap | 是 | 被添加元素的hashmap | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + let newHashMap = new HashMap(); + hashMap.setAll(newHashMap); + ``` + + +### set + +set(key: K, value: V): Object; + +向HashMap中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 添加成员数据的键名 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Object | 返回添加后的hashmap | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + ``` + + +### remove + +remove(key: K): V; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回删除元素的值 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + hashMap.remove("sdfs"); + ``` + + +### clear + +clear(): void; + +清除HashMap中的所有元素,并把length置为0。 + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + hashMap.clear(); + ``` + + +### keys + +keys(): IterableIterator<K>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<K> | 返回一个迭代器 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + let iter = hashMap.keys(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### values + +values(): IterableIterator<V>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<V> | 返回一个迭代器 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + let iter = hashMap.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### replace + +replace(key: K, value: V): boolean; + +对HashMap中一组数据进行更新(替换)。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定替换的元素 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功对已有数据进行替换 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("sdfs", 123); + hashMap.replace("sdfs", 357); + ``` + + +### forEach + +forEach(callbackfn: (value: V, key?: K, hashMap?: HashMap) => void, thisArg?: Object): void; + +通过回调函数来遍历HashMap实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 当前遍历到的元素键值对的值 | + | key | K | 是 | 当前遍历到的元素键值对的键 | + | hashMap | HashMap | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("sdfs", 123); + hashMap.set("dfsghsf", 357); + hashMap.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries + +entries(): IterableIterator<[K, V]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + let iter = hashMap.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<[K, V]>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let hashMap = new HashMap(); + hashMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + hashMap.set("sdfs", 356); + + // 使用方法一: + for (let item of hashMap) { + console.log("key: " + item[0]); + console.log("value: " + item[1]); + } + + // 使用方法二: + let iter = hashMap[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-hashset.md b/zh-cn/application-dev/reference/apis/js-apis-hashset.md new file mode 100644 index 0000000000000000000000000000000000000000..3589c8fdb1e8607152ee2e57e0a070b594ca3345 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-hashset.md @@ -0,0 +1,255 @@ +# 非线性容器HashSet + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import HashSet from '@ohos.util.HashSet'; +``` + +## 权限 + +无 + +## HashSet + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | HashSet的元素个数 | + + +### constructor + +constructor(); + +HashSet的构造函数。 + +- 示例: + ``` + let hashSet = new HashSet(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该HashSet是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const hashSet = new HashSet(); + hashSet.isEmpty(); + ``` + + +### has + +has(value: T): boolean; + +判断此HashSet中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### add + +add(value: T): boolean; + +向HashSet中添加数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 添加成员数据 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 返回是否有成功增加元素 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### remove + +remove(value: T): boolean; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 返回是否成功删除指定元素 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + hashSet.remove("sdfs"); + ``` + + +### clear + +clear(): void; + +清除HashSet中的所有元素,并把length置为0。 + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + hashSet.clear(); + ``` + + +### values + +values(): IterableIterator<T>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + let iter = hashSet.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### forEach + +forEach(callbackfn: (value: T, key?: T, hashSet?: HashSet<T>) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素键值对的值 | + | key | T | 否 | 当前遍历到的元素键值对的值(和value相同) | + | hashSet | HashSet<T> | 否 | 当前调用forEach方法的实例对象 | + + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("sdfs"); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries +entries(): IterableIterator<[T, T]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[T, T]> | 返回一个迭代器 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + let iter = hashSet.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let hashSet = new HashSet(); + hashSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + hashSet.add("sdfs"); + + // 使用方法一: + for (let item of hashSet) { + console.log("value: " + item); + } + + // 使用方法二: + let iter = hashSet[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md b/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md index e0d5f8e146e5df63023b67a078e0c7d5edcb34a3..aec3024d35bcb5205f7d72e7a8bbb35de7b1453c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @@ -11,9 +11,9 @@ import hiAppEvent from '@ohos.hiAppEvent'; ``` -## 权限 +## 系统能力 -无 +SystemCapability.HiviewDFX.HiAppEvent ## hiAppEvent.write diff --git a/zh-cn/application-dev/reference/apis/js-apis-hilog.md b/zh-cn/application-dev/reference/apis/js-apis-hilog.md new file mode 100644 index 0000000000000000000000000000000000000000..10809a70e6554b60481195dc90894f9adea1f896 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-hilog.md @@ -0,0 +1,182 @@ +# 日志打印 + +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +``` +import hilog from '@ohos.hilog'; +``` + +## 系统能力 + +SystemCapability.HiviewDFX.HiLog + +## hilog.debug + +debug(domain: number, tag: string, format: string, ...args: any[]) : void + +debug日志输出,打印debug级别日志。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| domain | number | 是 | 业务领域。范围0x0~0xFFFFF。 | +| tag | string | 是 | 字符串常量,标识调用所在的类或者业务行为。 | +| format | string | 是 | 格式字符串,包含参数类型、隐私标识。未加隐私标识的缺省为隐私参数。 | +| args | any[] | 是 | 与格式字符串里参数类型对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 | + +**示例:** + +``` +hilog.debug(0xFF00, "testTag", "%d: %{private}s World %{public}f", 1, "hello", 3.0); +``` + +**输出:** + +``` +09-08 12:49:35.941 1547 2452 D FF00/testTag: 1: hello World 3.0 +``` + +## **hilog.info** + +info(domain: number, tag: string, format: string, ...args: any[]) : void + +info日志输出,打印info级别日志。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| domain | number | 是 | 业务领域。范围0x0~0xFFFFF。 | +| tag | string | 是 | 字符串常量,标识调用所在的类或者业务行为。 | +| format | string | 是 | 格式字符串,包含参数类型、隐私标识。未加隐私标识的缺省为隐私参数。 | +| args | any[] | 是 | 与格式字符串里参数类型对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 | + +**示例:** + +``` +hilog.info(0xFF00, "testTag", "%d: %{private}s World %{public}f", 1, "hello", 3.0); +``` + +**输出:** + +``` +09-08 12:49:35.941 1547 2452 I FF00/testTag: 1: hello World 3.0 +``` + +## hilog.warn + +warn(domain: number, tag: string, format: string, ...args: any[]) : void + +warn日志输出,打印warn级别日志。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| domain | number | 是 | 业务领域。范围0x0~0xFFFFF。 | +| tag | string | 是 | 字符串常量,标识调用所在的类或者业务行为。 | +| format | string | 是 | 格式字符串,包含参数类型、隐私标识。未加隐私标识的缺省为隐私参数。 | +| args | any[] | 是 | 与格式字符串里参数类型对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 | + +**示例:** + +``` +hilog.warn(0xFF00, "testTag", "%d: %{private}s World %{public}f", 1, "hello", 3.0); +``` + +**输出:** + +``` +09-08 12:49:35.941 1547 2452 W FF00/testTag: 1: hello World 3.0 +``` + +## hilog.error + +error(domain: number, tag: string, format: string, ...args: any[]) : void + +error日志输出,打印error级别日志。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| domain | number | 是 | 业务领域。范围0x0~0xFFFFF。 | +| tag | string | 是 | 字符串常量,标识调用所在的类或者业务行为。 | +| format | string | 是 | 格式字符串,包含参数类型、隐私标识。未加隐私标识的缺省为隐私参数。 | +| args | any[] | 是 | 与格式字符串里参数类型对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 | + +**示例:** + +``` +hilog.error(0xFF00, "testTag", "%d: %{private}s World %{public}f", 1, "hello", 3.0); +``` + +**输出:** + +``` +09-08 12:49:35.941 1547 2452 E FF00/testTag: 1: hello World 3.0 +``` + +## hilog.fatal + +fatal(domain: number, tag: string, format: string, ...args: any[]) : void + +fatal日志输出,打印fatal级别日志。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| domain | number | 是 | 业务领域。范围0x0~0xFFFFF。 | +| tag | string | 是 | 字符串常量,标识调用所在的类或者业务行为。 | +| format | string | 是 | 格式字符串,包含参数类型、隐私标识。未加隐私标识的缺省为隐私参数。 | +| args | any[] | 是 | 与格式字符串里参数类型对应的可变长度参数列表。参数数目、参数类型必须与格式字符串中的标识一一对应。 | + +**示例:** + +``` +hilog.fatal(0xFF00, "testTag", "%d: %{private}s World %{public}f", 1, "hello", 3.0); +``` + +**输出:** + +``` +09-08 12:49:35.941 1547 2452 F FF00/testTag: 1: hello World 3.0 +``` + +## hilog.isLoggable + +isLoggable(domain: number, tag: string, level: LogLevel) : boolean + +检查一个domain、tag和日志级别是否被禁止打印日志。 + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | --------------------- | ---- | ------------------------------------------ | +| domain | number | 是 | 业务领域。范围0x0~0xFFFFF。 | +| tag | string | 是 | 字符串常量,标识调用所在的类或者业务行为。 | +| level | [LogLevel](#loglevel) | 是 | 日志级别。 | + +**示例:** + +``` +hilog.isLoggable(0xFF00, "testTag", hilog.DEBUG); +``` + +## LogLevel + +用于表示事件类型。 + +| 名称 | 默认值 | 说明 | +| ----- | ------ | ----------- | +| DEBUG | 3 | DEBUG级别。 | +| INFO | 4 | INFO级别。 | +| WARN | 5 | WARN级别。 | +| ERROR | 6 | ERROR级别。 | +| FATAL | 7 | FATAL级别。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md new file mode 100644 index 0000000000000000000000000000000000000000..b05217f58a56e2bb69fff3753dcceb88d1f2619a --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightmap.md @@ -0,0 +1,551 @@ +# 非线性容器LightWeightMap + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import LightWeightMap from '@ohos.util.LightWeightMap' +``` + + +## 权限 + +无 + +## LightWeightMap + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | LightWeightMap的元素个数 | + + +### constructor + +constructor(); + +LightWeightMap的构造函数。 + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该LightWeightMap是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const lightWeightMap = new LightWeightMap(); + lightWeightMap.isEmpty(); + ``` + + +### hasAll + +hasAll(map: LightWeightMap): boolean; + +判断此LightWeightMap中是否含有该指定map中的所有元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | map | LightWeightMap | 是 | 比较对象 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含所有元素 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let map = new LightWeightMap(); + map.set("sdfs", 356); + let result = lightWeightMap.hasAll(map); + ``` + + +### hasKey + +hasKey(key: K): boolean; + +判断此LightWeightMap中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### hasValue + +hasValue(value: V): boolean; + +判断此LightWeightMap中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.hasValue(123); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.hasValue(123); + ``` + + +### increaseCapacityTo + +increaseCapacityTo(minimumCapacity: number): void; + +将当前LightWeightMap扩容至可以容纳指定数量元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | minimumCapacity | number | 是 | 需要容纳数量 | + + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.increaseCapacityTo(10); + ``` + + +### get + +get(key: K): V; + +获取指定key所对应的value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回key映射的value值 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.get("sdfs"); + ``` + + +### getIndexOfKey + +getIndexOfKey(key: K): number; + +查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 被查找的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.getIndexOfKey("sdfs"); + ``` + + +### getIndexOfValue + +getIndexOfValue(value: V): number; + +查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 被查找的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.getIndexOfValue(123); + ``` + + +### getKeyAt + +getKeyAt(index: number): K; + +查找指定下标的元素键值对中key值,否则返回undefined。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 所查找的下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回该下标对应的元素键值对中key值 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.getKeyAt(1); + ``` + + +### setAll + +setAll(map: LightWeightMap): void; + +将一个LightWeightMap中的所有元素组添加到另一个lightweightmap中。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | map | LightWeightMap | 是 | 被添加元素的lightweightmap | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let map = new LightWeightMap(); + lightWeightMap.setAll(map); + ``` + + +### set +set(key: K, value: V): Object; + +向LightWeightMap中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 添加成员数据的键名 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Object | 返回添加后的hashmap | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + ``` + + +### remove + +remove(key: K): V; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回删除元素的值 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.remove("sdfs"); + ``` + + +### removeAt + +removeAt(index: number): boolean; + +删除指定下标的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定想要删除元素下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 确认是否成功删除元素 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.removeAt(1); + ``` + + +### setValueAt + +setValueAt(index: number, newValue: V): boolean; + +向LightWeightMap中具体位置替换键值对中的值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定替换数据下标 | + | newValue | V | 是 | 替换键值对中的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功替换指定位置数据 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.setValueAt(1, 3546); + ``` + + +### getValueAt + +getValueAt(index: number): V; + +获取LightWeightMap中具体位置键值对中的值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定查询数据下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回指定位置中键值对的值 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.getValueAt(1); + ``` + + +### clear + +clear(): void; + +清除LightWeightMap中的所有元素,并把length置为0。 + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + lightWeightMap.clear(); + ``` + + +### keys + +keys(): IterableIterator<K>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<K> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let iter = lightWeightMap.keys(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### values + +values(): IterableIterator<V>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<V> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let iter = lightWeightMap.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### forEach + +forEach(callbackfn: (value: V, key?: K, lightWeightMap?: LightWeightMap) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 当前遍历到的元素键值对的值 | + | key | K | 是 | 当前遍历到的元素键值对的键 | + | lightWeightMap | LightWeightMap | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("sdfs", 123); + lightWeightMap.set("dfsghsf", 357); + lightWeightMap.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries + +entries(): IterableIterator<[K, V]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + let iter = lightWeightMap.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<[K, V]>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightMap = new LightWeightMap(); + lightWeightMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + lightWeightMap.set("sdfs", 356); + + // 使用方法一: + for (let item of lightWeightMap) { + console.log("key: " + item[0]); + console.log("value: " + item[1]); + } + + // 使用方法二: + let iter = lightWeightMap[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md new file mode 100644 index 0000000000000000000000000000000000000000..353250ebdcb353a0ed9843b09c70869dba7a7b69 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-lightweightset.md @@ -0,0 +1,463 @@ +# 非线性容器LightWeightSet + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import LightWeightSet from '@ohos.util.LightWeightSet' +``` + + +## 权限 + +无 + +## LightWeightSet + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | LightWeightSet的元素个数 | + + +### constructor + +constructor(); + +LightWeightSet的构造函数。 + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该容器是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const lightWeightSet = new LightWeightSet(); + lightWeightSet.isEmpty(); + ``` + +### add + +add(value: T): boolean; + +向此容器中添加数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 添加的成员数据 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功添加元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### addAll + +addAll(set: LightWeightSet<T>): boolean; + +将另一个容器中的所有元素组添加到当前容器中。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | set | LightWeightSet<T> | 是 | 提供添加元素的lightweightmap | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let set = new LightWeightSet(); + set.add("sfage"); + lightWeightSet.addAll(set); + ``` + + +### hasAll + +hasAll(set: LightWeightSet<T>): boolean; + +判断此容器中是否含有该指定set中的所有元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | set | LightWeightSet<T> | 是 | 比较对象 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含所有元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let set = new LightWeightSet(); + set.add("sdfs"); + let result = lightWeightSet.hasAll(set); + ``` + + +### has + +has(value: T): boolean; + +判断此容器中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.has(123); + lightWeightSet.add(123); + lightWeightSet.has(123); + ``` + + +### equal + +equal(obj: Object): boolean; + +判断此容器中是否含有该指定obj同类型。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | obj | Object | 是 | 比较对象 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否构成类型相同 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let obj = {"Ahfbrgrbgnutfodgorrogorgrogofdfdf", "sdfs"}; + let result = lightWeightSet.equal(obj); + ``` + + +### ensureCapacityTo + +ensureCapacityTo(minimumCapacity: number): void; + +将当前容器扩容至可以容纳指定数量元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | minimumCapacity | number | 是 | 需要容纳数量 | + + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.ensureCapacityTo(10); + ``` + + +### getIndexOf + +getIndexOf(key: T): number; + +获取指定key所对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 在lightweightset中指定数据的下标 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.getIndexOf("sdfs"); + ``` + + +### remove + +remove(key: T): T; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除元素的值 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.remove("sdfs"); + ``` + + +### removeAt + +removeAt(index: number): boolean; + +删除指定下标的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定想要删除元素下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 确认是否成功删除元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.removeAt(1); + ``` + + +### getValueAt + +getValueAt(index: number): T; + +获取此容器中具体位置的元素 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定查询数据下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回指定位置中元素 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.getValueAt(1); + ``` + + +### clear + +clear(): void; + +清除容器中的所有元素,并把length置为0。 + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.clear(); + ``` + + +### toString + +toString(): String; + +获取包含容器中所有键和值的字符串。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | String | 返回一个字符串 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.toString(); + ``` + + +### toArray + +toArray(): Array<T>; + +获取包含此容器中所有对象的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回一个数组 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + lightWeightSet.toString(); + ``` + + +### values + +values(): IterableIterator<T>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let iter = lightWeightSet.values(); + let index = 0; + while(index < lightWeightSet.length) { + console.log(JSON.stringify(iter.next().value)); + index++; + } + ``` + + +### forEach + +forEach(callbackfn: (value: T, key?: T, lightWeightSet?: LightWeightSet<T>) => void, thisArg?: Object): void; + +通过回调函数来遍历LightWeightSet实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | key | T | 否 | 当前遍历到的元素(和value相同) | + | lightWeightSet | LightWeightSet<T> | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("sdfs"); + lightWeightSet.add("dfsghsf"); + lightWeightSet.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries + +entries(): IterableIterator<[T, T]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[T, T]> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + let iter = lightWeightSet.entries(); + let index = 0; + while(index < lightWeightSet.length) { + console.log(JSON.stringify(iter.next().value)); + index++; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let lightWeightSet = new LightWeightSet(); + lightWeightSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + lightWeightSet.add("sdfs"); + + // 使用方法一: + for (let item of lightWeightSet) { + console.log("value: " + item); + } + + // 使用方法二: + let iter = lightWeightSet[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md new file mode 100644 index 0000000000000000000000000000000000000000..385391288e46dd506618e3c19f0b2074af407abe --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-linkedlist.md @@ -0,0 +1,551 @@ +# 线性容器LinkedList + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import LinkedList from '@ohos.util.LinkedList' +``` + + +## 权限 + +无 + + +## LinkedList + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | LinkedList的元素个数 | + + +### constructor + +constructor(_head?: NodeObj<T>, _tail?: NodeObj<T>); + +LinkedList的构造函数。 + +- 参数: + | 参数名 | 类型 | 可读 | 可写 | 说明 | + | -------- | -------- | -------- | -------- | -------- | + | _head | NodeObj<T> | 是 | 否 | 入参对象,节点对象,含有element,和next指向,和prev指向 | + | _tail | NodeObj<T> | 是 | 否 | 入参对象,节点对象,含有element,和next指向,和prev指向 | + +- 示例: + ``` + let linkedList = new LinkedList(); + ``` + + +### add + +add(element: T): boolean; + +在LinkedList尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add("a"); + linkedList.add(1); + let b = [1, 2, 3]; + linkedList.add(b); + let c = {name : "lala", age : "13"}; + linkedList.add(false); + ``` +### addFirst + +addFirst(element: T): void; + +在LinkedList头部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.addFirst("a"); + linkedList.addFirst(1); + let b = [1, 2, 3]; + linkedList.addFirst(b); + let c = {name : "lala", age : "13"}; + linkedList.addFirst(false); + ``` + +### insert + +insert(element: T, index: number): void; + +在长度范围内任意插入指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 被插入的元素 | + | index | number | 是 | 被插入的位置索引 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.insert("A", 0); + linkedList.insert(0, 1); + linkedList.insert(true, 2); + ``` + +### has + +has(element: T): boolean; + +判断此LinkedList中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.has("Ahfbrgrbgnutfodgorrogorg"); + linkedList.add("Ahfbrgrbgnutfodgorrogorg"); + linkedList.has("Ahfbrgrbgnutfodgorrogorg"); + ``` + +### get + +get(index: number): T; + +根据下标获取LinkedList中的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 根据下标查找到的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(1); + linkedList.add(2); + linkedList.add(4); + linkedList.get(2); + ``` +### getLastIndexOf + +getLastIndexOf(element: T): number; + +返回指定元素最后一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素最后一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(1); + linkedList.add(2); + linkedList.add(4); + linkedList.getLastIndexOf(2); + ``` + +### getIndexOf + +getIndexOf(element: T): number; + +返回指定元素第一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(1); + linkedList.add(2); + linkedList.add(4); + linkedList.getIndexOf(2); + ``` +### removeByIndex + +removeByIndex(index: number): T; + +根据元素的下标值查找元素,返回元素后将其删除。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定元素的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(4); + linkedList.removeByIndex(2); + ``` +### removeFirst + +removeFirst(): T; + +删除并返回LinkedList的第一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(4); + linkedList.removeFirst(); + ``` +### removeLast + +removeLst(): T; + +删除并返回LinkedList的最后一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(2); + linkedList.add(4); + linkedList.removeLast(); + ``` + +### remove + +remove(element: T): boolean; + +删除查找到的第一个指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.remove(2); + ``` +### removeFirstFound + +removeFirstFound(element: T): boolean; + +删除第一次出现的指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.removeFirstFound(4); + ``` +### removeLastFound + +removeLastFound(element: T): boolean; + +删除最后一次出现的指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.removeLastFound(4); + ``` +### clone +clone(): LinkedList<T>; + +克隆一个与LinkedList一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | LinkedList<T> | 返回LinkedList对象实例 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.clone(); + ``` +### forEach +forEach(callbackfn: (value: T, index?: number, linkedlist?: LinkedList<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历LinkedList实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | linkedlist | LinkedList<T> | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.forEach((value, index) => { + console.log(value, index); + }); + ``` +### clear +clear(): void; + +清除LinkedList中的所有元素,并把length置为0。 + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.clear(); + ``` +### set +set(index: number, element: T): T; +将此 LinkedList 中指定位置的元素替换为指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 查找的下标值 | + | element | T | 是 | 用来替换的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T类型 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.set(2, "b"); + ``` +### convertToArray +convertToArray(): Array<T>; + +把当前LinkedList实例转换成数组,并返回转换后的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回数组类型 | + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.convertToArray(); + ``` + +### getFirst + +getFirst(): T; +获取LinkedList实例中的第一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.getFirst(); + ``` +### getLast + +getLast(): T; +获取LinkedList实例中的最后一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + linkedList.getLast(); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器。 | + + +- 示例: + ``` + let linkedList = new LinkedList(); + linkedList.add(2); + linkedList.add(4); + linkedList.add(5); + linkedList.add(4); + + // 使用方法一: + for (let item of linkedList) { + console.log(item); + } + + // 使用方法二: + let iter = linkedList[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-list.md b/zh-cn/application-dev/reference/apis/js-apis-list.md new file mode 100644 index 0000000000000000000000000000000000000000..bef7e6b9b4346110aff2868d616dfc8afafebc1c --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-list.md @@ -0,0 +1,561 @@ +# 线性容器List + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import List from '@ohos.util.List' +``` + + +## 权限 + +无 + + +## List + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | List的元素个数 | + + +### constructor + +constructor(_head?: NodeObj<T>); + +List的构造函数。 + +- 参数: + | 参数名 | 类型 | 可读 | 可写 | 说明 | + | -------- | -------- | -------- | -------- | -------- | + | _head | NodeObj<T> | 是 | 否 | 入参对象,节点对象,含有element,和next指向 | + +- 示例: + ``` + let list = new List(); + ``` + + +### add + +add(element: T): boolean; + +在List尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let list = new List; + list.add("a"); + list.add(1); + let b = [1, 2, 3]; + list.add(b); + let c = {name : "lala", age : "13"}; + list.add(false); + ``` + +### insert + +insert(element: T, index: number): void; + +在长度范围内任意位置插入指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 被插入的元素 | + | index | number | 是 | 被插入的位置索引 | + +- 示例: + ``` + let list = new List(); + list.insert("A", 0); + list.insert(0, 1); + list.insert(true, 2); + ``` + +### has + +has(element: T): boolean; + +判断此List中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let list = new List(); + list.has("Ahfbrgrbgnutfodgorrogorg"); + list.add("Ahfbrgrbgnutfodgorrogorg"); + list.has("Ahfbrgrbgnutfodgorrogorg"); + ``` + +### get + +get(index: number): T; + +根据下标获取List中的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 要查找的下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 根据下标查找到的元素 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + list.add(1); + list.add(2); + list.add(4); + list.get(2); + ``` +### getLastIndexOf + +getLastIndexOf(element: T): number; + +查找指定元素最后一次出现的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 查找指定元素最后一次出现的下标值,查找失败返回-1 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + list.add(1); + list.add(2); + list.add(4); + list.getLastIndexOf(2); + ``` + +### getIndexOf + +getIndexOf(element: T): number; + +查找指定元素第一次出现的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回第一次找到指定元素的下标,没有找到返回-1 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + list.add(1); + list.add(2); + list.add(4); + list.getIndexOf(2); + ``` + +### equal + +equal(obj: Object): boolean; + +比较指定对象与此List是否相等。如果对象与此列表相同,返回true,否则返回false。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | obj | Object | 是 | 用来比较的对象 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 返回boolean类型 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + let obj1 = new List(); + obj1.add(2); + obj1.add(4); + obj1.add(5); + list.equal(obj1); + let obj2 = {name : "lala", age : "13"}; + list.equal(obj2); + ``` +### removeByIndex + +removeByIndex(index: number): T; + +根据元素的下标值查找元素,返回元素后将其删除。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定元素的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(2); + list.add(4); + list.removeByIndex(2); + ``` + +### remove + +remove(element: T): boolean; + +删除查找到的第一个指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.remove(2); + ``` + +### replaceAllElements +replaceAllElements(callbackfn: (value: T, index?: number, list?: List<T>) => T, +thisArg?: Object): void; + +用户操作List中的元素,用操作后的元素替换原元素并返回操作后的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | list | List<T> | 否 | 当前调用replaceAllElements方法的实例对象 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.replaceAllElements((value, index) => { + return value = 2 * value; + }); + list.replaceAllElements((value, index) => { + return value = value - 2; + }); + ``` +### forEach +forEach(callbackfn: (value: T, index?: number, list?: List<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历List实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素。 | + | index | number | 否 | 当前遍历到的下标值。 | + | list | List<T> | 否 | 当前调用forEach方法的实例对象 | + + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.forEach((value, index) => { + console.log(value, index); + }); + + ``` +### sort +sort(comparator: (firstValue: T, secondValue: T) => number): void; + +对List中的元素进行一个排序操作。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 是 | 回调函数。 | + +- comparator的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | firstValue | T | 是 | 前一项元素 | + | secondValue | T | 是 | 后一项元素 | + + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.sort(a, (b => a - b)); + list.sort(a, (b => b - a)); + ``` +### getSubList +getSubList(fromIndex: number, toIndex: number): List<T>; + +根据下标截取List中的一段元素,并返回这一段List实例,包括起始值但不包括终止值。 +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | List<T> | 返回List对象实例 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.subList(2, 4); + list.subList(4, 3); + list.subList(2, 6); + ``` + +### clear +clear(): void; + +清除List中的所有元素,并把length置为0。 + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.clear(); + ``` +### set +set(index: number, element: T): T; +将此 List 中指定位置的元素替换为指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 查找的下标值 | + | element | T | 是 | 用来替换的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T类型 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.set(2, "b"); + + ``` +### convertToArray +convertToArray(): Array<T>; + +把当前List实例转换成数组,并返回转换后的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回数组类型 | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.convertToArray(); + ``` +### isEmpty +isEmpty(): boolean; + +判断该List是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.isEmpty(); + ``` +### getFirst + +getFirst(): T; +获取List实例中的第一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let list = new Vector(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.getFirst(); + ``` +### getLast + +getLast(): T; +获取List实例中的最后一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let list = new Vector(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + list.getLast(); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器。 | + + +- 示例: + ``` + let list = new List(); + list.add(2); + list.add(4); + list.add(5); + list.add(4); + + // 使用方法一: + for (let item of list) { + console.log(item); + } + + // 使用方法二: + let iter = list[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-media.md b/zh-cn/application-dev/reference/apis/js-apis-media.md index 8855a83325232bff6fa06fdcf142f17f9100f307..21af291759b0e9c973a051ce31c2b5e660311e67 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-media.md +++ b/zh-cn/application-dev/reference/apis/js-apis-media.md @@ -575,6 +575,7 @@ prepare(config: AudioRecorderConfig): void **示例:** ``` +var audiorecorder = media.createAudioRecorder(); let audioRecorderConfig = { audioEncoder : AAC_LC , audioEncodeBitRate : 22050, @@ -596,6 +597,7 @@ start(): void **示例:** ``` +var audiorecorder = media.createAudioRecorder(); audiorecorder.start(); ``` @@ -608,6 +610,7 @@ stop(): void **示例:** ``` +var audiorecorder = media.createAudioRecorder(); audiorecorder.stop(); ``` @@ -620,6 +623,7 @@ release(): void **示例:** ``` +var audiorecorder = media.createAudioRecorder(); audiorecorder.release(); ``` @@ -634,6 +638,7 @@ reset(): void **示例:** ``` +var audiorecorder = media.createAudioRecorder(); audiorecorder.reset(); ``` @@ -653,6 +658,7 @@ on(type: 'prepare' | 'start' | 'stop' | 'release' | 'reset', callback: () => voi **示例:** ``` +var audiorecorder = media.createAudioRecorder(); audiorecorder.on('prepare', () => { console.log('Preparation succeeded.'); audiorecorder.start(); diff --git a/zh-cn/application-dev/reference/apis/js-apis-notification.md b/zh-cn/application-dev/reference/apis/js-apis-notification.md index 02964d02cf598c71a0febb23db10d47b1ecacc69..881bf945bc79614c36f7b574dba1456945644992 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-notification.md +++ b/zh-cn/application-dev/reference/apis/js-apis-notification.md @@ -6,6 +6,12 @@ import Notification from '@ohos.notification'; ``` +## 系统能力 + +```js +SystemCapability.Notification.Notification +``` + ## Notification.publish(request: NotificationRequest, callback: AsyncCallback\) - 接口说明 diff --git a/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md b/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md index 0e2cad1377516dab8e71878eea75c8938aaea29b..0730011d84859cb178d328a94fdbef118a6ac0a5 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @@ -370,4 +370,171 @@ abilityStartSetting属性是一个定义为[key: string]: any的对象,key对 | WINDOW_MODE_FULLSCREEN | 1 | 全屏。 | | WINDOW_MODE_SPLIT_PRIMARY | 100 | 分屏主屏。 | | WINDOW_MODE_SPLIT_SECONDARY | 101 | 分屏次屏。 | -| WINDOW_MODE_FLOATING | 102 | 悬浮窗。 | \ No newline at end of file +| WINDOW_MODE_FLOATING | 102 | 悬浮窗。 | + + +## particleAbility.startBackgroundRunning + +startBackgroundRunning(id: number, request: NotificationRequest, callback: AsyncCallback<void>): void; + +向系统申请长时任务,使用callback形式返回结果。(此接口为api7接口,后续会被废弃,请使用新的api8接口) + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | id | number | 是 | 长时任务通知id号 | + | request | NotificationRequest | 是 | 通知参数,用于显示通知栏的信息 | + | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | + +- **示例**: +```js +import notification from '@ohos.notification'; +import particleAbility from '@ohos.ability.particleAbility'; +import wantAgent from '@ohos.wantAgent'; + +function callback(err, data) { + if (err) { + console.error("Operation failed Cause: " + err); + } else { + console.info("Operation succeeded"); + } +} + +let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] +}; + +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + let basicContent = { + title: "title", + text: "text" + }; + let notificationContent = { + contentType: notification.ContentType.NOTIFICATION_CONTENT_TEXT, + normal: basicContent + }; + let request = { + content: notificatonContent, + wantAgent: wantAgentObj + }; + let id = 1; + particleAbility.startBackgroundRunning(id, request, callback); +}); + +``` + +## particleAbility.startBackgroundRunning + +startBackgroundRunning(id: number, request: NotificationRequest): Promise<void> + +向系统申请长时任务,使用promise形式返回结果。(此接口为api7接口,后续会被废弃,请使用新的api8接口) + +**参数**: +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| id | number | 是 | 长时任务通知id号 | +| request | NotificationRequest | 是 | 通知参数,用于显示通知栏的信息 | + +**返回值** +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 使用Promise形式返回结果。 | + +- **示例**: +```js +import notification from '@ohos.notification'; +import particleAbility from '@ohos.ability.particleAbility'; +import wantAgent from '@ohos.wantAgent'; + +let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESET_FLAG] +}; + +wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + let basicContent = { + title: "title", + text: "text" + }; + let notificationContent = { + contentType: notification.ContentType.NOTIFICATION_CONTENT_TEXT, + normal: basicContent + }; + let request = { + content: notificatonContent, + wantAgent: wantAgentObj + }; + let id = 1; + particleAbility.startBackgroundRunning(id, request).then(() => { + console.info("Operation succeeded"); + }).catch((err) => { + console.error("Operation failed Cause: " + err); + }); +}); + +``` + +## particleAbility.cancelBackgroundRunning + +cancelBackgroundRunning(callback: AsyncCallback<void>): void; + +向系统申请取消长时任务,使用callback形式返回结果。(此接口为api7接口,后续会被废弃,请使用新的api8接口) + +- **参数**: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | + +- **示例**: +```js +import particleAbility from '@ohos.ability.particleAbility'; + +function callback(err, data) { + if (err) { + console.error("Operation failed Cause: " + err); + } else { + console.info("Operation succeeded"); + } +} + +particleAbility.cancelBackgroundRunning(callback); + +``` + +## particleAbility.cancelBackgroundRunning + +cancelBackgroundRunning(): Promise<void>; + +向系统申请取消长时任务,使用promise形式返回结果。(此接口为api7接口,后续会被废弃,请使用新的api8接口) + +**返回值** +| 类型 | 说明 | +| -------------- | ------------------------- | +| Promise\ | 使用Promise形式返回结果。 | + +- **示例**: +```js +import particleAbility from '@ohos.ability.particleAbility'; + +particleAbility.cancelBackgroundRunning().then(() => { + console.info("Operation succeeded"); +}).catch((err) => { + console.error("Operation failed Cause: " + err); +}); + +``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-plainarray.md b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md new file mode 100644 index 0000000000000000000000000000000000000000..f8657b795f73c6238842c81b245cb7e52ad7f8ca --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-plainarray.md @@ -0,0 +1,421 @@ +# 非线性容器PlainArray + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import PlainArray from '@ohos.util.PlainArray' +``` + + +## 权限 + +无 + +## PlainArray + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | PlainArray的元素个数 | + + +### constructor + +constructor(); + +PlainArray的构造函数。 + +- 示例: + ``` + let plainArray = new PlainArray(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该容器是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const plainArray = new PlainArray(); + plainArray.isEmpty(); + ``` + + +### has + +has(key: number): boolean; + +判断此容器中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 查询的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.has(1); + plainArray.add(1, "sddfhf"); + plainArray.has(1); + ``` + + +### get + +get(key: number): T; + +获取指定key所对应的value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回key映射的value值 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.get(1); + ``` + + +### getIndexOfKey + +getIndexOfKey(key: number): number; + +查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 被查找的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.getIndexOfKey("sdfs"); + ``` + + +### getIndexOfValue + +getIndexOfValue(value: T): number; + +查找指定元素第一次出现的下标值,如果没有找到该元素返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 被查找的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.getIndexOfValue("sddfhf"); + ``` + + +### getKeyAt + +getKeyAt(index: number): number; + +查找指定下标的元素键值对中key值,否则返回undefined。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 所查找的下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回该下标对应的元素键值对中key值 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.getKeyAt(1); + ``` + + +### clone + +clone(): PlainArray<T>; + +克隆一个一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | PlainArray<T> | 返回新的对象实例 | + +- 示例: + ``` + let plainArray = new ArrayList(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + let newPlainArray = plainArray.clone(); + ``` + + +### add + +add(key: number, value: T): boolean; + +向容器中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 添加成员数据的键名 | + | value | T | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 确认是否成功添加 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + ``` + + +### remove + +remove(key: number): T; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | number | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除元素的值 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.remove(2); + ``` + + +### removeAt + +removeAt(index: number): boolean; + +删除指定下标的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定想要删除元素下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 确认是否成功删除元素 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.removeAt(1); + ``` + + +### removeRangeFrom + +removeRangeFrom(index: number, size: number): number; + +删除一定范围内的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 删除元素的起始下标 | + | size | number | 是 | 期望删除元素个数 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 实际删除元素个数 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.removeAt(1, 3); + ``` + + +### setValueAt + +setValueAt(index: number, newValue: T): void; + +向容器中具体位置替换键值对中的值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定替换数据下标 | + | newValue | T | 是 | 替换键值对中的值 | + + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.setValueAt(1, 3546); + ``` + + +### toString + +toString(): String; + +获取包含容器中所有键和值的字符串。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | String | 返回一个字符串 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.toString(); + ``` + + +### clear + +clear(): void; + +清除容器中的所有元素,并把length置为0。 + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.clear(); + ``` + + +### forEach + +forEach(callbackfn: (value: T, key?: number, plainArray?: PlainArray) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素键值对的值 | + | key | number | 是 | 当前遍历到的元素键值对的键 | + | plainArray | PlainArray | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + plainArray.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<[number, T]>; + +返回一个迭代器,迭代器的每一项都是一个 JavaScript对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[number, T]> | 返回一个迭代器 | + +- 示例: + ``` + let plainArray = new PlainArray(); + plainArray.add(1, "sddfhf"); + plainArray.add(2, "sffdfhf"); + + // 使用方法一: + for (let item of plainArray) { + console.log("index: " + item[0]); + console.log("value: " + item[1]); + } + + // 使用方法二: + let iter = plainArray[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-power.md b/zh-cn/application-dev/reference/apis/js-apis-power.md index 8304b440be0a7fa40c3be3af046863b6cb2da3af..281e065072a9cbd418ab2755255613665be337b9 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-power.md +++ b/zh-cn/application-dev/reference/apis/js-apis-power.md @@ -10,14 +10,9 @@ import power from '@ohos.power'; ``` +## 系统能力 -## 权限 - -关机权限: ohos.permission.SHUTDOWN - -重启权限: ohos.permission.REBOOT - -重启并进入recovery模式的权限:ohos.permission.REBOOT_RECOVERY +SystemCapability.PowerManager.PowerManager ## power.shutdownDevice @@ -26,6 +21,8 @@ shutdownDevice(reason: string): void 系统关机。 +需要权限:ohos.permission.SHUTDOWN + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -44,6 +41,8 @@ rebootDevice(reason: string): void 重启设备。 +需要权限:ohos.permission.REBOOT(重启权限)、ohos.permission.REBOOT_RECOVERY(重启并进入recovery模式的权限) + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-process.md b/zh-cn/application-dev/reference/apis/js-apis-process.md index 5aa3245c385bfbaa6d6f190ec708844dbc5ec51f..d7a2671e56c1d12b6a54d0e73e0aaf8f45ffbe54 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-process.md +++ b/zh-cn/application-dev/reference/apis/js-apis-process.md @@ -11,11 +11,6 @@ import process from '@ohos.process'; ``` -## 权限 - -无 - - ## 属性 | 名称 | 类型 | 可读 | 可写 | 说明 | @@ -143,12 +138,12 @@ kill函数用来发送信号给子进程,结束指定进程。 isIsolatedProcess(): boolean -检查进程是否被隔离。 +判断进程是否被隔离。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 进程是否隔离 | + | boolean | 返回判断结果,如果返回true表示进程被隔离。 | - 示例: ``` @@ -160,17 +155,17 @@ isIsolatedProcess(): boolean isAppUid(v:number): boolean -判断是否特定程序的uid。 +判断uid是否属于应用程序。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | v | number | 是 | 进程的id。 | + | v | number | 是 | 应用程序的uid。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 是否是当前app的uid | + | boolean | 返回判断结果,如果返回true表示为应用程序的uid。| - 示例: ``` @@ -182,12 +177,12 @@ isAppUid(v:number): boolean is64Bit(): boolean -判断运行环境是不是64位。 +判断运行环境是否64位。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 是不是64位环境 | + | boolean | 返回判断结果,如果返回true表示为64位环境。 | - 示例: ``` @@ -204,12 +199,12 @@ getUidForName(v:string): number - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | v | string | 是 | 进程name | + | v | string | 是 | 进程名。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 进程的uid | + | number | 返回进程uid。| - 示例: ``` @@ -221,17 +216,17 @@ getUidForName(v:string): number getThreadPriority(v:number): number -根据指定的 TID 获取线程优先级。 +根据指定的tid获取线程优先级。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | v | number | 是 | 进程的id | + | v | number | 是 | 指定的线程tid。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 进程的优先级 | + | number | 返回线程的优先级。 | - 示例: ``` @@ -249,31 +244,13 @@ getStartRealtime() :number - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 时间 | + | number | 返回经过的实时时间。| - 示例: ``` var realtime = process.getStartRealtime(); ``` - -## process.getAvailableCores8+ - -getAvailableCores() :number[] - -获取多核设备上当前进程可用的 CPU 内核。 - -- 返回值: - | 类型 | 说明 | - | -------- | -------- | - | number[] | 可用内核数 | - -- 示例: - ``` - var result = getAvailableCores(); - ``` - - ## process.getPastCputime8+ getPastCputime() :number @@ -283,7 +260,7 @@ getPastCputime() :number - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 时间 | + | number | 返回经过的CPU时间。 | - 示例: ``` @@ -295,17 +272,17 @@ getPastCputime() :number getSystemConfig(name:number): number -用该方法发送signal到指定的进程。 +获取系统配置信息。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | number | 是 | 系统配置参数名 | + | name | number | 是 | 指定系统配置参数名。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 配置信息 | + | number | 返回系统配置信息。 | - 示例: ``` @@ -323,12 +300,12 @@ getEnvironmentVar(name:string): string - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | string | 是 | 环境名 | + | name | string | 是 | 环境变量名。 | - 返回值: | 类型 | 说明 | | -------- | -------- | - | string | 环境名对应的value | + | string | 返回环境变量名对应的value。 | - 示例: ``` @@ -367,7 +344,7 @@ runCmd(command: string, options?: { timeout : number, killSignal :number | str var result = child.wait(); child.getOutput.then(val=>{ console.log("child.getOutput = " + val); - } + }) ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-queue.md b/zh-cn/application-dev/reference/apis/js-apis-queue.md new file mode 100644 index 0000000000000000000000000000000000000000..30eb24a15f2e4fe6d03b8fcae31c84ebb4a98d60 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-queue.md @@ -0,0 +1,180 @@ +# 线性容器Queue + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import Queue from '@ohos.util.Queue' +``` + + +## 权限 + +无 + + +## Queue + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | Queue的元素个数 | + + +### constructor + +constructor(); + +Queue的构造函数。 + + +- 示例: + ``` + let queue = new Queue(); + ``` + + +### add + +add(element: T): boolean; + +在队列尾部插入元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let queue = new Queue(); + queue.add("a"); + queue.add(1); + let b = [1, 2, 3]; + queue.add(b); + let c = {name : "lala", age : "13"}; + queue.add(false); + ``` + +### pop + +pop(): T + +删除头元素并返回该删除元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let queue = new Queue(); + queue.add(2); + queue.add(4); + queue.add(5); + queue.add(2); + queue.add(4); + queue.pop(); + ``` + +### getFirst + +getFirst(): T; + +获取队列的头元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回尾元素 | + +- 示例: + ``` + let queue = new Queue(); + queue.add(2); + queue.add(4); + queue.add(5); + queue.add(2); + queue.getFirst(); + ``` + +### forEach +forEach(callbackfn: (value: T, index?: number, queue?: Queue<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历Queue实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数。 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | queue | Queue<T> | 否 | 当前调用forEach方法的实例对象 | + + +- 示例: + ``` + let queue = new Queue(); + queue.add(2); + queue.add(4); + queue.add(5); + queue.add(4); + queue.forEach((value, index) => { + console.log(value, index); + }); + + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + + +- 示例: + ``` + let queue = new Queue(); + queue.add(2); + queue.add(4); + queue.add(5); + queue.add(4); + + // 使用方法一: + for (let item of queue) { + console.log(item); + } + + // 使用方法二: + let iter = queue[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md index 302ec50fe59579adac4133cd9f5e41df1ce37536..5d634d453ea544c2eff9e67b164e41d6e4de6a1d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @@ -11,6 +11,11 @@ import reminderAgent from'@ohos.reminderAgent'; ``` +## 系统能力 + +SystemCapability.Notification.ReminderAgent + + ## 权限 ohos.permission.PUBLISH_AGENT_REMINDER diff --git a/zh-cn/application-dev/reference/apis/js-apis-runninglock.md b/zh-cn/application-dev/reference/apis/js-apis-runninglock.md index 887fa5eb22a99229226be3d13c70037e44d61318..c6f8ba213794bcd5398c20148c79624c45c3c698 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-runninglock.md +++ b/zh-cn/application-dev/reference/apis/js-apis-runninglock.md @@ -11,9 +11,9 @@ import runninglock from '@ohos.runningLock'; ``` -## 权限 +## 系统能力 -申请、使用锁的权限:ohos.permission.RUNNING_LOCK +SystemCapability.PowerManager.PowerManager ## RunningLockType @@ -84,6 +84,8 @@ createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback&l 创建RunningLock锁。 +需要权限:ohos.permission.RUNNING_LOCK + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -113,6 +115,8 @@ createRunningLock(name: string, type: RunningLockType): Promise<RunningLock&g 创建Runninglock锁。 +需要权限:ohos.permission.RUNNING_LOCK + - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md index c672a9bfdf63115a0070c576bf939021735739e5..838641fb4ee7d5f08e671f789e9000f31f602164 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -10,6 +10,9 @@ import sensor from '@ohos.sensor'; ``` +## 系统能力 + +SystemCapability.Sensors.Sensor ## 权限列表 diff --git a/zh-cn/application-dev/reference/apis/js-apis-stack.md b/zh-cn/application-dev/reference/apis/js-apis-stack.md new file mode 100644 index 0000000000000000000000000000000000000000..c20b9196cd20fe6b88b58bbeb192aa261abb24ee --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-stack.md @@ -0,0 +1,222 @@ +# 线性容器Stack + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import Stack from '@ohos.util.Stack' +``` + + +## 权限 + +无 + + +## Stack + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | Stack的元素个数 | + + +### constructor + +constructor(); + +Stack的构造函数。 + + +- 示例: + ``` + let stack = new Stack(); + ``` + + +### push + +push(item: T): T; + +在栈顶插入元素,并返回该元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | item | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回被添加进去的元素 | + +- 示例: + ``` + let stack = new Stack(); + stack.push("a"); + stack.push(1); + let b = [1, 2, 3]; + stack.push(b); + let c = {name : "lala", age : "13"}; + stack.push(false); + ``` + +### pop + +pop(): T; + +删除栈顶元素并返回该删除元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(2); + stack.push(4); + stack.pop(); + ``` + +### peek + +peek(): T; + +获取并返回栈顶元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回栈顶元素 | + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(2); + stack.peek(); + ``` +### locate + +locate(element: T): number; + +返回指定元素第一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 找到就返回下标值,查找失败返回-1 | +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(2); + stack.locate(2); + ``` + +### forEach +forEach(callbackfn: (value: T, index?: number, stack?: Stack<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历Stack实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素。 | + | index | number | 否 | 当前遍历到的下标值。 | + | stack | Stack<T> | 否 | 当前调用forEach方法的实例对象。 | + + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(4); + stack.forEach((value, index) => { + console.log(value, index); + }); + ``` +### isEmpty +isEmpty(): boolean; + +判断该栈是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(4); + stack.isEmpty(); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + + +- 示例: + ``` + let stack = new Stack(); + stack.push(2); + stack.push(4); + stack.push(5); + stack.push(4); + + // 使用方法一: + for (let item of stack) { + console.log(item); + } + + // 使用方法二: + let iter = stack[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-statfs.md b/zh-cn/application-dev/reference/apis/js-apis-statfs.md index de83a64b5d31a3da69ec9c072ce0391d8f27f809..8c7b111f4effa7815c208b55c79f5ea1ab64de00 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-statfs.md +++ b/zh-cn/application-dev/reference/apis/js-apis-statfs.md @@ -1,11 +1,12 @@ # statfs - +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 -``` -import statfs from '@ohos.statfs' +```js +import statfs from '@ohos.statfs'; ``` ## 使用说明 @@ -16,13 +17,13 @@ import statfs from '@ohos.statfs' 通过上述接口获取到应用目录路径dir,文件名为“xxx.txt”,文件所在绝对路径为: -``` -let path = dir + "xxx.txt" +```js +let path = dir + "xxx.txt"; ``` -## 权限列表 +## 系统能力 -无 +SystemCapability.FileManagement.File.FileIO ## statfs.getFreeBytes @@ -44,8 +45,13 @@ getFreeBytes(path:string):Promise<number> - 示例: - ``` - let num = await statfs.getFreeBytes(path); + ```js + let path = "/data"; + statfs.getFreeBytes(path).then(function (number){ + console.info("getFreeBytes successfully:"+ number); + }).catch(function(err){ + console.info("getFreeBytes failed with error:"+ err); + }); ``` ## statfs.getFreeBytes @@ -63,7 +69,7 @@ getFreeBytes(path:string, callback:AsyncCallback<number>): void - 示例: - ``` + ```js statfs.getFreeBytes(path, function(err, number){ //do something }); @@ -89,8 +95,13 @@ getTotalBytes.(path:string):Promise<number> - 示例: - ``` - let num = await statfs.getTotalBytes(path); + ```js + let path = "/data"; + statfs.getTotalBytes(path).then(function (number){ + console.info("getTotalBytes successfully:"+ number); + }).catch(function(err){ + console.info("getTotalBytes failed with error:"+ err); + }); ``` ## statfs.getTotalBytes @@ -108,7 +119,7 @@ getTotalBytes(path:string, callback:AsyncCallback<number>): void - 示例: - ``` + ```js statfs.getTotalBytes(path, function(err, number){ //do something }); diff --git a/zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md b/zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md new file mode 100644 index 0000000000000000000000000000000000000000..1f6fd7240d544c637071afe99294fc1e46af5ae1 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-storage-statistics.md @@ -0,0 +1,183 @@ +# 应用空间统计 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```js +import storagestatistics from "@ohos.storagestatistics"; +``` + +## 系统能力 + +SystemCapability.FileManagement.StorageService.SpatialStatistics + +## storagestatistics.getTotalSizeOfVolume + +getTotalSizeOfVolume(volumeUuid: string): Promise<number> + +异步获取指定卷的总空间大小,以promise方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ------ | ---- | ---- | + | volumeUuid | string | 是 | 卷id | + +- 返回值 + + | 类型 | 说明 | + | --------------------- | ---------------- | + | Promise<number> | 返回指定卷总空间 | + +- 示例 + + ```js + let uuid = ""; + storagestatistics.getTotalSizeOfVolume(uuid).then(function(number){ + console.info("getTotalSizeOfVolume successfully:"+ number); + }).catch(function(err){ + console.info("getTotalSizeOfVolume failed with error:"+ err); + }); + ``` + +## storagestatistics.getTotalSizeOfVolume + +getTotalSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void + +异步获取指定卷的总空间大小,以callback方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ------------------------------------ | ---- | -------------------------- | + | volumeUuid | string | 是 | 卷id | + | callback | callback:AsyncCallback<number> | 是 | 获取指定卷总空间之后的回调 | + +- 示例 + + ```js + let uuid = ""; + storagestatistics.getTotalSizeOfVolume(uuid, function(error, number){ + // do something + }); + ``` + + + +## storagestatistics.getFreeSizeOfVolume + +getFreeSizeOfVolume(volumeUuid: string): Promise<number> + +异步获取指定卷的可用空间大小,以promise方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ------ | ---- | ---- | + | volumeUuid | string | 是 | 卷id | + +- 返回值 + + | 类型 | 说明 | + | --------------------- | ------------------ | + | Promise<number> | 返回指定卷可用空间 | + +- 示例 + + ```js + let uuid = ""; + storagestatistics.getFreeSizeOfVolume(uuid).then(function(number){ + console.info("getFreeSizeOfVolume successfully:"+ number); + }).catch(function(err){ + console.info("getFreeSizeOfVolume failed with error:"+ err); + }); + + ``` + +## storagestatistics.getFreeSizeOfVolume + +getFreeSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void + +异步获取指定卷的可用空间大小,以callback方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | ------------------------------------ | ---- | ---------------------------- | + | volumeUuid | string | 是 | 卷id | + | callback | callback:AsyncCallback<number> | 是 | 获取指定卷可用空间之后的回调 | + +- 示例 + + ```js + let uuid = ""; + storagestatistics.getFreeSizeOfVolume(uuid, function(error, number){ + // do something + }); + ``` + +## storagestatistics.getBundleStats + +getBundleStats(volumeUuid: string, packageName:String, ): Promise<BundleStats> + +异步获取指定卷上的应用存储状态,以promise方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | ----------- | ------ | ---- | -------- | + | volumeUuid | string | 是 | 卷id | + | packageName | string | 是 | 应用包名 | + +- 返回值 + + | 类型 | 说明 | + | ------------------------------------------ | -------------------------- | + | Promise<[Bundlestats](#bundlestats)> | 返回指定卷上的应用存储状态 | + +- 示例 + + ```js + let uuid = ""; + let packageName = ""; + storagestatistics.getBundleStats(uuid, packageName).then(function(BundleStats){ + console.info("getBundleStats successfully:"+ JSON.stringify(BundleStats)); + }).catch(function(err){ + console.info("getBundleStats failed with error:"+ err); + }); + ``` + +## storagestatistics.getBundleStats + +getBundleStats(volumeUuid: string, callback:AsyncCallback<BundleStats>):void + +异步获取指定卷上的应用存储状态,以callback方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | ---------- | --------------------------------------------------------- | ---- | ------------------------------------ | + | volumeUuid | string | 是 | 卷id | + | callback | callback:AsyncCallback<[Bundlestats](#bundlestats)> | 是 | 获取指定卷上的应用存储状态之后的回调 | + +- 示例 + + ```js + let uuid = ""; + let packageName = ""; + storagestatistics.getBundleStats(uuid, packageName, function(error, BundleStats){ + // do something + }); + ``` + +## BundleStats + +### 属性 + +| 名称 | 类型 | 说明 | +| --------- | ------ | -------------- | +| appSize | number | app数据大小 | +| cacheSize | number | 缓存数据大小 | +| dataSize | number | 应用总数据大小 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-treemap.md b/zh-cn/application-dev/reference/apis/js-apis-treemap.md new file mode 100644 index 0000000000000000000000000000000000000000..56fd01993c739aced2a480e6957c571580a6be39 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-treemap.md @@ -0,0 +1,476 @@ +# 非线性容器TreeMap + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import TreeMap from '@ohos.util.TreeMap' +``` + + +## 权限 + +无 + +## TreeMap + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | TreeMap的元素个数 | + + +### constructor + +constructor(comparator?:(firstValue: K, secondValue: K) => boolean); + +TreeMap的构造函数。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 否 | 用户自定义的比较函数 | + +- 示例: + ``` + let treeMap = new TreeMap(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该容器是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const treeMap = new TreeMap(); + treeMap.isEmpty(); + ``` + + +### hasKey + +hasKey(key: K): boolean; + +判断此容器中是否含有该指定key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.hasKey("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### hasValue + +hasValue(value: V): boolean; + +判断此容器中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.hasValue(123); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.hasValue(123); + ``` + + +### get + +get(key: K): V; + +获取指定key所对应的value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 查找的指定key | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回key映射的value值 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.get("sdfs"); + ``` + + +### getFirstKey + +getFirstKey(): K; + +获取容器中排序第一的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回排序第一的数据 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let result = treeMap.getFirstKey(); + ``` + + +### getLastKey + +getLastKey(): K; + +获取容器中排序最后的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回排序最后的数据 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let result = treeMap.getLastKey(); + ``` + + +### setAll + +setAll(map: TreeMap): void; + +将一个treemap中的所有元素组添加到另一个treemap中。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | map | TreeMap | 是 | 被添加元素的treemap | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let map = new TreeMap(); + treeMap.setAll(map); + ``` + + +### set +set(key: K, value: V): Object; + +向treemap中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 添加成员数据的键名 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Object | 返回添加后的hashmap | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + ``` + + +### remove + +remove(key: K): V; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定删除的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | V | 返回删除元素的值 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.remove("sdfs"); + ``` + + +### getLowerByKey + +getLowerByKey(key: K): K; + +获取容器中比传入key排序靠前一位的key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 对比的key值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回排序中key前一位的数据 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.set("zdfgsd", 356); + let result = treeMap.getLowerByKey("sdfs"); + ``` + + +### getHigherByKey + +getHigherByKey(key: K): K; + +获取容器中比传入key排序靠后一位的key。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 对比的key值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | K | 返回排序中key后一位的数据 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.set("zdfgsd", 356); + let result = treeMap.getHigherByKey("sdfs"); + ``` + + +### replace +replace(key: K, value: V): boolean; + +对TreeMap中一组数据进行更新(替换)。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | K | 是 | 依据key指定替换的元素 | + | value | V | 是 | 添加成员数据的值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功对已有数据进行替换 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("sdfs", 123); + treeMap.replace("sdfs", 357); + ``` + + +### clear + +clear(): void; + +清除TreeMap中的所有元素,并把length置为0。 + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + treeMap.clear(); + ``` + + +### keys + +keys(): IterableIterator<K>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<K> | 返回一个迭代器 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let iter = treeMap.keys(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### values + +values(): IterableIterator<V>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<V> | 返回一个迭代器 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let iter = treeMap.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### forEach + +forEach(callbackfn: (value: V, key?: K, treeMap?: TreeMap) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | V | 是 | 当前遍历到的元素键值对的值 | + | key | K | 是 | 当前遍历到的元素键值对的键 | + | treeMap | TreeMap | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("sdfs", 123); + treeMap.set("dfsghsf", 357); + treeMap.forEach((value, key) => { + console.log(value, key); + }); + ``` + + +### entries + +entries(): IterableIterator<[K, V]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + let iter = treeMap.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<[K, V]>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[K, V]> | 返回一个迭代器 | + +- 示例: + ``` + let treeMap = new TreeMap(); + treeMap.set("Ahfbrgrbgnutfodgorrogorgrogofdfdf", 123); + treeMap.set("sdfs", 356); + + // 使用方法一: + for (let item of treeMap) { + console.log("key: " + item[0]); + console.log("value: " + item[1]); + } + + // 使用方法二: + let iter = treeMap[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-treeset.md b/zh-cn/application-dev/reference/apis/js-apis-treeset.md new file mode 100644 index 0000000000000000000000000000000000000000..10cbd68738d777fd5c8788ec379f7562ca449f7f --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-treeset.md @@ -0,0 +1,393 @@ +# 非线性容器TreeSet + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import TreeSet from '@ohos.util.TreeSet' +``` + + +## 权限 + +无 + +## TreeSet + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | TreeSet的元素个数 | + + +### constructor + +constructor(comparator?:(firstValue: T, secondValue: T) => boolean); + +TreeSet的构造函数。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 否 | 用户自定义的比较函数 | + +- 示例: + ``` + let treeSet = new TreeSet(); + ``` + + +### isEmpty + +isEmpty(): boolean; + +判断该容器是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + const treeSet = new TreeSet(); + treeSet.isEmpty(); + ``` + + +### has + +has(value: T): boolean; + +判断此容器中是否含有该指定value。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.has(123); + treeSet.add(123); + treeSet.has(123); + ``` + + +### getFirstValue + +getFirstValue(): T; + +获取容器中排序第一的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回排序第一的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let result = treeSet.getFirstValue(); + ``` + + +### getLastValue + +getLastValue(): T; + +获取容器中排序最后的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回排序最后的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let result = treeSet.getLastValue(); + ``` + + +### add +add(value: T): boolean; + +向TreeSet中添加一组数据。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 添加的成员数据 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否成功添加新数据至容器 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + + +### remove + +remove(key: T): boolean; + +删除指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 指定的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 判断是否成功删除元素 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + treeSet.remove("sdfs"); + ``` + + +### getLowerValue + +getLowerValue(key: T): T; + +获取容器中比传入元素排序靠前一位的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 对比的元素值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回排序中对比元素前一位的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + treeSet.add("zdfgsd"); + let result = treeSet.getLowerValue("sdfs"); + ``` + + +### getHigherValue + +getHigherValue(key: T): T; + +获取容器中比传入元素排序靠后一位的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | key | T | 是 | 对比的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回排序中传入元素后一位的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + treeSet.add("zdfgsd"); + let result = treeSet.getHigherValue("sdfs"); + ``` + + +### popFirst + +popFirst(): T; + +删除容器中排序最前的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let result = treeSet.popFirst(); + ``` + + +### popLast + +popLast(): T; + +删除容器中排序最后的数据。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的数据 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let result = treeSet.popLast(); + ``` + + +### clear + +clear(): void; + +清除容器中的所有元素,并把length置为0。 + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + treeSet.clear(); + ``` + + +### values + +values(): IterableIterator<T>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let iter = treeSet.values(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` + + +### forEach + +forEach(callbackfn: (value: T, key?: T, treeSet?: TreeSet<T>) => void, thisArg?: Object): void; + +通过回调函数来遍历实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | key | T | 否 | 当前遍历到的元素(和value相同). | + | treeSet | TreeSet<T> | 否 | 当前调用forEach方法的实例对象 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("sdfs"); + treeSet.add("dfsghsf"); + treeSet.forEach((value, key) => { + console.log(value, key) + }); + ``` + + +### entries + +entries(): IterableIterator<[T, T]>; + +返回包含此映射中包含的键的新迭代器对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<[T, T]> | 返回一个迭代器 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + let iter = treeSet.entries(); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp[0]); + console.log(temp[1]); + temp = iter.next().value; + } + ``` + + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器 | + +- 示例: + ``` + let treeSet = new TreeSet(); + treeSet.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + treeSet.add("sdfs"); + + // 使用方法一: + for (let item of treeSet) { + console.log("value: " + item); + } + + // 使用方法二: + let iter = treeSet[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-uri.md b/zh-cn/application-dev/reference/apis/js-apis-uri.md index 3d557c30957aba3b1b92df02452bb8a90a087847..ad0716494694700651adaa1e94df1beacb36ef0e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-uri.md +++ b/zh-cn/application-dev/reference/apis/js-apis-uri.md @@ -10,12 +10,6 @@ import uri from '@ohos.uri' ``` - -## 权限 - -无 - - ## URI @@ -24,7 +18,7 @@ import uri from '@ohos.uri' | 名称 | 参数类型 | 可读 | 可写 | 说明 | | -------- | -------- | -------- | -------- | -------- | | scheme | string | 是 | 否 | 获取URI 的协议部分。 | -| userinfo | string | 是 | 否 | 获取 URI 的用户信息部分。 | +| userInfo | string | 是 | 否 | 获取 URI 的用户信息部分。 | | host | string | 是 | 否 | 获取 URI 的主机名部分(不带端口)。 | | port | string | 是 | 否 | 获取 URI 的端口部分。 | | path | string | 是 | 否 | 获取 URI 的路径部分。 | @@ -64,7 +58,7 @@ toString(): string - 返回值: | 类型 | 说明 | | -------- | -------- | - | string | 用于返回网址的字符串序列化。 | + | string | 返回网址的字符串序列化。 | - 示例: ``` @@ -87,7 +81,7 @@ equals(other: URI): boolean - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 用于测试此URI是否与其他URI对象相等。 | + | boolean | 返回true表示相等,否则返回false。 | - 示例: ``` @@ -96,15 +90,16 @@ equals(other: URI): boolean uriInstance.equals(uriInstance1); ``` - ### checkIsAbsolute -判断此URI是否为绝对URI。 +checkIsAbsolute(): boolean + +判断此URI是否为绝对URI(是否定义了scheme组件)。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | boolean | 用于说明此URI是否为绝对URI(是否定义了scheme组件)。 | + | boolean | 返回true表示该URI是否为绝对URI。 | - 示例: ``` @@ -122,7 +117,7 @@ normalize(): URI - 返回值: | 类型 | 说明 | | -------- | -------- | - | URI | 用于规范化此URI的路径,并返回一个path被规范化后的URI对象。 | + | URI | 返回一个path被规范化后的URI对象。 | - 示例: ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-url.md b/zh-cn/application-dev/reference/apis/js-apis-url.md index bbe12540d1a55d2357a60ab06ac3fe49d04d84ce..e8b003482705ae144781b70d18953e481f045f7a 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-url.md +++ b/zh-cn/application-dev/reference/apis/js-apis-url.md @@ -11,11 +11,6 @@ import Url from '@ohos.url' ``` -## 权限 - -无 - - ## URLSearchParams diff --git a/zh-cn/application-dev/reference/apis/js-apis-util.md b/zh-cn/application-dev/reference/apis/js-apis-util.md index 71707c4098ba3429ec091d68d343c151453bdf49..6b08fdcb79ee751afde0cebe83dd35bc1c72c7d0 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-util.md +++ b/zh-cn/application-dev/reference/apis/js-apis-util.md @@ -15,11 +15,6 @@ import util from '@ohos.util'; ``` -## 权限 - -无 - - ## util.printf printf(format: string, ...args: Object[]): string @@ -91,8 +86,8 @@ callbackWrapper(original: Function): (err: Object, value: Object )=>void } var cb = util.callbackWrapper(promiseFn); cb((err, ret) => { - expect(err).strictEqual('value'); - expect(ret).strictEqual(undefined); + console.log(err); + console.log(ret); }) ``` @@ -124,7 +119,7 @@ promiseWrapper(original: (err: Object, value: Object) => void): Object } let newPromiseObj = util.promiseWrapper(aysnFun)("Hello", 'World'); newPromiseObj.then(res => { - expect(res).strictEqual('HelloWorld'); + console.log(res); }) ``` @@ -296,7 +291,7 @@ RationalNumber的构造函数。 - 示例: ``` - var rationalNumber = new util.RationalNumber(1,2); + var rationalNumber = new util.RationalNumber(1,2); ``` @@ -551,7 +546,7 @@ constructor(capacity?:number) - 示例: ``` - var lrubuffer= new util.LruBuffer(); + var lrubuffer= new util.LruBuffer(); ``` @@ -661,7 +656,7 @@ getMissCount():number ``` var pro = new util.LruBuffer(); pro.put(2,10); - pro.get(2) + pro.get(2); var result = pro.getMissCount(); ``` @@ -896,7 +891,7 @@ afterRemoval(isEvict:boolean,key:K,value:V,newValue:V):void } } } - ChildLruBuffer.getInstance().afterRemoval(false,10,30,null); + ChildLruBuffer.getInstance().afterRemoval(false,10,30,null); ``` @@ -1115,7 +1110,7 @@ intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope var tempMiDF = new Temperature(35); var tempMidS = new Temperature(39); var range = new util.Scope(tempLower, tempUpper); - var result = range.intersect(tempMiDF, tempMidS); + var result = range.intersect(tempMiDF, tempMidS); ``` @@ -1135,7 +1130,7 @@ getUpper():ScopeType var tempLower = new Temperature(30); var tempUpper = new Temperature(40); var range = new util.Scope(tempLower, tempUpper); - var result = range.getUpper(); + var result = range.getUpper(); ``` @@ -1155,7 +1150,7 @@ getLower():ScopeType var tempLower = new Temperature(30); var tempUpper = new Temperature(40); var range = new util.Scope(tempLower, tempUpper); - var result = range.getLower(); + var result = range.getLower(); ``` @@ -1183,7 +1178,7 @@ expand(lowerObj:ScopeType,upperObj:ScopeType):Scope var tempMiDF = new Temperature(35); var tempMidS = new Temperature(39); var range = new util.Scope(tempLower, tempUpper); - var result = range.expand(tempMiDF, tempMidS); + var result = range.expand(tempMiDF, tempMidS); ``` @@ -1211,7 +1206,7 @@ expand(range:Scope):Scope var tempMidS = new Temperature(39); var range = new util.Scope(tempLower, tempUpper); var rangeFir = new util.Scope(tempMiDF, tempMidS); - var result = range.expand(rangeFir); + var result = range.expand(rangeFir); ``` @@ -1237,7 +1232,7 @@ expand(value:ScopeType):Scope var tempUpper = new Temperature(40); var tempMiDF = new Temperature(35); var range = new util.Scope(tempLower, tempUpper); - var result = range.expand(tempMiDF); + var result = range.expand(tempMiDF); ``` @@ -1263,7 +1258,7 @@ contains(value:ScopeType):boolean var tempUpper = new Temperature(40); var tempMiDF = new Temperature(35); var range = new util.Scope(tempLower, tempUpper); - range.contains(tempMiDF); + range.contains(tempMiDF); ``` @@ -1291,7 +1286,7 @@ contains(range:Scope):boolean var tempLess = new Temperature(20); var tempMore = new Temperature(45); var rangeSec = new util.Scope(tempLess, tempMore); - var result = range.contains(rangeSec); + var result = range.contains(rangeSec); ``` @@ -1309,7 +1304,7 @@ clamp(value:ScopeType):ScopeType - 返回值: | 类型 | 说明 | | -------- | -------- | - | [ScopeType](#scopetype8) | 如果传入的value小于下限,则返回lowerObj;如果大于上限值则返回upperObj;如果在当前范围内,则返回value | + | [ScopeType](#scopetype8) | 如果传入的value小于下限,则返回lowerObj;如果大于上限值则返回upperObj;如果在当前范围内,则返回value。 | - 示例: ``` @@ -1317,7 +1312,7 @@ clamp(value:ScopeType):ScopeType var tempUpper = new Temperature(40); var tempMiDF = new Temperature(35); var range = new util.Scope(tempLower, tempUpper); - var result = range.clamp(tempMiDF); + var result = range.clamp(tempMiDF); ``` @@ -1332,7 +1327,7 @@ Base64的构造函数。 - 示例: ``` - var base64 = new util.Base64(); + var base64 = new util.Base64(); ``` @@ -1429,12 +1424,11 @@ encode(src:Uint8Array):Promise<Uint8Array> var that = new util.Base64(); var array = new Uint8Array([115,49,51]); var rarray = new Uint8Array([99,122,69,122]); - await that.encode(array).then(val=>{ + that.encode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { - expect(val[i]).assertEqual(rarray[i]) + console.log(val[i]) } }) - done(); ``` @@ -1458,10 +1452,9 @@ encodeToString(src:Uint8Array):Promise<string> ``` var that = new util.Base64(); var array = new Uint8Array([115,49,51]); - await that.encodeToString(array).then(val=>{ - expect(val).assertEqual('czEz') + that.encodeToString(array).then(val=>{ + console.log(val) }) - done(); ``` @@ -1486,12 +1479,11 @@ decode(src:Uint8Array | string):Promise<Uint8Array> var that = new util.Base64(); var array = new Uint8Array([99,122,69,122]); var rarray = new Uint8Array([115,49,51]); - await that.decode(array).then(val=>{ + that.decode(array).then(val=>{ for (var i = 0; i < rarray.length; i++) { - expect(val[i]).assertEqual(rarray[i]) + console.log(val[i]) } }) - done(); ``` @@ -1588,7 +1580,7 @@ isArgumentsObject(value: Object):boolean isArrayBuffer(value: Object):boolean -检查输入的value是否是ArrayBuffer对象类型。 +检查输入的value是否是ArrayBuffer类型。 - 参数: | 参数名 | 类型 | 必填 | 说明 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-vector.md b/zh-cn/application-dev/reference/apis/js-apis-vector.md new file mode 100644 index 0000000000000000000000000000000000000000..e0548b7cd3d43907ae849068ce2595a199d4166e --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-vector.md @@ -0,0 +1,684 @@ +# 线性容器Vector + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +``` +import Vector from '@ohos.util.Vector' +``` + + +## 权限 + +无 + + +## Vector + + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| -------- | -------- | -------- | -------- | -------- | +| length | number | 是 | 否 | Vector的元素个数 | + + +### constructor + +constructor(); + +Vector的构造函数。 + +- 示例: + ``` + let vector = new Vector(); + ``` + + +### add + +add(element: T): boolean; + +在Vector中尾部插入元素 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 添加进去的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 插入成功返回true,失败返回false | + +- 示例: + ``` + let vector = new Vector(); + vector.add("a"); + vector.add(1); + let b = [1, 2, 3]; + vector.add(b); + let c = {name : "lala", age : "13"}; + vector.add(false); + ``` + +### insert + +insert(element: T, index: number): void; + +在长度范围内任意插入指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 被插入的元素 | + | index | number | 是 | 被插入的位置索引 | + +- 示例: + ``` + let vector = new Vector(); + vector.insert("A", 0); + vector.insert(0, 1); + vector.insert(true, 2); + ``` + +### has + +has(element: T): boolean; + +判断此Vector中是否含有该指定元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 是否包含指定元素 | + +- 示例: + ``` + let vector = new Vector(); + vector.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + vector.add("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + vector.has("Ahfbrgrbgnutfodgorrogorgrogofdfdf"); + ``` + +### getIndexOf + +getIndexOf(element: T): number; + +返回指定元素第一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定的元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素第一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(2); + vector.add(1); + vector.add(2); + vector.add(4); + vector.getIndexOf(2); + ``` +### getLastIndexOf + +getLastIndexOf(element: T): number; + +返回指定元素最后一次出现时的下标值,查找失败返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回指定元素最后一次出现时的下标值,查找失败返回-1 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(2); + vector.add(1); + vector.add(2); + vector.add(4); + vector.getLastIndexOf(2); + ``` +### removeByIndex + +removeByIndex(index: number): T; + +根据元素的下标值查找元素,返回元素后将其删除。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | index | number | 是 | 指定元素的下标值 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回删除的元素 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(2); + vector.add(4); + vector.removeByIndex(2); + ``` + +### remove + +remove(element: T): boolean; + +删除查找到的第一个指定的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 指定元素 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 删除成功返回true,失败返回false | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.remove(2); + ``` +### removeByRange +removeByRange(fromIndex: number, toIndex: number): void; + +从一段范围内删除元素,包括起始值但不包括终止值。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.removeByRange(2,4); + vector.removeByRange(4,3); + vector.removeByRange(2,6); + ``` + +### replaceAllElements +replaceAllElements(callbackfn: (value: T, index?: number, vector?: Vector<T>) => T, +thisArg?: Object): void; + +用户操作Vector中的元素,用操作后的元素替换原元素并返回操作后的元素。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素 | + | index | number | 否 | 当前遍历到的下标值 | + | vector | Vector<T> | 否 | 当前调用replaceAllElements方法的实例对象 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.replaceAllElements((value, index) => { + return value = 2 * value; + }); + vector.replaceAllElements((value, index) => { + return value = value - 2; + }); + ``` +### forEach +forEach(callbackfn: (value: T, index?: number, vector?: Vector<T>) => void, +thisArg?: Object): void; + +通过回调函数来遍历Vector实例对象上的元素以及元素对应的下标。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | callbackfn | function | 是 | 回调函数。 | + | thisArg | Object | 否 | callbackfn被调用时用作this值 | + +- callbackfn的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | value | T | 是 | 当前遍历到的元素。 | + | index | number | 否 | 当前遍历到的下标值。 | + | vector | Vector<T> | 否 | 当前调用forEach方法的实例对象。 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.forEach((value, index) => { + console.log(value, index) + }); + + ``` +### sort +sort(comparator?: (firstValue: T, secondValue: T) => number): void; + +对Vector中的元素进行一个排序操作。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | comparator | function | 否 | 回调函数。 | + +- comparator的参数说明 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | firstValue | T | 是 | 前一项元素 | + | secondValue | T | 是 | 后一项元素 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.sort(a, (b => a - b)); + vector.sort(a, (b => b - a)); + vector.sort(); + ``` +### subVector +subVector(fromIndex: number, toIndex: number): Vector<T>; + +根据下标截取Vector中的一段元素,并返回这一段vector实例,包括起始值但不包括终止值。 +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | fromIndex | number | 是 | 起始下标 | + | toIndex | number | 是 | 终止下标 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Vector<T> | 返回Vector对象实例 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.subVector(2,4); + vector.subVector(4,3); + vector.subVector(2,6); + + ``` + +### clear +clear(): void; + +清除Vector中的所有元素,并把length置为0。 + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.clear(); + ``` +### clone +clone(): Vector<T>; + +克隆一个与Vector一模一样的实例,并返回克隆后的实例,修改克隆后的实例并不会影响原实例。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Vector<T> | 返回Vector对象实例 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.clone(); + ``` +### getCapacity +getCapacity(): number; + +获取当前实例的容量大小。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回Vector的容量大小 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.getCapacity(); + ``` +### convertToArray +convertToArray(): Array<T>; + +把当前Vector实例转换成数组,并返回转换后的数组。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | Array<T> | 返回数组类型 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.convertToArray(); + ``` +### isEmpty +isEmpty(): boolean; + +判断该Vector是否为空。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | boolean | 为空返回true, 不为空返回false | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.isEmpty(); + ``` +### increaseCapacityTo +increaseCapacityTo(newCapacity: number): void; + +如果传入的新容量大于或等于Vector中的元素个数,将容量变更为新容量。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | newCapacity | number | 是 | 新容量 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.increaseCapacityTo(2); + vector.increaseCapacityTo(8); + ``` +### trimToCurrentLength +trimToCurrentLength(): void; + +把容量限制为当前的length大小。 + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.trimToCurrentLength(2); + ``` +### toString + +toString(): string; +用","将Vector实例中的元素按顺序拼接成字符串。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | string | 返回字符串类型 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.toSting(); + ``` + +### copyToArray + +copyToArray(array: Array<T>): void; +将Vector实例中的元素按照下标复制进array。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | array | Array<T> | 是 | 数组 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + let array = ["a", "b", "c", "d", "e", "f"]; + vector.copyToArray(array); + ``` +### getFirstElement + +getFirstElement(): T; +获取实例中的第一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.getFirstElement(); + ``` +### getLastElement + +getLastElement(): T; +获取Vector实例中的最后一个元素。 + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | T | 返回T型 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.getLastElement(); + ``` +### getLastIndexFrom + +getLastIndexFrom(element: T, index: number): number; + +从指定索引向后搜索, 返回该元素的下标索引,如果查找失败,则返回-1。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 要查找的元素 | + | index | number | 是 | 从指定索引开始搜索 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回该元素的下标 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.add("a"); + vector.getLastIndexFrom(4,3); + ``` +### getIndexFrom + +getIndexFrom(element: T, index: number): number; + +从指定索引向前搜索, 返回该元素的下标索引,如果查找失败,则返回 -1 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | element | T | 是 | 要查找的元素 | + | index | number | 是 | 从指定索引开始搜索 | + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | number | 返回该元素的下标 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.add("a"); + vector.getIndexFrom(4, 3); + ``` +### setLength +setLength(newSize: number): void; +设置Vector实例的元素个数。 + +- 参数: + | 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | + | newSize | number | 是 | 设置的新长度 | + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + vector.setLength(8); + vector.setLength(2); + ``` + +### [Symbol.iterator] + +[Symbol.iterator]\(): IterableIterator<T>; + + +返回一个迭代器,迭代器的每一项都是一个 JavaScript 对象,并返回该对象。 + + +- 返回值: + | 类型 | 说明 | + | -------- | -------- | + | IterableIterator<T> | 返回一个迭代器。 | + + +- 示例: + ``` + let vector = new Vector(); + vector.add(2); + vector.add(4); + vector.add(5); + vector.add(4); + + // 使用方法一: + for (let item of vector) { + console.log(item); + } + + // 使用方法二: + let iter = vector[Symbol.iterator](); + let temp = iter.next().value; + while(temp != undefined) { + console.log(temp); + temp = iter.next().value; + } + ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md index a31e5000d1cac98fb82212357b5bfa9117370fe7..7e4d658d1a434da4af2e0b54d058bc7da917300d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-vibrator.md +++ b/zh-cn/application-dev/reference/apis/js-apis-vibrator.md @@ -10,6 +10,9 @@ import vibrator from '@ohos.vibrator'; ``` +## 系统能力 + +SystemCapability.Sensors.MiscDevice ## 权限列表 diff --git a/zh-cn/application-dev/reference/apis/js-apis-volumemanager.md b/zh-cn/application-dev/reference/apis/js-apis-volumemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..dec4792a4ca340a5ec8fefb6e8ec5d27a739f71b --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-volumemanager.md @@ -0,0 +1,167 @@ +# 卷管理 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```js +import volumemanager from "@ohos.volumemanager"; +``` + +## 系统能力 + +SystemCapability.FileManagement.StorageService.Volume + +## volumemanager.getAllVolumes + +getAllVolumes(): Promise<Volume[]> + +异步获取当前所有可获得的卷信息,以promise方式返回。 + +- 返回值 + + | 类型 | 说明 | + | ---------------------------------- | -------------------------- | + | Promise<[Volume](#volume)[]> | 返回当前所有可获得的卷信息 | + +- 示例 + + ```js + volumemanager.getAllVolumes().then(function(volumes){ + // do something + }); + ``` + +## volumemanager.getAllVolumes + +getAllVolumes(callback:AsyncCallback<Volume[]>):void + +异步获取当前所有可获得的卷信息,以callback方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------------------------------------- | ---- | ------------------------------------ | + | callback | callback:AsyncCallback<[Volume](#volume)[]> | 是 | 获取当前所有可获得的卷信息之后的回调 | + +- 示例 + + ```js + let uuid = ""; + volumemanager.getAllVolumes(uuid, function(error, volumes){ + // do something + }); + ``` + + +## volumemanager.mount + +mount(volumeId: string): Promise<boolean> + +异步挂载指定卷,以promise方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------ | ---- | ---- | + | volumeId | string | 是 | 卷id | + +- 返回值 + + | 类型 | 说明 | + | ---------------------- | ---------- | + | Promise<boolean> | 挂载指定卷 | + +- 示例 + + ```js + let volumeId = ""; + volumemanager.mount(volumeId).then(function(flag){ + // do something + }); + ``` + +## volumemanager.mount + +mount(volumeId: string, callback:AsyncCallback<boolean>):void + +异步获取指定卷的可用空间大小,以callback方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------------------------- | ---- | -------------------- | + | volumeId | string | 是 | 卷id | + | callback | callback:AsyncCallback<boolean> | 是 | 挂载指定卷之后的回调 | + +- 示例 + + ```js + let volumeId = ""; + volumemanager.mount(volumeId, function(error, flag){ + // do something + }); + ``` + +## volumemanager.unmount + +unmount(volumeId: string): Promise<boolean> + +异步卸载指定卷,以promise方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------ | ---- | ---- | + | volumeId | string | 是 | 卷id | + +- 返回值 + + | 类型 | 说明 | + | ---------------------- | ---------- | + | Promise<boolean> | 卸载指定卷 | + +- 示例 + + ```js + let volumeId = ""; + volumemanager.unmount(volumeId).then(function(flag){ + // do something + }); + ``` + +## volumemanager.unmount + +unmount(volumeId: string, callback:AsyncCallback<boolean>):void + +异步卸载指定卷,以callback方式返回。 + +- 参数 + + | 参数名 | 类型 | 必填 | 说明 | + | -------- | ------------------------------------- | ---- | -------------------- | + | volumeId | string | 是 | 卷id | + | callback | callback:AsyncCallback<boolean> | 是 | 卸载指定卷之后的回调 | + +- 示例 + + ```js + let volumeId = ""; + volumemanager.unmount(volumeId, function(error, flag){ + // do something + }); + ``` + +## Volume + +### 属性 + +| 名称 | 类型 | 说明 | +| ----------- | ------- | -------------------- | +| id | number | 卷id | +| uuid | string | 卷uuid | +| description | string | 卷相关描述 | +| removeAble | boolean | 是否为可移动存储设备 | +| state | int | 当前卷状态 | +| path | string | 卷的挂载地址 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index ff45b896576008a906846753b579d928b04cbaf1..7ceb3a6c4b5c0ed422b81e41d329679df0464c73 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -11,6 +11,11 @@ import window from '@ohos.window'; ``` +## 系统能力 +SystemCapability.WindowManager.WindowManager.Core + + + ## 权限列表 ohos.permission.SYSTEM_FLOAT_WINDOW @@ -189,7 +194,7 @@ getAbilityWindowMode(callback: AsyncCallback<WindowMode>): void ``` window.getAbilityWindowMode((err, data) => { if (err) { - console.error(''Failed to obtain the window mode. Cause:' + JSON.stringify(err)); + console.error('Failed to obtain the window mode. Cause:' + JSON.stringify(err)); return; } console.info('Window mode obtained. Data:' + JSON.stringify(data)) diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 32c60ad58e313e0bae553022f4e6a742903c9341..57eaaf62badf4a17f228717065573bc2d9be67e4 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -11,11 +11,6 @@ import worker from '@ohos.worker'; ``` -## 权限 - -无 - - ## 属性 | 名称 | 参数类型 | 可读 | 可写 | 说明 | @@ -51,7 +46,7 @@ worker构造函数。 | options | [WorkerOptions](#workeroptions) | 否 | worker构造的选项。 | - 返回值: - | 参数名 | 说明 | + | 类型 | 说明 | | -------- | -------- | | worker | 执行Worker构造函数生成的Worker对象,失败则返回undefined。 | @@ -294,7 +289,7 @@ dispatchEvent(event: Event): boolean | event | [Event](#event) | 是 | 需要分发的事件。 | - 返回值: - | 参数名 | 说明 | + | 类型 | 说明 | | -------- | -------- | | boolean | 分发的结果,false表示分发失败。 | @@ -347,7 +342,7 @@ worker向宿主线程发送消息。 ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e){ parentPort.postMessage("receive data from main.js") @@ -369,7 +364,7 @@ close(): void ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { parentPort.close() @@ -397,7 +392,7 @@ DedicatedWorkerGlobalScope的onmessage属性表示worker线程收到来自其宿 ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessage = function(e) { console.log("receive main.js message") @@ -424,7 +419,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当 Worker 对象接收 ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort; parentPort.onmessageerror= function(e) { console.log("worker.js onmessageerror") @@ -466,7 +461,7 @@ DedicatedWorkerGlobalScope的onmessageerror属性表示当 Worker 对象接收 | evt | [Event](#event) | 是 | 回调的事件类。 | - 返回值 - | 参数名 | 说明 | + | 类型 | 说明 | | -------- | -------- | | void \| Promise<void> | 无返回值或者以Promise形式返回。 | @@ -533,7 +528,7 @@ WorkerGlobalScope的onerror属性表示worker在执行过程中发生异常被 ``` ``` // worker.js - import worker from "@ohos.worker"; + import worker from '@ohos.worker'; const parentPort = worker.parentPort parentPort.onerror = function(e){ console.log("worker.js onerror") diff --git a/zh-cn/application-dev/reference/apis/js-apis-xml.md b/zh-cn/application-dev/reference/apis/js-apis-xml.md index fe319f9f62406f7282e42d1afa540525efb3555f..3765c3ff2c2b877bb4b7c16a2ff57b1669ff2933 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-xml.md +++ b/zh-cn/application-dev/reference/apis/js-apis-xml.md @@ -11,11 +11,6 @@ import xml from '@ohos.xml'; ``` -## 权限 - -无 - - ## XmlSerializer @@ -28,7 +23,7 @@ XmlSerializer的构造函数。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | buffer | ArrayBuffer \| DataView | 是 | 用于接收写入xml信息的ArrayBuffer \| DataView内存。 | + | buffer | ArrayBuffer \| DataView | 是 | 用于接收写入xml信息的ArrayBuffer或DataView内存。 | | encoding | string | 否 | 编码格式。 | - 示例: @@ -48,8 +43,8 @@ setAttributes(name: string, value: string):void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | string | 是 | 属性的key值 | - | value | string | 是 | 属性的value值 | + | name | string | 是 | 属性的key值。 | + | value | string | 是 | 属性的value值。 | - 示例: ``` @@ -67,7 +62,7 @@ addEmptyElement(name: string): void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | string | 是 | 该空元素的元素名 | + | name | string | 是 | 该空元素的元素名。 | - 示例: ``` @@ -93,12 +88,12 @@ setDeclaration(): void startElement(name: string): void -XmlSerializer的构造函数。 +根据给定名称写入元素开始标记。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | name | string | 是 | 当前元素的元素名 | + | name | string | 是 | 当前元素的元素名。 | - 示例: ``` @@ -113,7 +108,7 @@ XmlSerializer的构造函数。 endElement(): void -设置结束元素方法。 +写入元素结束标记。 - 示例: ``` @@ -135,8 +130,8 @@ setNamespace(prefix: string, namespace: string): void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | prefix | string | 是 | 当前元素及其子元素的前缀 | - | namespace | string | 是 | 当前元素及其子元素的命名空间 | + | prefix | string | 是 | 当前元素及其子元素的前缀。 | + | namespace | string | 是 | 当前元素及其子元素的命名空间。 | - 示例: ``` @@ -148,43 +143,43 @@ setNamespace(prefix: string, namespace: string): void thatSer.endElement();// = >'\r\n'; ``` -### setCommnet +### setComment -setCommnet(text: string): void +setComment(text: string): void 写入comment属性。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | text | string | 是 | 当前元素的注释内容 | + | text | string | 是 | 当前元素的注释内容。 | - 示例: ``` var arrayBuffer = new ArrayBuffer(1024); var thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); - thatSer.setCommnet("Hi!"); + thatSer.setComment("Hi!"); thatSer.endElement(); // => '\r\n \r\n'; ``` -### setCData +### setCDATA -setCData(text: string): void +setCDATA(text: string): void -写入CData属性。 +写入CDATA属性。 - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | text | string | 是 | CDate属性的内容 | + | text | string | 是 | CDATA属性的内容。 | - 示例: ``` var arrayBuffer = new ArrayBuffer(1028); var thatSer = new xml.XmlSerializer(arrayBuffer); - thatSer.setCData('root SYSTEM') // => ''; + thatSer.setCDATA('root SYSTEM') // => ''; ``` @@ -197,7 +192,7 @@ setText(text: string): void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | text | string | 是 | text属性的内容 | + | text | string | 是 | text属性的内容。 | - 示例: ``` @@ -219,7 +214,7 @@ setDocType(text: string): void - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | text | string | 是 | DocType属性的内容 | + | text | string | 是 | DocType属性的内容。 | - 示例: ``` @@ -241,8 +236,8 @@ constructor(buffer: ArrayBuffer | DataView, encoding?: string) - 参数: | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | buffer | ArrayBuffer \| DataView | 是 | 含有xml文本信息的ArrayBuffer 或者DataView | - | encoding | string | 否 | 编码格式(仅支持utf-8) | + | buffer | ArrayBuffer \| DataView | 是 | 含有xml文本信息的ArrayBuffer或者DataView。 | + | encoding | string | 否 | 编码格式(仅支持utf-8)。 | - 示例: ``` @@ -325,12 +320,12 @@ xml解析选项。 getColumnNumber(): number -获取当前行号,从1开始。 +获取当前列号,从1开始。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 返回当前行号。 | + | number | 返回当前列号。 | ### getDepth @@ -349,12 +344,12 @@ getDepth(): number getLineNumber(): number -获取当前列号,从1开始。 +获取当前行号,从1开始。 - 返回值: | 类型 | 说明 | | -------- | -------- | - | number | 返回当前列号。 | + | number | 返回当前行号。 | ### getName diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index 16c26fd80771ea1586cad5815a211e04c1e43785..c6efba1fd72e46de2323575f64cad167f788ac72 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -7,7 +7,7 @@ ## 接口 -CanvasRenderingContext2D\(setting: RenderingContextSetting\) +CanvasRenderingContext2D\(setting: RenderingContextSettings\) - 参数 @@ -40,9 +40,9 @@ CanvasRenderingContext2D\(setting: RenderingContextSetting\) ### RenderingContextSettings -RenderingContextSettings\(antialias?: bool, alpha?: bool\) +RenderingContextSettings\(antialias?: bool) -用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿和是否包含一个alpha通道。 +用来配置CanvasRenderingContext2D对象的参数,包括是否开启抗锯齿。 - 参数 @@ -69,17 +69,6 @@ RenderingContextSettings\(antialias?: bool, alpha?: bool\)

表明canvas是否开启抗锯齿。

alpha

-

bool

-

-

false

-

表明canvas包含是否包含一个alpha通道。

-
@@ -282,7 +271,7 @@ RenderingContextSettings\(antialias?: bool, alpha?: bool\) @Entry @Component struct FillStyleExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -310,7 +299,7 @@ struct FillStyleExample { @Entry @Component struct LineWidthExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -338,7 +327,7 @@ struct LineWidthExample { @Entry @Component struct StrokeStyleExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -367,7 +356,7 @@ struct StrokeStyleExample { @Entry @Component struct LineCapExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -399,7 +388,7 @@ struct LineCapExample { @Entry @Component struct LineJoinExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -432,7 +421,7 @@ struct LineJoinExample { @Entry @Component struct MiterLimit { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -465,7 +454,7 @@ struct MiterLimit { @Entry @Component struct Font { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -492,8 +481,8 @@ struct Font { ``` @Entry @Component -struct TextAlign { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -536,7 +525,7 @@ struct TextAlign { @Entry @Component struct TextBaseline { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -579,7 +568,7 @@ struct TextBaseline { @Entry @Component struct GlobalAlpha { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -610,7 +599,7 @@ struct GlobalAlpha { @Entry @Component struct LineDashOffset { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -703,7 +692,7 @@ struct LineDashOffset { @Entry @Component struct GlobalCompositeOperation { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -739,7 +728,7 @@ struct GlobalCompositeOperation { @Entry @Component struct ShadowBlur { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true); + private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); build() { @@ -769,7 +758,7 @@ struct ShadowBlur { @Entry @Component struct ShadowColor { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -799,7 +788,7 @@ struct ShadowColor { @Entry @Component struct ShadowOffsetX { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -830,7 +819,7 @@ struct ShadowOffsetX { @Entry @Component struct ShadowOffsetY { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -860,7 +849,7 @@ struct ShadowOffsetY { @Entry @Component struct ImageSmoothingEnabled { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") @@ -959,7 +948,7 @@ fillRect\(x: number, y: number, w: number, h: number\): void @Entry @Component struct FillRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -1055,7 +1044,7 @@ strokeRect\(x: number, y: number, w: number, h: number\): void @Entry @Component struct StrokeRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1150,7 +1139,7 @@ clearRect\(x: number, y: number, w: number, h: number\): void @Entry @Component struct ClearRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1236,7 +1225,7 @@ fillText\(text: string, x: number, y: number\): void @Entry @Component struct FillText { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1321,7 +1310,7 @@ strokeText\(text: string, x: number, y: number\): void @Entry @Component struct StrokeText { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1421,7 +1410,7 @@ measureText\(text: string\): TextMetrics @Entry @Component struct MeasureText { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -1484,8 +1473,8 @@ stroke\(path?: Path2D\): void ``` @Entry @Component - struct Stroke { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -1522,7 +1511,7 @@ beginPath\(\): void @Entry @Component struct BeginPath { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -1601,7 +1590,7 @@ moveTo\(x: number, y: number\): void @Entry @Component struct MoveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -1678,7 +1667,7 @@ lineTo\(x: number, y: number\): void @Entry @Component struct LineTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -1715,7 +1704,7 @@ closePath\(\): void @Entry @Component struct ClosePath { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -1793,7 +1782,7 @@ createPattern\(image: ImageBitmap, repetition: string\): void @Entry @Component struct CreatePattern { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") @@ -1914,7 +1903,7 @@ bezierCurveTo\(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number @Entry @Component struct BezierCurveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2013,7 +2002,7 @@ quadraticCurveTo\(cpx: number, cpy: number, x: number, y: number\): void @Entry @Component struct QuadraticCurveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true); + private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -2133,7 +2122,7 @@ arc\(x: number, y: number, radius: number, startAngle: number, endAngle: number, @Entry @Component struct Arc { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2242,7 +2231,7 @@ arcTo\(x1: number, y1: number, x2: number, y2: number, radius: number\): void @Entry @Component struct ArcTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2383,8 +2372,8 @@ ellipse\(x: number, y: number, radiusX: number, radiusY: number, rotation: numbe ``` @Entry @Component - struct Ellipse { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2485,8 +2474,8 @@ rect\(x: number, y: number, width: number, height: number\): void ``` @Entry @Component - struct Rect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2521,7 +2510,7 @@ fill\(\): void @Entry @Component struct Fill { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2556,7 +2545,7 @@ clip\(\): void @Entry @Component struct Clip { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2627,7 +2616,7 @@ rotate\(rotate: number\): void @Entry @Component struct Rotate { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2702,7 +2691,7 @@ scale\(x: number, y: number\): void @Entry @Component struct Scale { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2826,7 +2815,7 @@ transform方法对应一个变换矩阵,想对一个图形进行变化的时 @Entry @Component struct Transform { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -2950,7 +2939,7 @@ setTransfrom方法使用的参数和transform\(\)方法相同,但setTransform\ @Entry @Component struct SetTransform { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -3027,7 +3016,7 @@ translate\(x: number, y: number\): void @Entry @Component struct Translate { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -3184,7 +3173,7 @@ drawImage\(image: ImageBitmap, sx: number, sy: number, sWidth: number, sHeight: @Entry @Component struct ImageExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true); + private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); build() { @@ -3461,7 +3450,7 @@ putImageData\(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY @Entry @Component struct PutImageData { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -3501,8 +3490,8 @@ restore\(\): void ``` @Entry @Component - struct Restore { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -3512,7 +3501,7 @@ restore\(\): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.controller.restore() + this.context.restore() }) } .width('100%') @@ -3533,8 +3522,8 @@ save\(\): void ``` @Entry @Component - struct Restore { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { @@ -3627,9 +3616,8 @@ createLinearGradient\(x0: number, y0: number, x1: number, y1: number\): void @Entry @Component struct CreateLinearGradient { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private gra:CanvasGradient = new CanvasGradient() build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -3639,9 +3627,9 @@ createLinearGradient\(x0: number, y0: number, x1: number, y1: number\): void .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.context.createLinearGradient(50,0, 300,100) - this.gra.addColorStop(0.0, 'red') - this.gra.addColorStop(0.5, 'white') - this.gra.addColorStop(1.0, 'green') + grad.addColorStop(0.0, 'red') + grad.addColorStop(0.5, 'white') + grad.addColorStop(1.0, 'green') this.context.fillStyle = grad this.context.fillRect(0, 0, 500, 500) }) @@ -3750,9 +3738,8 @@ createRadialGradient\(x0: number, y0: number, r0: number, x1: number, y1: number @Entry @Component struct CreateRadialGradient { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private gra:CanvasGradient = new CanvasGradient() build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -3762,9 +3749,9 @@ createRadialGradient\(x0: number, y0: number, r0: number, x1: number, y1: number .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.context.createRadialGradient(200,200,50, 200,200,200) - this.gra.addColorStop(0.0, 'red') - this.gra.addColorStop(0.5, 'white') - this.gra.addColorStop(1.0, 'green') + grad.addColorStop(0.0, 'red') + grad.addColorStop(0.5, 'white') + grad.addColorStop(1.0, 'green') this.context.fillStyle = grad this.context.fillRect(0, 0, 500, 500) }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md index 5133d246a5ab8fe433a70e49eb1175f3d195f862..890dddfd3f0f5460b8701fa0016a1cfe4c6f9692 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md @@ -78,7 +78,7 @@ Canvas\(context: CanvasRenderingContext2D\) @Entry @Component struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) build() { diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index 30324ac239042e494db9368c7f90e3a5118eb1b1..ece4af28de8ab0b2b2f7f3c5a62f29a081a7065f 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -56,9 +56,8 @@ addColorStop\(offset: number, color: string\): void @Entry @Component struct Page45 { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private gra:CanvasGradient = new CanvasGradient() build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -68,9 +67,9 @@ addColorStop\(offset: number, color: string\): void .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.context.createLinearGradient(50,0, 300,100) - this.gra.addColorStop(0.0, 'red') - this.gra.addColorStop(0.5, 'white') - this.gra.addColorStop(1.0, 'green') + grad.addColorStop(0.0, 'red') + grad.addColorStop(0.5, 'white') + grad.addColorStop(1.0, 'green') this.context.fillStyle = grad this.context.fillRect(0, 0, 500, 500) }) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md index d4a3609367f5e27349ede2f1f27848edd079a344..fcf6834efccdf82fe89ae1b5ade67eaa00ac30b5 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md @@ -83,7 +83,7 @@ ImageBitmap\(src: string\) @Entry @Component struct DrawImageExample { - private settings:RenderingContextSettings = new RenderingContextSettings(true,true) + private settings:RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/example.jpg") diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md index e4193e5a512ff0d0321fabcfb62dabf4877f6a7d..ae6665dd8b95a396696b7e75f3e265b777522755 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md @@ -45,7 +45,7 @@ addPath\(path: Object\): void @Entry @Component struct AddPath { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Da: Path2D = new Path2D("M250 150 L150 350 L350 350 Z") @@ -83,7 +83,7 @@ closePath\(\): void @Entry @Component struct ClosePath { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() @@ -161,7 +161,7 @@ moveTo\(x: number, y: number\): void @Entry @Component struct MoveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() @@ -239,7 +239,7 @@ lineTo\(x: number, y: number\): void @Entry @Component struct LineTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() @@ -363,7 +363,7 @@ bezierCurveTo\(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number @Entry @Component struct BezierCurveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() @@ -460,7 +460,7 @@ quadraticCurveTo\(cpx: number, cpy: number, x: number ,y: number\): void @Entry @Component struct QuadraticCurveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() @@ -580,7 +580,7 @@ arc\(x: number, y: number, radius: number, startAngle: number, endAngle: number, @Entry @Component struct Arc { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() @@ -687,7 +687,7 @@ arcTo\(x1: number, y1: number, x2: number, y2: number, radius: number\): void @Entry @Component struct ArcTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() @@ -827,8 +827,8 @@ ellipse\(x: number, y: number, radiusX: number, radiusY: number, rotation: numbe ``` @Entry @Component - struct Ellipse { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() @@ -924,8 +924,8 @@ rect\(x: number, y: number, width: number, height: number\): void ``` @Entry @Component - struct Rect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index b2815c7ef50d1dc34413c5bbde53915d445659ee..5e7ef1059b8e62baf37c51cd5d402d3ba64ef6cd 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -258,7 +258,7 @@ OffscreenCanvasRenderingContext2D\(width: number, height: number, setting: Rende @Entry @Component struct FillStyleExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -289,7 +289,7 @@ struct FillStyleExample { @Entry @Component struct LineWidthExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -320,7 +320,7 @@ struct LineWidthExample { @Entry @Component struct StrokeStyleExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -352,7 +352,7 @@ struct StrokeStyleExample { @Entry @Component struct LineCapExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -387,7 +387,7 @@ struct LineCapExample { @Entry @Component struct LineJoinExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -423,7 +423,7 @@ struct LineJoinExample { @Entry @Component struct MiterLimit { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -459,7 +459,7 @@ struct MiterLimit { @Entry @Component struct Font { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -489,8 +489,8 @@ struct Font { ``` @Entry @Component -struct TextAlign { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -536,7 +536,7 @@ struct TextAlign { @Entry @Component struct TextBaseline { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -582,7 +582,7 @@ struct TextBaseline { @Entry @Component struct GlobalAlpha { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -616,7 +616,7 @@ struct GlobalAlpha { @Entry @Component struct LineDashOffset { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -712,7 +712,7 @@ struct LineDashOffset { @Entry @Component struct GlobalCompositeOperation { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -751,7 +751,7 @@ struct GlobalCompositeOperation { @Entry @Component struct ShadowBlur { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -784,7 +784,7 @@ struct ShadowBlur { @Entry @Component struct ShadowColor { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -818,7 +818,7 @@ struct ShadowColor { @Entry @Component struct ShadowOffsetX { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -852,7 +852,7 @@ struct ShadowOffsetX { @Entry @Component struct ShadowOffsetY { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -886,7 +886,7 @@ struct ShadowOffsetY { @Entry @Component struct ImageSmoothingEnabled { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -987,7 +987,7 @@ fillRect\(x: number, y: number, w: number, h: number\): void @Entry @Component struct FillRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -1086,7 +1086,7 @@ strokeRect\(x: number, y: number, w: number, h: number\): void @Entry @Component struct StrokeRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1184,7 +1184,7 @@ clearRect\(x: number, y: number, w: number, h: number\): void @Entry @Component struct ClearRect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1273,7 +1273,7 @@ fillText\(text: string, x: number, y: number\): void @Entry @Component struct FillText { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1361,7 +1361,7 @@ strokeText\(text: string, x: number, y: number\): void @Entry @Component struct StrokeText { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1463,7 +1463,7 @@ measureText\(text: string\): TextMetrics @Entry @Component struct MeasureText { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1529,10 +1529,10 @@ stroke\(path?: Path2D\): void ``` @Entry @Component - struct Stroke { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenRenderingContext(600, 600, this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1569,7 +1569,7 @@ beginPath\(\): void @Entry @Component struct BeginPath { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1650,7 +1650,7 @@ moveTo\(x: number, y: number\): void @Entry @Component struct MoveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1729,7 +1729,7 @@ lineTo\(x: number, y: number\): void @Entry @Component struct LineTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1768,7 +1768,7 @@ closePath\(\): void @Entry @Component struct ClosePath { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -1848,7 +1848,7 @@ createPattern\(image: ImageBitmap, repetition: string\): CanvasPattern @Entry @Component struct CreatePattern { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -1971,7 +1971,7 @@ bezierCurveTo\(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number @Entry @Component struct BezierCurveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2072,7 +2072,7 @@ quadraticCurveTo\(cpx: number, cpy: number, x: number, y: number\): void @Entry @Component struct QuadraticCurveTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2194,7 +2194,7 @@ arc\(x: number, y: number, radius: number, startAngle: number, endAngle: number, @Entry @Component struct Arc { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2305,7 +2305,7 @@ arcTo\(x1: number, y1: number, x2: number, y2: number, radius: number\): void @Entry @Component struct ArcTo { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2448,8 +2448,8 @@ ellipse\(x: number, y: number, radiusX: number, radiusY: number, rotation: numbe ``` @Entry @Component - struct Ellipse { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2548,8 +2548,8 @@ rect\(x: number, y: number, width: number, height: number\): void ``` @Entry @Component - struct Rect { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2586,7 +2586,7 @@ fill\(\): void @Entry @Component struct Fill { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2623,7 +2623,7 @@ clip\(\): void @Entry @Component struct Clip { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2692,7 +2692,7 @@ rotate\(rotate: number\): void @Entry @Component struct Rotate { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2769,7 +2769,7 @@ scale\(x: number, y: number\): void @Entry @Component struct Scale { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -2895,7 +2895,7 @@ transform方法对应一个变换矩阵,想对一个图形进行变化的时 @Entry @Component struct Transform { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -3021,7 +3021,7 @@ setTransfrom方法使用的参数和transform\(\)方法相同,但setTransform\ @Entry @Component struct SetTransform { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -3100,7 +3100,7 @@ translate\(x: number, y: number\): void @Entry @Component struct Translate { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -3259,7 +3259,7 @@ drawImage\(image: ImageBitmap, sx: number, sy: number, sWidth: number, sHeight: @Entry @Component struct Index { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -3539,7 +3539,7 @@ putImageData\(imageData: Object, dx: number, dy: number, dirtyX?: number, dirtyY @Entry @Component struct PutImageData { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -3581,8 +3581,8 @@ restore\(\): void ``` @Entry @Component - struct Restore { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -3615,8 +3615,8 @@ save\(\): void ``` @Entry @Component - struct Restore { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { @@ -3711,9 +3711,8 @@ createLinearGradient\(x0: number, y0: number, x1: number, y1: number\): void @Entry @Component struct CreateLinearGradient { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private gra:CanvasGradient = new CanvasGradient() private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -3723,9 +3722,9 @@ createLinearGradient\(x0: number, y0: number, x1: number, y1: number\): void .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.offContext.createLinearGradient(50,0, 300,100) - this.gra.addColorStop(0.0, 'red') - this.gra.addColorStop(0.5, 'white') - this.gra.addColorStop(1.0, 'green') + grad.addColorStop(0.0, 'red') + grad.addColorStop(0.5, 'white') + grad.addColorStop(1.0, 'green') this.offContext.fillStyle = grad this.offContext.fillRect(0, 0, 500, 500) var image = this.offContext.transferToImageBitmap() @@ -3836,9 +3835,8 @@ createRadialGradient\(x0: number, y0: number, r0: number, x1: number, y1: number @Entry @Component struct CreateRadialGradient { - private settings: RenderingContextSettings = new RenderingContextSettings(true,true) + private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private gra:CanvasGradient = new CanvasGradient() private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { @@ -3848,9 +3846,9 @@ createRadialGradient\(x0: number, y0: number, r0: number, x1: number, y1: number .backgroundColor('#ffff00') .onReady(() =>{ var grad = this.offContext.createRadialGradient(200,200,50, 200,200,200) - this.gra.addColorStop(0.0, 'red') - this.gra.addColorStop(0.5, 'white') - this.gra.addColorStop(1.0, 'green') + grad.addColorStop(0.0, 'red') + grad.addColorStop(0.5, 'white') + grad.addColorStop(1.0, 'green') this.offContext.fillStyle = grad this.offContext.fillRect(0, 0, 500, 500) var image = this.offContext.transferToImageBitmap() diff --git a/zh-cn/contribute/OpenHarmony-64bits-coding-guide.md b/zh-cn/contribute/OpenHarmony-64bits-coding-guide.md index a9a6b2b27ecd7c5b357b520ad8646817b80eeb44..4b13d58fcaf4829611ed49195b4fcf618772ab7c 100755 --- a/zh-cn/contribute/OpenHarmony-64bits-coding-guide.md +++ b/zh-cn/contribute/OpenHarmony-64bits-coding-guide.md @@ -7,7 +7,7 @@ OpenHarmony的目标是面向全场景、全连接、全智能时代,基于开源的方式,搭建一个智能终端设备操作系统的框架和平台,促进万物互联产业的繁荣发展。具有“硬件互助,资源共享”、“一次开发,多端部署”、“统一OS,弹性部署”的技术特性。 OpenHarmony支持三种系统类型: -1. 轻量系统(mini system),面向从MCU类处理器(例如Arm Cortex-M、RISC-V 32位)的轻量设备,硬件资源极其有限,支持的设备最小内存为128KiB; +1. 轻量系统(mini system),面向MCU类处理器(例如Arm Cortex-M、RISC-V 32位)的轻量设备,硬件资源极其有限,支持的设备最小内存为128KiB; 2. 小型系统(small system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为1MiB 3. 标准系统(standard system),面向应用处理器(例如Arm Cortex-A 64位)的设备,支持的设备最小内存为128MiB @@ -35,7 +35,7 @@ OpenHarmony支持三种系统类型: | size_t | **4** | **8** | **8** | 4 | 8 | | pointer | **4** | **8** | **8** | 4 | 8 | -上表中只包含了部分基本类型,下表分别将ILP32和LP64的siziof和print`进行对比,展示了更全面的常量和类型对应的差异: +上表中只包含了部分基本类型,下表分别将ILP32和LP64的sizeof和print`进行对比,展示了更全面的常量和类型对应的差异: | Type | ILP32 sizeof | ILP32 print | LP64 sizeof | LP64 print | 备注 | | ------------------ | ------------ | ----------- | ----------- | ---------- | ------ | @@ -115,8 +115,8 @@ typedef struct tagFoo { | uint16_t | 2 | 2 | %u | 代替unsigned short | | int32_t | 4 | 4 | %d | 代替int | | uint32_t | 4 | 4 | %u | 代替unsigned int | -| int64_t | 8 | 8 | %PRId64 | 代替long long,宏实现代码兼容 | -| uint64_t | 8 | 8 | %PRIu64 | 代替unsigned longlong,宏实现代码兼容 | +| int64_t | 8 | 8 | %PRId64 | 代替long long、宏实现代码兼容 | +| uint64_t | 8 | 8 | %PRIu64 | 代替unsigned long long、宏实现代码兼容 | | float | 4 | 4 | %f | 单精度浮点数 | | double | 8 | 8 | %lf | 双精度浮点数 | | bool | 1 | 1 | %d | 布尔类型 | @@ -170,7 +170,7 @@ long var; #### 【规则】当需要采用整型变量来存储指针时,变量应该定义成uintptr_t以适应不同的位宽 -【说明】uintptr_t类型用于用于存储指针长度级别的数据,其长度在32位和64位可自动适应。 +【说明】uintptr_t类型用于用于存储指针长度的数据,其长度在32位和64位可自动适应。 【示例】 @@ -262,7 +262,7 @@ format ‘%p’ expects argument of type ‘void *’, but argument 2 has type | 0x80000000LL | 8 | 8 | 增加LL后缀,小于uint32_t范围,长度固定 | | 0x8000000000 | **NA或8** | **8** | 无后缀,超过uint32_t的范围,编译器默认为LL或无效,64位下固定为uint64_t类型 | | 0x8000000000L | **NA或8** | **8** | 后缀为L,对超过uint32_t的范围常数,增加该参数没有意义,应当避免使用 | -| 0x8000000000LL | 8 | 8 | 默认为LL,uint64_t类型 | +| 0x8000000000LL | 8 | 8 | 后缀为LL,uint64_t类型 | 从上表中可看出,使用L或UL后缀的常量,其长度在32位和64位下发生变化,不利于代码的可移植性,因此禁止使用这个后缀。 @@ -533,7 +533,7 @@ q = (int32_t *) (int32_t)&i; int32_t length = (int32_t)strlen(str); // 错误 ``` -strlen返回size_t(它在LP64中是unsigned long),当赋值给一个int32_t时,截断是必然发生的。而通常,截断只会在str的长度大于2GB时才会发生,这种情况在程序中一般不会出现,容易出现问题。 +strlen返回size_t(它在LP64中是unsigned long),当赋值给一个int32_t时,截断是必然发生的。而通常,截断只会在str的长度大于2GB时才会发生,这种情况在程序中一般不会出现,容易忽略。 #### 【规则】在64位环境下使用大数组或大for循环索引时,索引类型应当与下标边界保持一致 diff --git a/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md b/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md index 1c7ae8e8f2bf412c75499e91eb5d1eace88de77e..1521c5dab674669f3497d607275ac24a723aff52 100755 --- a/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md +++ b/zh-cn/contribute/OpenHarmony-hdf-coding-guide.md @@ -16,7 +16,7 @@ HDF(Hardware Driver Foundation)驱动框架,为开发者提供驱动框架 #### 【规则】OpenHarmony的驱动程序,应当使用HDF框架提供的能力实现 -【说明】HDF驱动框架提供了驱动加载、驱动服务管理和驱动消息机制,同时还提供了操作系统抽象层(OSAL, Operating System Abstract Layer)和平台抽象层(PAL, Platform Abstract Layer)来保证驱动程序的跨系统跨平台部署的特性。除此之外,HDF提供了驱动模型的抽象、公共工具、外围器件框架等能力。开发者应该基于HDF提供的这些能力开发驱动,从而保证驱动程序可以在各种形态的OpenHarmony上进行部署。 +【说明】HDF驱动框架提供了驱动加载、驱动服务管理和驱动消息机制,同时还提供了操作系统抽象层(OSAL, Operating System Abstraction Layer)和平台抽象层(PAL, Platform Abstraction Layer)来保证驱动程序的跨系统跨平台部署的特性。除此之外,HDF提供了驱动模型的抽象、公共工具、外围器件框架等能力。开发者应该基于HDF提供的这些能力开发驱动,从而保证驱动程序可以在各种形态的OpenHarmony上进行部署。 #### 【规则】开发者应当遵循此规范要求,开发能够同时满足内核态和用户态的驱动 @@ -332,7 +332,7 @@ root { #### 【建议】当preload字段配置为默认加载时,应当根据业务要求配置按序加载的优先级 -【说明】在HDF框架定义的device_info.hcs配置文件中,priority字段(取值范围为整数0到200)是用来表示Host和驱动的优先级。不同的Host内的驱动,Host的priority值越小,驱动加载优先级越高;同一个Host内驱动的priority值越小,加载优先级越高。priority字段的默认值为100,当未配置或字段值相同时,HDF框架将不保证驱动的加载顺序。开发者应当根据业务场景的要求,配置preority字段,保证各个驱动的启动顺序。 +【说明】在HDF框架定义的device_info.hcs配置文件中,priority字段(取值范围为整数0到200)是用来表示Host和驱动的优先级。不同的Host内的驱动,Host的priority值越小,驱动加载优先级越高;同一个Host内驱动的priority值越小,加载优先级越高。priority字段的默认值为100,当未配置或字段值相同时,HDF框架将不保证驱动的加载顺序。开发者应当根据业务场景的要求,配置priority字段,保证各个驱动的启动顺序。 【样例】 diff --git a/zh-cn/device-dev/get-code/gettools-acquire.md b/zh-cn/device-dev/get-code/gettools-acquire.md index 9fe2e55209f388f28f3bddae6e5d6a75c2f95fa0..dc8a50e2512fb9d81540f85e30f573545bf987d2 100644 --- a/zh-cn/device-dev/get-code/gettools-acquire.md +++ b/zh-cn/device-dev/get-code/gettools-acquire.md @@ -43,7 +43,7 @@ OpenHarmony为开发者提供了两种Docker环境,以帮助开发者快速完

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

0.0.5

+

0.0.6

标准系统

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