提交 3b0247da 编写于 作者: J jerry 提交者: Gitee

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

Signed-off-by: Njerry <sijunjie@huawei.com>
...@@ -407,7 +407,7 @@ zh-cn/application-dev/reference/apis/js-apis-prompt.md @huaweimaxuchu @HelloCrea ...@@ -407,7 +407,7 @@ zh-cn/application-dev/reference/apis/js-apis-prompt.md @huaweimaxuchu @HelloCrea
zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone zh-cn/application-dev/reference/apis/js-apis-queue.md @gongjunsong @ge-yafang @flyingwolf @BlackStone
zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785 zh-cn/application-dev/reference/apis/js-apis-radio.md @zhang-hai-feng @zengyawen @jyh926 @gaoxi785
zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @jayleehw @RayShih @li-weifeng2 @currydavids
zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @zengyawen @nagexiucai @murphy1984 zh-cn/application-dev/reference/apis/js-apis-request.md @feng-aiwen @ningningW @nagexiucai @murphy1984
zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @budda-wang @yangqing3 zh-cn/application-dev/reference/apis/js-apis-resource-manager.md @Buda-Liu @ningningW @budda-wang @yangqing3
zh-cn/application-dev/reference/apis/js-apis-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy zh-cn/application-dev/reference/apis/js-apis-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world zh-cn/application-dev/reference/apis/js-apis-rpc.md @xuepianpian @RayShih @zhaopeng_gitee @vagrant_world
...@@ -589,7 +589,7 @@ zh-cn/application-dev/reference/errorcodes/errorcode-power.md @zengyawen ...@@ -589,7 +589,7 @@ zh-cn/application-dev/reference/errorcodes/errorcode-power.md @zengyawen
zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang
zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md @HelloCrease zh-cn/application-dev/reference/errorcodes/errorcode-promptAction.md @HelloCrease
zh-cn/application-dev/reference/errorcodes/errorcode-reminderAgentManager.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-reminderAgentManager.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-request.md @zengyawen zh-cn/application-dev/reference/errorcodes/errorcode-request.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @ningningW zh-cn/application-dev/reference/errorcodes/errorcode-resource-manager.md @ningningW
zh-cn/application-dev/reference/errorcodes/errorcode-router.md @HelloCrease zh-cn/application-dev/reference/errorcodes/errorcode-router.md @HelloCrease
zh-cn/application-dev/reference/errorcodes/errorcode-rpc.md @RayShih zh-cn/application-dev/reference/errorcodes/errorcode-rpc.md @RayShih
......
# Application Test
- [arkXtest User Guide](arkxtest-guidelines.md)
- [SmartPerf User Guide](smartperf-guidelines.md)
- [wukong User Guide](wukong-guidelines.md)
# arkXtest User Guide
## Overview
To accelerate test automation of OpenHarmony, arkXtest — an automated test framework that supports both the JavaScript (JS) and TypeScript (TS) programming languages — is provided.
In this document you will learn about the key functions of arkXtest and how to use it to perform unit testing on application or system APIs and to write UI automated test scripts.
### Introduction
arkXtest is part of the OpenHarmony toolkit and provides basic capabilities of writing and running OpenHarmony automated test scripts. In terms of test script writing, arkXtest offers a wide range of APIs, including basic process APIs, assertion APIs, and APIs related to UI operations. In terms of test script running, arkXtest offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results.
### Principles
arkXtest is divided into two parts: unit test framework and UI test framework.
- Unit Test Framework
As the backbone of arkXtest, the unit test framework offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results. The figure below shows the main functions of the unit test framework.
![](figures/UnitTest.PNG)
The following figure shows the basic unit test process. To start the unit test framework, run the **aa test** command.
![](figures/TestFlow.PNG)
- UI Testing Framework
The UI test framework provides [UiTest APIs](../reference/apis/js-apis-uitest.md) for you to call in different test scenarios. The test scripts are executed on top of the unit test framework mentioned above.
The figure below shows the main functions of the UI test framework.
![](figures/Uitest.PNG)
### Limitations and Constraints
- The features of the UI test framework are available only in OpenHarmony 3.1 and later versions.
- The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md).
## Environment preparations
### Environment Requirements
Software for writing test scripts: DevEco Studio 3.0 or later
Hardware for running test scripts: PC connected to a OpenHarmony device, such as the RK3568 development board
### Setting Up the Environment
[Download DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download) and set it up as instructed on the official website.
## Creating a Test Script
1. Open DevEco Studio and create a project, where the **ohos** directory is where the test script is located.
2. Open the .ets file of the module to be tested in the project directory. Move the cursor to any position in the code, and then right-click and choose **Show Context Actions** > **Create Ohos Test** or press **Alt+Enter** and choose **Create Ohos Test** to create a test class.
## Writing a Unit Test Script
```TS
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
const delegator = abilityDelegatorRegistry.getAbilityDelegator()
export default function abilityTest() {
describe('ActsAbilityTest', function () {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{
console.info('Uitest, start ability finished:' + result)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
})
await sleep(1000);
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
})
done();
})
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
})
}
```
The unit test script must contain the following basic elements:
1. Import of the dependency package so that the dependent test APIs can be used.
2. Test code, mainly about the related logic, such as API invoking.
3. Invoking of the assertion APIs and setting of checkpoints. If there is no checkpoint, the test script is considered as incomplete.
## Writing a UI Test Script
You write a UI test script based on the unit test framework, adding the invoking of APIs provided by the UI test framework to implement the corresponding test logic.
In this example, the UI test script is written based on the preceding unit test script. First, add the dependency package, as shown below:
```js
import {UiDriver,BY,UiComponent,MatchPattern} from '@ohos.uitest'
```
Then, write specific test code. Specifically, implement the click action on the started application page and add checkpoint check cases.
```js
export default function abilityTest() {
describe('ActsAbilityTest', function () {
it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin");
//start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{
console.info('Uitest, start ability finished:' + result)
}).catch(err => {
console.info('Uitest, start ability failed: ' + err)
})
await sleep(1000);
//check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility');
})
//ui test code
//init uidriver
var driver = await UiDriver.create();
await driver.delayMs(1000);
//find button by text 'Next'
var button = await driver.findComponent(BY.text('Next'));
//click button
await button.click();
await driver.delayMs(1000);
//check text
await driver.assertComponentExist(BY.text('after click'));
await driver.pressBack();
done();
})
function sleep(time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
})
}
```
## Running the Test Script
You can run a test script in DevEco Studio in any of the following modes:
- Test package level: All test cases in the test package are executed.
- Test suite level: All test cases defined in the **describe** method are executed.
- Test method level: The specified **it** method, that is, a single test case, is executed.
![](figures/Execute.PNG)
## Viewing the Test Result
After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure.
![](figures/TestResult.PNG)
## FAQs
### FAQs About Unit Test Cases
#### The logs in the test case are printed after the test case result
**Problem**
The logs added to the test case are displayed after the test case execution, rather than during the test case execution.
**Possible Causes**
More than one asynchronous interface is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete.
**Solution**
If more than one asynchronous interface is called, you are advised to encapsulate the interface invoking into the promise mode
#### Error "fail to start ability" is reported during test case execution
**Problem**
When a test case is executed, the console returns the error message "fail to start ability".
**Possible Causes**
An error occurs during the packaging of the test package, and the test framework dependency file is not included in the test package.
**Solution**
Check whether the test package contains the **OpenHarmonyTestRunner.abc** file. If the file does not exist, rebuild and pack the file and perform the test again.
#### Test case execution timeout
**Problem**
After the test case execution is complete, the console displays the error message "execute time XXms", indicating that the case execution times out.
**Possible Causes**
1. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out.
2. The time taken for API invocation is longer than the timeout interval set for test case execution.
**Solution**
1. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails.
2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio.
### FAQs About UI Test Cases
#### The failure log contains "Get windows failed/GetRootByWindow failed"
**Problem**
The UI test case fails to be executed. The HiLog file contains the error message "Get windows failed/GetRootByWindow failed".
**Possible Causes**
The ArkUI feature is disabled. As a result, the control tree information on the test page is not generated.
**Solution**
Run the following command, restart the device, and execute the test case again:
```shell
hdc shell param set persist.ace.testmode.enabled 1
```
#### The failure log contains "uitest-api dose not allow calling concurrently"
**Problem**
The UI test case fails to be executed. The HiLog file contains the error message "uitest-api dose not allow calling concurrently".
**Possible Causes**
1. In the test case, the **await** operator is not added to the asynchronous interface provided by the UI test framework.
2. The UI test case is executed in multiple processes. As a result, multiple UI test processes are started. The framework does not support multi-process invoking.
**Solution**
1. Check the case implementation and add the **await** operator to the asynchronous interface invoking.
2. Do not execute UI test cases in multiple processes.
#### The failure log contains "dose not exist on current UI! Check if the UI has changed after you got the widget object"
**Problem**
The UI test case fails to be executed. The HiLog file contains the error message "dose not exist on current UI! Check if the UI has changed after you got the widget object".
**Possible Causes**
After the target component is found in the code of the test case, the device UI changes. As a result, the found component is lost and the emulation operation cannot be performed.
**Solution**
Run the UI test case again.
# SmartPerf User Guide
## Overview
Performance testing helps developers detect the performance bottlenecks and deliver quality applications that meet user expectations. For this reason, SmartPerf, a performance testing tool specially designed for OpenHarmony developers, is provided.
## Introduction
SmartPerf is a reliable, easy-to-use performance and power consumption test tool built for the OpenHarmony system. It provides KPIs with test value details that help you measure the performance and power consumption of your application, such as FPS, CPU, GPU, and Ftrace.
You can use SmartPerf in two modes: visualized operation mode (SmartPerf-Device) and command-line shell mode (SmartPerf-Daemon). SmartPerf-Device supports visualized operations and floating window based operations (such as data collection control and real-time data display). SmartPerf-Daemon is applicable to devices without screens and devices with high tolerance regarding performance, for example, Hi3568.
## Principles
SmartPerf come with SmartPerf-Device and SmartPerf-Daemon. SmartPerf-Device sends data requests for KPIs (such as FPS, RAM, and Trace) through messages to SmartPerf-Daemon, which then collects and sends back data as requested, and displays the received data. SmartPerf-Daemon also allows on-demand data collection through hell commands. The figure below demonstrates the main functions of SmartPerf.
![SmartPerf](figures/SmartPerfStru.png)
## Constraints
- SmartPerf-Device and SmartPerf-Daemon are pre-installed in version 3.2 and later versions.
- SmartPerf-Device requires a screen to work correctly.
## Environment Preparations
To run SmartPerf-Daemon, you must connect the PC to an OpenHarmony device, such as the RK3568 development board.
## Performing Performance Testing
**Using SmartPerf-Device**
In the screenshots below, the RK3568 development board is used as an example.
1. Set the application for which you want to collect data.
Start SmartPerf-Device. On the home screen, select the test application and test indicators, and touch **Start Test**.
2. Control the data collection process from the floating window.
To start collection, touch **Start** in the floating window. To pause, touch the timer in the floating window to pause data collection. To resume, touch the timer again. To view the collected data in real time, double-touch the timer. To stop, touch and hold the timer. You can drag the floating window to anywhere you like.
3. View the report.
Touch **Report** to view the test report list. Touch **Report List** to view details about test indicators.
**Using SmartPerf-Daemon**
1. Access the shell and run the following command to view the help information:
```
:# SP_daemon --help
```
2. Run the collection commands.
```
:# SP_daemon -N 2 -PKG com.ohos.contacts -c -g -t -p -r
```
**Collection Commands**
| Command | Function |Mandatory|
| :-----| :--------------------- |:-----|
| -N | Set the number of collection times. |Yes|
| -PKG | Set the package name. | No|
| -PID | Sets the PID of a process (applicable to RAM).|No|
| -c | Set whether to collect CPU data. | No|
| -g | Set whether to collect GPU data. |No|
| -f | Set whether to collect FPS data. |No|
| -t | Set whether to collect temperature data. |No|
| -p | Set whether to collect current data. |No|
| -r | Set whether to collect memory data. |No|
The default output path of the test result is as follows:
```
/data/local/tmp/data.csv
```
# wukong User Guide
## Overview
Stability testing is important in that it demonstrates how an application performs under stress. For this reason, wukong, a stability testing tool specially designed for OpenHarmony developers, is provided.
In this document you will learn about the key functions of wukong and how to use it to perform stability testing.
## Introduction
wukong is part of the OpenHarmony toolkit and implements basic application stability test capabilities such as random event injection, component injection, exception capture, report generation, and data traversal of abilities.
## Principles
wukong mainly provides two types of tests: random test and special test.
- Random test
The random test is the staple service of wukong. It provides the basic startup, running, and result summary features, as shown below.
![](figures/wukongRandomTest.png)
The following figure shows the basic running process of the random test, which depends on the **hdc** command.
![](figures/wukongRandomTestFlow.png)
- Special test
The special test provides a wide range of features: traversing the components of an application in sequence, recording and playback, and sleeping and waking up.
The following figure shows the main features of the special test.
![](figures/wukongSpecialTest.png)
For details about the test commands, see [wukong](https://gitee.com/openharmony/ostest_wukong/blob/master/README.md).
## Constraints
1. wukong is pre-installed in version 3.2 and later versions.
2. In versions earlier than 3.2, you must build wukong separately and push it to the tested OpenHarmony device. The procedure is as follows:
How to build:
```
./build.sh --product-name rk3568 --build-target wukong
```
How to push:
```
hdc_std shell mount -o rw,remount /
hdc_std file send wukong /
hdc_std shell chmod a+x /wukong
hdc_std shell mv /wukong /bin/
```
## Environment Preparations
To run commands, connect the PC to an OpenHarmony device, such as the RK3568 development board.
## Performing Stability Testing
**Using wukong exec for Random Test**
Access the shell and run the following random test command:
```
# wukong exec -s 10 -i 1000 -a 0.28 -t 0.72 -c 100
```
Random test commands
| Command | Value | Description |
| -------------- | -------------- | ---------------------------------------------- |
| wukong exec | - | Works as the main command. |
| -s | 10 | Sets the random seed. The value 10 is the seed value. |
| -i | 1000 | Sets the application startup interval to 1000 ms.|
| -a | 0.28 | Sets the proportion of the random application startup test to 28%. |
| -t | 0.72 | Sets the proportion of the random touch test to 72%. |
| -c | 100 | Sets the number of execution times to 100. |
**Using wukong special for Special Test**
Access the shell and run the following commands to perform the sequential traversal test:
```bash
# wukong special -C [bundlename] -p
```
Special test commands
| Command | Value | Description |
| -------------- |-------------- | ---------------------------------------------- |
| wukong special | - | Works as the main command. |
| -C [bundlename] |[bundlename] | Sets the bundle name of the application for the sequential traversal test. |
| -p | - | Indicates a screenshot. |
## Viewing the Test Result
After the test commands are executed, the test result is automatically generated.
You can obtain the test result in the following directory:
```
Before 2022/9/22: /data/local/wukong/report/xxxxxxxx_xxxxxx/
Since 2022/9/22: /data/local/tmp/wukong/report/xxxxxxxx_xxxxxx/
```
>**NOTE**
>
>The folder for test reports is automatically generated.
Content of the folder is described in the table below.
| Folder/File | Description |
| ------------------------------------ | ------------------ |
| exception/ | Stores exception files generated during the test.|
| screenshot/ | Stores screenshots of the sequential traversal test. |
| wukong_report.csv | Stores the test report summary. |
You can view the wukong execution log in the path below:
```
reports/xxxxxxxx_xxxxxx/wukong.log
```
...@@ -13,6 +13,9 @@ ...@@ -13,6 +13,9 @@
- Vibrator - Vibrator
- [Vibrator Overview](vibrator-overview.md) - [Vibrator Overview](vibrator-overview.md)
- [Vibrator Development](vibrator-guidelines.md) - [Vibrator Development](vibrator-guidelines.md)
- Multimodal Input
- [Input Device Development](inputdevice-guidelines.md)
- [Mouse Pointer Development](pointerstyle-guidelines.md)
- Update Service - Update Service
- [Sample Server Overview](sample-server-overview.md) - [Sample Server Overview](sample-server-overview.md)
- [Sample Server Development](sample-server-guidelines.md) - [Sample Server Development](sample-server-guidelines.md)
# Input Device Development
## When to Use
Input device management provides functions such as listening for device hot swap events and querying the keyboard type of a specified device. For example, as a user enters text, the input method determines whether to launch the virtual keyboard based on whether a physical keyboard is currently inserted. Your application can determine whether a physical keyboard is inserted by listening to device hot swap events.
## Modules to Import
```js
import inputDevice from '@ohos.multimodalInput.inputDevice';
```
## Available APIs
The following table lists the common APIs for input device management. For details about the APIs, see [ohos.multimodalInput.inputDevice](../reference/apis/js-apis-inputdevice.md).
| Instance| API | Description|
| ----------- | ------------------------------------------------------------ | -------------------------- |
| inputDevice | function getDeviceList(callback: AsyncCallback\<Array\<number>>): void; | Obtains the list of input devices.|
| inputDevice | function getKeyboardType(deviceId: number, callback: AsyncCallback\<KeyboardType>): void; | Obtains the keyboard type of the input device.|
| inputDevice | function on(type: "change", listener: Callback\<DeviceListener>): void; | Enables listening for device hot swap events.|
| inputDevice | function off(type: "change", listener?: Callback\<DeviceListener>): void; | Disables listening for device hot swap events.|
## Virtual Keyboard Detection
When a user enters text, the input method determines whether to launch the virtual keyboard based on whether a physical keyboard is currently inserted. Your application can determine whether a physical keyboard is inserted by listening to device hot swap events.
## How to Develop
1. Call the **getDeviceList** API to obtain the list of connected input devices. Call the **getKeyboardType** API to traverse all connected devices to check whether a physical keyboard exists. If a physical keyboard exists, mark the physical keyboard as connected. This step ensures that your application detects all inserted input devices before listening for device hot swap events.
2. Call the **on** API to listen for device hot swap events. If a physical keyboard is inserted, mark the physical keyboard as connected. If a physical keyboard is removed, mark the physical keyboard as disconnected.
3. When a user enters text, check whether a physical keyboard is connected. If a physical keyboard is not connected, launch the virtual keyboard.
```js
import inputDevice from '@ohos.multimodalInput.inputDevice';
let isPhysicalKeyboardExist = true;
try {
// 1. Obtain the list of input devices and check whether a physical keyboard is connected.
inputDevice.getDeviceList().then(data => {
for (let i = 0; i < data.length; ++i) {
inputDevice.getKeyboardType(data[i]).then(res => {
if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD) {
// The physical keyboard is connected.
isPhysicalKeyboardExist = true;
}
});
}
});
// 2. Listen for device hot swap events.
inputDevice.on("change", (data) => {
console.log(`Device event info: ${JSON.stringify(data)}`);
inputDevice.getKeyboardType(data.deviceId, (error, type) => {
console.log("The keyboard type is: " + type);
if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
// The physical keyboard is inserted.
isPhysicalKeyboardExist = true;
} else if (type == inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'remove') {
// The physical keyboard is removed.
isPhysicalKeyboardExist = false;
}
});
});
} catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
// 3. Determine whether to launch the virtual keyboard based on the value of isPhysicalKeyboardExist.
// TODO
```
# Mouse Pointer Development
## When to Use
Mouse pointer management provides the functions such as displaying or hiding the mouse pointer as well as querying and setting the pointer style. For example, you can determine whether to display or hide the mouse pointer when a user watches a video in full screen, and can switch the mouse pointer to a color picker when a user attempts color pickup.
## Modules to Import
```js
import inputDevice from '@ohos.multimodalInput.pointer';
```
## Available APIs
The following table lists the common APIs for mouse pointer management. For details about the APIs, see [ohos.multimodalInput.pointer](../reference/apis/js-apis-pointer.md).
| Instance | API | Description |
| ------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| pointer | function isPointerVisible(callback: AsyncCallback\<boolean>): void; | Checks the visible status of the mouse pointer. |
| pointer | function setPointerVisible(visible: boolean, callback: AsyncCallback\<void>): void; | Sets the visible status of the mouse pointer. This setting takes effect for the mouse pointer globally.|
| pointer | function setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\<void>): void; | Sets the mouse pointer style. This setting takes effect for the mouse pointer style of a specified window. |
| pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\<PointerStyle>): void; | Obtains the mouse pointer style. |
## Hiding the Mouse Pointer
When watching a video in full-screen mode, a user can hide the mouse pointer for an improved user experience.
## How to Develop
1. Switch to the full-screen playback mode.
2. Hide the mouse pointer.
3. Exit the full-screen playback mode.
4. Display the mouse pointer.
```js
import pointer from '@ohos.multimodalInput.pointer';
// 1. Switch to the full-screen playback mode.
// 2. Hide the mouse pointer.
try {
pointer.setPointerVisible(false, (error) => {
if (error) {
console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Set pointer visible success.`);
});
} catch (error) {
console.log(`The mouse pointer hide attributes is failed. ${JSON.stringify(error, [`code`, `message`])}`);
}
// 3. Exit the full-screen playback mode.
// 4. Display the mouse pointer.
try {
pointer.setPointerVisible(true, (error) => {
if (error) {
console.log(`Set pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
return;
}
console.log(`Set pointer visible success.`);
});
} catch (error) {
console.log(`Set pointer visible failed, ${JSON.stringify(error, [`code`, `message`])}`);
}
```
## Setting the Mouse Pointer Style
When designing a color picker, you can have the mouse pointer switched to the color picker style during color pickup and then switched to the default style on completion of color pickup. This setting takes effect for the pointer style of a specified window in the current application. A total of 39 pointer styles can be set. For details, see [Pointer Style](../reference/apis/js-apis-pointer.md#pointerstyle9).
### How to Develop
1. Enable the color pickup function.
2. Obtain the window ID.
3. Set the mouse pointer to the color picker style.
4. End color pickup.
5. Set the mouse pointer to the default style.
```js
import window from '@ohos.window';
// 1. Enable the color pickup function.
// 2. Obtain the window ID.
window.getTopWindow((error, windowClass) => {
windowClass.getProperties((error, data) => {
var windowId = data.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
return;
}
try {
// 3. Set the mouse pointer to the color picker style.
pointer.setPointerStyle(windowId, pointer.PointerStyle.COLOR_SUCKER).then(() => {
console.log(`Successfully set mouse pointer style`);
});
} catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`);
}
});
});
// 4. End color pickup.
window.getTopWindow((error, windowClass) => {
windowClass.getProperties((error, data) => {
var windowId = data.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
return;
}
try {
// 5. Set the mouse pointer to the default style.
pointer.setPointerStyle(windowId, pointer.PointerStyle.DEFAULT).then(() => {
console.log(`Successfully set mouse pointer style`);
});
} catch (error) {
console.log(`Failed to set the pointer style, error=${JSON.stringify(error)}, msg=${JSON.stringify(message)}`);
}
});
});
```
...@@ -3,30 +3,18 @@ ...@@ -3,30 +3,18 @@
## When to Use ## When to Use
- Data provided by the compass sensor denotes the current orientation of the user device, which helps your application accurately navigate for the user. With the sensor module, a device can obtain sensor data. For example, the device can subscribe to data of the orientation sensor to detect its own orientation, and data of the pedometer sensor to learn the number of steps the user walks every day.
- Data provided by the proximity sensor denotes the distance between the device and a visible object, which enables the device to automatically turn on or off its screen accordingly to prevent accidental touch on the screen. For details about the APIs, see [Sensor](../reference/apis/js-apis-sensor.md).
- Data provided by the barometer sensor helps your application accurately determine the altitude of the device.
- Data provided by the ambient light sensor helps your device automatically adjust its backlight.
- Data provided by the Hall effect sensor implements the smart cover mode of your device.
- Data provided by the heart rate sensor helps your application track the heart health of a user.
- Data provided by the pedometer sensor helps your application obtain the number of steps a user has walked.
- Data provided by the wear detection sensor helps your application detect whether a user is wearing a wearable device.
## Available APIs ## Available APIs
| Module| API| Description| | Module| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.sensor | sensor.on(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to data changes of a type of sensor.| | ohos.sensor | sensor.on(sensorId, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to data changes of a type of sensor.|
| ohos.sensor | sensor.once(sensorType, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to only one data change of a type of sensor.| | ohos.sensor | sensor.once(sensorId, callback:AsyncCallback&lt;Response&gt;): void | Subscribes to only one data change of a type of sensor.|
| ohos.sensor | sensor.off(sensorType, callback?:AsyncCallback&lt;void&gt;): void | Unsubscribes from sensor data changes.| | ohos.sensor | sensor.off(sensorId, callback?:AsyncCallback&lt;void&gt;): void | Unsubscribes from sensor data changes.|
## How to Develop ## How to Develop
...@@ -43,52 +31,46 @@ ...@@ -43,52 +31,46 @@
For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md). For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
2. Subscribe to data changes of a type of sensor. 2. Subscribe to data changes of a type of sensor. The following uses the acceleration sensor as an example.
``` ```js
import sensor from "@ohos.sensor"; import sensor from "@ohos.sensor";
sensor.on(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data){ sensor.on(sensor.SensorId.ACCELEROMETER, function(data){
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
}); });
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. ![171e6f30-a8d9-414c-bafa-b430340305fb](figures/171e6f30-a8d9-414c-bafa-b430340305fb.png)
![en-us_image_0000001241693881](figures/en-us_image_0000001241693881.png)
3. Unsubscribe from sensor data changes. 3. Unsubscribe from sensor data changes.
``` ```js
import sensor from "@ohos.sensor"; import sensor from "@ohos.sensor";
sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER); sensor.off(sensor.SensorId.ACCELEROMETER);
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. ![65d69983-29f6-4381-80a3-f9ef2ec19e53](figures/65d69983-29f6-4381-80a3-f9ef2ec19e53.png)
![en-us_image_0000001196654004](figures/en-us_image_0000001196654004.png)
4. Subscribe to only one data change of a type of sensor. 4. Subscribe to only one data change of a type of sensor.
``` ```js
import sensor from "@ohos.sensor"; import sensor from "@ohos.sensor";
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) { sensor.once(sensor.SensorId.ACCELEROMETER, function(data) {
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
}); });
``` ```
The following figure shows the successful call result when **SensorType** is **SENSOR_TYPE_ID_ACCELEROMETER**. ![db5d017d-6c1c-4a71-a2dd-f74b7f23239e](figures/db5d017d-6c1c-4a71-a2dd-f74b7f23239e.png)
![en-us_image_0000001241733907](figures/en-us_image_0000001241733907.png)
If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example: If the API fails to be called, you are advised to use the **try/catch** statement to capture error information that may occur in the code. Example:
``` ```js
import sensor from "@ohos.sensor"; import sensor from "@ohos.sensor";
try { try {
sensor.once(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, function(data) { sensor.once(sensor.SensorId.ACCELEROMETER, function(data) {
console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained. console.info("Data obtained successfully. x: " + data.x + "y: " + data.y + "z: " + data.z); // Data is obtained.
}); });
} catch (error) { } catch (error) {
console.error("Failed to get sensor data"); console.error("Get sensor data error. data:" + error.data, " msg:", error.message);
} }
``` ```
\ No newline at end of file
...@@ -3,32 +3,29 @@ ...@@ -3,32 +3,29 @@
Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the [Sensor](../reference/apis/js-apis-sensor.md) APIs, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the [Sensor](../reference/apis/js-apis-sensor.md) APIs, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications.
| Type | Name | Description | Usage |
A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows: | --------------------------- | ------------------ | ------------------------------------------------------------ | ---------------------------------------- |
| ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status |
| Type | Name | Description | Usage | | ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation |
| --------------------------------------- | --------- | ---------------------------------------- | -------------------- | | LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis |
| SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status | | GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity |
| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation | | GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity |
| SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis | | GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity |
| SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity | | SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device |
| SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity | | PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step |
| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity | | PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked |
| SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device | | AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature |
| SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step | | MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass |
| SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked | | MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation |
| SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature | | HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity |
| SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass | | BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar. | Measuring the barometric pressure |
| SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation | | ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad.| Providing the three orientation angles of the screen |
| SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity | | ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor.| Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system |
| SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar.| Measuring the barometric pressure | | PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call |
| SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad. | Providing the three orientation angles of the screen | | AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top|
| SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor. | Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system | | HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data |
| SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call | | WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables |
| SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top| | HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device |
| SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data |
| SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables |
| SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device |
## Working Principles ## Working Principles
...@@ -60,4 +57,3 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso ...@@ -60,4 +57,3 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. | | Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting. 2. The APIs for subscribing to and unsubscribing from sensor data work in pairs. If you do not need sensor data, call the unsubscription API to stop sensor data reporting.
...@@ -10,42 +10,55 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -10,42 +10,55 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
## Available APIs ## Available APIs
| Module | API | Description | | Module | API | Description |
| ------------- | ---------------------------------------- | ------------------------------- | | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| ohos.vibrator | vibrate(duration: number): Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result. | | ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise&lt;void&gt; | Starts vibration with the specified effect and attribute. This API uses a promise to return the result.|
| ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified duration. This API uses a callback to return the result. | | ohos.vibrator | startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback&lt;void&gt;): void | Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result.|
| ohos.vibrator | vibrate(effectId: EffectId): Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result. | | ohos.vibrator | stopVibration(stopMode: VibratorStopMode): Promise&lt;void&gt; | Stops vibration in the specified mode. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified effect. This API uses a callback to return the result.| | ohos.vibrator | stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback&lt;void&gt;): void | Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. |
| ohos.vibrator | stop(stopMode: VibratorStopMode): Promise&lt;void&gt;| Stops vibration. This API uses a promise to return the result. |
| ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void | Stops vibration. This API uses a callback to return the result. |
## How to Develop ## How to Develop
1. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md). 1. Before using the vibrator on a device, you must declare the **ohos.permission.VIBRATE** permission. For details about how to configure a permission, see [Declaring Permissions](../security/accesstoken-guidelines.md).
2. Trigger the device to vibrate. 2. Start vibration with the specified effect and attribute.
``` ```js
import vibrator from "@ohos.vibrator" import vibrator from '@ohos.vibrator';
vibrator.vibrate(1000).then((error) => { try {
if (error) { // The call fails, and error.code and error.message are printed. vibrator.startVibration({
console.log("Promise return failed.error.code " + error.code + "error.message " + error.message); type: 'time',
} else { // The call is successful, and the device starts to vibrate. duration: 1000,
console.log("Promise returned to indicate a successful vibration.") }, {
} id: 0,
}) usage: 'alarm'
}, (error) => {
if (error) {
console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message);
return;
}
console.log('Callback returned to indicate a successful vibration.');
});
} catch (err) {
console.error('errCode: ' + err.code + ' ,msg: ' + err.message);
}
``` ```
3. Stop the vibration. 3. Stop vibration in the specified mode.
``` ```js
import vibrator from "@ohos.vibrator" import vibrator from '@ohos.vibrator';
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => { try {
if (error) { // The call fails, and error.code and error.message are printed. // Stop vibration in VIBRATOR_STOP_MODE_TIME mode.
console.log("Promise return failed.error.code " + error.code + "error.message " + error.message); vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) {
} else { // The call is successful, and the device stops vibrating. if (error) {
console.log("Promise returned to indicate successful."); console.log('error.code' + error.code + 'error.message' + error.message);
} return;
}) }
console.log('Callback returned to indicate successful.');
})
} catch (err) {
console.info('errCode: ' + err.code + ' ,msg: ' + err.message);
}
``` ```
# FAQs # FAQs
- [Ability Framework Development](faqs-ability.md) - [Ability Framework Development](faqs-ability.md)
- [Bundle Management Development](faqs-bundle.md)
- [ArkUI (eTS) Development](faqs-ui-ets.md) - [ArkUI (eTS) Development](faqs-ui-ets.md)
- [ArkUI (JavaScript) Development](faqs-ui-js.md) - [ArkUI (JavaScript) Development](faqs-ui-js.md)
- [Bundle Management Development](faqs-bundle.md)
- [Data Management Development](faqs-data-management.md)
- [Development Board](faqs-development-board.md)
- [Device Management Development](faqs-device-management.md)
- [DFX Development](faqs-dfx.md)
- [Graphics and Image Development](faqs-graphics.md) - [Graphics and Image Development](faqs-graphics.md)
- [hdc_std Command Usage](faqs-ide.md)
- [IDE Usage](faqs-hdc-std.md)
- [Intl Development](faqs-international.md)
- [File Management Development](faqs-file-management.md) - [File Management Development](faqs-file-management.md)
- [Media Development](faqs-media.md) - [Media Development](faqs-media.md)
- [Network and Connection Development](faqs-connectivity.md) - [Network and Connection Development](faqs-connectivity.md)
- [Data Management Development](faqs-data-management.md)
- [Device Management Development](faqs-device-management.md)
- [DFX Development](faqs-dfx.md)
- [Intl Development](faqs-international.md)
- [Native API Usage](faqs-native.md) - [Native API Usage](faqs-native.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md) - [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md)
- [IDE Usage](faqs-ide.md)
- [hdc_std Command Usage](faqs-hdc-std.md)
- [Development Board](faqs-development-board.md)
\ No newline at end of file
...@@ -21,7 +21,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9 ...@@ -21,7 +21,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5, stage model of API version 9
Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available. Error code 28 refers to **CURLE_OPERATION_TIMEDOUT**, which means a cURL operation timeout. For details, see any HTTP status code description available.
Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
## What does error code 6 mean for the response of \@ohos.net.http.d.ts? ## What does error code 6 mean for the response of \@ohos.net.http.d.ts?
...@@ -30,4 +30,4 @@ Applicable to: OpenHarmony SDK 3.2.3.5 ...@@ -30,4 +30,4 @@ Applicable to: OpenHarmony SDK 3.2.3.5
Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible. Error code 6 indicates a failure to resolve the host in the address. You can ping the URL carried in the request to check whether the host is accessible.
Reference: [Development Guide](https://gitee.com/openharmony/docs/blob/master/en/application-dev/reference/apis/js-apis-http.md#httpresponse) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html) Reference: [Response Codes](../reference/apis/js-apis-http.md#responsecode) and [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html)
# Data Management Development # Data Management Development
## How Do I Save PixelMap Data to a Database?
## How Do I Save PixelMap data to a database?
Applicable to: OpenHarmony SDK 3.2.3.5 Applicable to: OpenHarmony SDK 3.2.3.5
You can convert a **PixelMap** into a **ArrayBuffer** and save the **ArrayBuffer** to your database. You can convert a **PixelMap** into an **ArrayBuffer** and save the **ArrayBuffer** to your database.
Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1) Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1)
...@@ -14,11 +12,65 @@ Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstob ...@@ -14,11 +12,65 @@ Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstob
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Run the hdc_std command to copy the .db, .db-shm, and .db-wal files from **/data/app/el2/100/database/Bundle name/entry/db/**, and then use the SQLite tool to open the files. Run the hdc_std command to copy the .db, .db-shm, and .db-wal files in **/data/app/el2/100/database/*bundleName*/entry/db/**, and then use the SQLite tool to open the files.
Example: Example:
``` ```
hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db
``` ```
## Does the Database Has a Lock Mechanism?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
The distributed data service (DDS), relational database (RDB) store, and preferences provided OpenHarmony have a lock mechanism. You do not need to bother with the lock mechanism during the development.
## What Is a Transaction in an RDB Store?
Applicable to: all versions
When a large number of operations are performed in an RDB store, an unexpected exception may cause a failure of some data operations and loss of certain data. As a result, the application may become abnormal or even crash.
A transaction is a group of tasks serving as a single logical unit. It eliminates the failure of some of the operations and loss of associated data.
## What Data Types Does an RDB Store Support?
Applicable to: OpenHarmony SDK 3.0 or later, stage model of API version 9
An RDB store supports data of the number, string, and Boolean types. The number array supports data of the Double, Long, Float, Int, or Int64 type, with a maximum precision of 17 decimal digits.
## How Do I View Database db Files?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
1. Run the **hdc_std shell** command.
2. Obtain the absolute path or sandbox path of the database.
The absolute path is **/data/app/el2/<userId>/database/<bundleName>**. The default **<userId>** is **100**.
To obtain the sandbox path, run the **ps -ef | grep hapName** command to obtain the process ID of the application.
The database sandbox path is **/proc/<Application process ID>/root/data/storage/el2/database/**.
3. Run the **find ./ -name "\*.db"** command in the absolute path or sandbox path of the database.
## How Do I Store Long Text Data?
Applicable to: OpenHarmony SDK 3.2.5.5, API version 9
- Preferences support a string of up to 8192 bytes.
- The KV store supports a value of up to 4 MB.
Reference: [Preference Overview](../database/database-preference-overview.md) and [Distributed Data Service Overview](../database/database-mdds-overview.md)
## How Do I Develop DataShare on the Stage Model
Applicable to: OpenHarmony SDK 3.2.5.5, API version 9
The DataShare on the stage model cannot be used with the **DataAbility** for the FA model. The connected server application must be implemented by using **DataShareExtensionAbility**.
Reference: [DataShare Development](../database/database-datashare-guidelines.md)
...@@ -19,7 +19,7 @@ Run **hdc\_std shell param get persist.ace.testmode.enabled**. ...@@ -19,7 +19,7 @@ Run **hdc\_std shell param get persist.ace.testmode.enabled**.
If the value is **0**, run the **hdc\_std shell param set persist.ace.testmode.enabled 1** to enable the test mode. If the value is **0**, run the **hdc\_std shell param set persist.ace.testmode.enabled 1** to enable the test mode.
## Why Is Private Displayed in Logs When the Format Parameter Type of hilog in C++ Code Is %d or %s? ## Why is private displayed in logs when the format parameter type of HiLog in C++ code is %d or %s?
When format parameters such as **%d** and **%s** are directly used, the standard system uses **private** to replace the actual data for printing by default to prevent data leakage. To print the actual data, replace **%d** with **%{public}d** or replace **%s** with **%{public}s**. When format parameters such as **%d** and **%s** are directly used, the standard system uses **private** to replace the actual data for printing by default to prevent data leakage. To print the actual data, replace **%d** with **%{public}d** or replace **%s** with **%{public}s**.
...@@ -35,7 +35,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5 ...@@ -35,7 +35,7 @@ Applicable to: OpenHarmony SDK 3.2.2.5
You are advised to use the [HiLog](../reference/apis/js-apis-hilog.md) for log printing. For details about how to set the **domain** parameter, see the [Development Guide](../reference/apis/js-apis-hilog.md#hilogisloggable). You are advised to use the [HiLog](../reference/apis/js-apis-hilog.md) for log printing. For details about how to set the **domain** parameter, see the [Development Guide](../reference/apis/js-apis-hilog.md#hilogisloggable).
## What is the maximum length of a log record when HiLog Is used? Is it configurable? ## What is the maximum length of a log record when HiLog is used? Is it configurable?
Applicable to: OpenHarmony SDK 3.2.2.5 Applicable to: OpenHarmony SDK 3.2.2.5
......
# File Management Development # File Management Development
## Does fileio.rmdir Delete Files Recursively?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
## What If There is No Return Value or Error Captured After getAlbums Is Called? Yes. **fileio.rmdir** deletes files recursively.
## How Do I Create a File That Does Not Exist?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
You can use **fileio.open(filePath, 0o100, 0o666)**. The second parameter **0o100** means to create a file if it does not exist. The third parameter **mode** must also be specified.
## What If "call fail callback fail, code: 202, data: json arguments illegal" Is Displayed?
Applicable to: OpenHarmony SDK 3.2.6.3, stage model of API version 9
When the **fileio** module is used to copy files, the file path cannot start with "file:///".
## How Do I Read Files Outside the App Sandbox?
Applicable to: OpenHarmony SDK 3.2.6.5, stage model of API version 9
If the input parameter of the **fileio** API is **path**, only the sandbox directory of the current app obtained from the context can be accessed. To access data in other directories such as the user data, images, and videos, open the file as the data owner and operate with the file descriptor (FD) returned.
For example, to read or write a file in Media Library, perform the following steps:
1. Use **getFileAssets()** to obtain the **fileAsset** object.
2. Use **fileAsset.open()** to obtain the FD.
3. Use the obtained FD as the **fileIo** API parameter to read and write the file.
## What If the File Contains Garbled Characters?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Read the file content from the buffer, and decode the file content using **util.TextDecoder**.
Example:
```
import util from '@ohos.util'
async function readFile(path) {
let stream = fileio.createStreamSync(path, "r+");
let readOut = await stream.read(new ArrayBuffer(4096));
let textDecoder = new util.TextDecoder("utf-8", { ignoreBOM: true });
let buffer = new Uint8Array(readOut.buffer)
let readString = textDecoder.decode(buffer, { stream: false });
console.log ("[Demo] File content read: "+ readString);
}
```
## What Should I Do If There Is No Return Value or Error Captured After getAlbums Is Called?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbums**, and this permission needs user authorization. For details, see OpenHarmony [Application Permission List](../security/permission-list.md). The **ohos.permission.READ_MEDIA** is required for using **getAlbums()**. In addition, this permission needs user authorization. For details, see [OpenHarmony Permission List](../security/permission-list.md).
1. Configure the required permission in the **module.json5** file. 1. Configure the required permission in the **module.json5** file.
``` ```
"requestPermissions": [ "requestPermissions": [
{ {
...@@ -19,7 +69,7 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum ...@@ -19,7 +69,7 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum
``` ```
2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded. 2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded.
``` ```
private requestPermissions() { private requestPermissions() {
let permissionList: Array<string> = [ let permissionList: Array<string> = [
...@@ -34,3 +84,21 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum ...@@ -34,3 +84,21 @@ The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbum
}) })
} }
``` ```
## What Do I Do If the App Crashes When FetchFileResult() Is Called Multiple Times?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Each time after the **FetchFileResult** object is called, call **FetchFileResult.close()** to release and invalidate the **FetchFileResult** object .
## What If An Error Is Reported by IDE When mediaLibrary.getMediaLibrary() Is Called in the Stage Model?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
In the stage model, use **mediaLibrary.getMediaLibrary(context: Context)** to obtain the media library instance.
## How Do I Sort the Data Returned by mediaLibrary.getFileAssets()?
Applicable to: OpenHarmony SDK 3.2.5.5, stage model of API version 9
Use the **order** attribute in **[MediaFetchOptions](../reference/apis/js-apis-medialibrary.md#mediafetchoptions7)** to sort the data returned.
...@@ -45,7 +45,7 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim ...@@ -45,7 +45,7 @@ Use [Locale](../reference/apis/js-apis-intl.md#locale) APIs to maximize or minim
```js ```js
var locale = "zh-CN"; var locale = "zh-CN";
var options = {caseFirst: false, calendar: "chinese", collation: "pinyin"}; var options = {caseFirst: "false", calendar: "chinese", collation: "pinyin"};
var localeObj = new intl.Locale(locale, options); var localeObj = new intl.Locale(locale, options);
``` ```
...@@ -347,4 +347,4 @@ The following sample is provided to help you better understand how to develop in ...@@ -347,4 +347,4 @@ The following sample is provided to help you better understand how to develop in
-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International) -[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International)
-[`International`: Internationalization (eTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) -[`International`: Internationalization (ArkTS) (API8) (Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International)
...@@ -5,3 +5,4 @@ ...@@ -5,3 +5,4 @@
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
- [Native Window Development](native-window-guidelines.md) - [Native Window Development](native-window-guidelines.md)
- [Using MindSpore Lite for Model Inference](mindspore-lite-guidelines.md) - [Using MindSpore Lite for Model Inference](mindspore-lite-guidelines.md)
- [Connecting the Neural Network Runtime to an AI Inference Framework](neural-network-runtime-guidelines.md)
...@@ -24,7 +24,7 @@ APIs involved in MindSpore Lite model inference are categorized into context API ...@@ -24,7 +24,7 @@ APIs involved in MindSpore Lite model inference are categorized into context API
| ------------------ | ----------------- | | ------------------ | ----------------- |
|OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.| |OH_AI_ContextHandle OH_AI_ContextCreate()|Creates a context object.|
|void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.| |void OH_AI_ContextSetThreadNum(OH_AI_ContextHandle context, int32_t thread_num)|Sets the number of runtime threads.|
| void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are categorized into little cores and big cores depending on the CPU frequency.| | void OH_AI_ContextSetThreadAffinityMode(OH_AI_ContextHandle context, int mode)|Sets the affinity mode for binding runtime threads to CPU cores, which are classified into large, medium, and small cores based on the CPU frequency. You only need to bind the large or medium cores, but not small cores.|
|OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.| |OH_AI_DeviceInfoHandle OH_AI_DeviceInfoCreate(OH_AI_DeviceType device_type)|Creates a runtime device information object.|
|void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.| |void OH_AI_ContextDestroy(OH_AI_ContextHandle *context)|Destroys a context object.|
|void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.| |void OH_AI_DeviceInfoSetEnableFP16(OH_AI_DeviceInfoHandle device_info, bool is_fp16)|Sets whether to enable float16 inference. This function is available only for CPU and GPU devices.|
......
# Development References # Development References
- [SystemCapability](syscap.md)
- [SysCap List](syscap-list.md) - [SysCap List](syscap-list.md)
- [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md) - [Component Reference (ArkTS-based Declarative Development Paradigm)](arkui-ts/Readme-EN.md)
- [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md) - [Component Reference (JavaScript-compatible Web-like Development Paradigm)](arkui-js/Readme-EN.md)
- [API Reference (JS and TS APIs)](apis/Readme-EN.md) - [JS Service Widget UI Component Reference](js-service-widget-ui/Readme-EN.md)
- [API Reference (ArkTS and JS APIs)](apis/Readme-EN.md)
- [Error Codes](errorcodes/Readme-EN.md)
- API Reference (Native APIs) - API Reference (Native APIs)
- [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md) - [Standard Libraries Supported by Native APIs](native-lib/Readme-EN.md)
# @ohos.accessibility.GesturePath
The **GesturePath** module provides APIs for creating gesture path information required for an accessibility application to inject gestures.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import GesturePath from '@ohos.accessibility.GesturePath';
```
## GesturePath
Defines a gesture path.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
| Name | Type | Readable | Writable | Description |
| ------------ | ---------------------------------------- | ---- | ---- | ------ |
| points | Array&lt;[GesturePoint](js-apis-accessibility-GesturePoint.md#gesturepoint)&gt; | Yes | Yes | Gesture touch point. |
| durationTime | number | Yes | Yes | Total gesture duration, in milliseconds.|
### constructor
constructor(durationTime: number);
Constructor used to create a **GesturePath** object.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| durationTime | number | Yes| Total gesture duration, in milliseconds.|
**Example**
```ts
let gesturePath = new GesturePath.GesturePath(20);
```
# @ohos.accessibility.GesturePoint
The **GesturePoint** module provides APIs for creating gesture touch point information required for an accessibility application to inject gestures.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```ts
import GesturePoint from '@ohos.accessibility.GesturePoint';
```
## GesturePoint
Defines a gesture touch point.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
| Name | Type | Readable | Writable | Description |
| --------- | ------ | ---- | ---- | ------- |
| positionX | number | Yes | Yes | X coordinate of the touch point.|
| positionY | number | Yes | Yes | Y coordinate of the touch point.|
### constructor
constructor(positionX: number, positionY: number);
Constructor used to create a **GesturePoint** object.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| positionX | number | Yes| X coordinate of the touch point.|
| positionY | number | Yes | Y coordinate of the touch point.|
**Example**
```ts
let gesturePoint = new GesturePoint.GesturePoint(1, 2);
```
# Accessibility Extension Ability # @ohos.application.AccessibilityExtensionAbility
The **AccessibilityExtensionAbility** module is based on the ExtensionAbility framework and provides the **AccessibilityExtensionAbility**. The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the ExtensionAbility framework.
>**NOTE** > **NOTE**
> >
>The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
>The APIs of this module can be used only in the stage model.
## Modules to Import ## Modules to Import
...@@ -18,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens ...@@ -18,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
| Name | Type | Readable | Writable | Description | | Name | Type| Readable| Writable| Description |
| --------- | -------- | ---- | ---- | ------------------------- | | --------- | -------- | ---- | ---- | ------------------------- |
| context | [AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) | Yes | No | Context of the accessibility extension ability. | | context | [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) | Yes| No| Context of the accessibility extension ability.|
## AccessibilityEvent ## AccessibilityEvent
...@@ -32,36 +30,10 @@ Defines an accessibility event. ...@@ -32,36 +30,10 @@ Defines an accessibility event.
| Name | Type | Readable | Writable | Description | | Name | Type | Readable | Writable | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------- | | --------- | ---------------------------------------- | ---- | ---- | ---------- |
| eventType | [EventType](js-apis-accessibility.md#eventtype) \| [WindowUpdateType](js-apis-accessibility.md#windowupdatetype) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | | eventType | [accessibility.EventType](js-apis-accessibility.md#EventType) \| [accessibility.WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. |
| target | AccessibilityElement | Yes | No | Target component where the event occurs.| | target | AccessibilityElement | Yes | No | Target component where the event occurs.|
| timeStamp | number | Yes | No | Timestamp of the event. | | timeStamp | number | Yes | No | Timestamp of the event. |
## GesturePath
Defines a gesture path.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
| Name | Type | Readable | Writable | Description |
| ------------ | ---------------------------------------- | ---- | ---- | ------ |
| points | Array&lt;[GesturePoint](gesturepoint)&gt; | Yes | Yes | An array of gesture touch points. |
| durationTime | number | Yes | Yes | Total time consumed by the gesture.|
## GesturePoint
Defines a gesture touch point.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
### Attributes
| Name | Type | Readable | Writable | Description |
| --------- | ------ | ---- | ---- | ------- |
| positionX | number | Yes | Yes | X-coordinate of the touch point.|
| positionY | number | Yes | Yes | Y-coordinate of the touch point.|
## GestureType ## GestureType
Enumerates gesture types. Enumerates gesture types.
...@@ -89,7 +61,7 @@ Enumerates gesture types. ...@@ -89,7 +61,7 @@ Enumerates gesture types.
## PageUpdateType ## PageUpdateType
Enumerates the page refresh types. Enumerates the page update types.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
...@@ -106,27 +78,25 @@ Enumerates the touch guide event types. ...@@ -106,27 +78,25 @@ Enumerates the touch guide event types.
| Name | Description | | Name | Description |
| ---------- | ------------ | | ---------- | ------------ |
| touchBegin | A touch starts in touch guide mode.| | touchBegin | Start of touch in touch guide mode. |
| touchEnd | A touch ends in touch guide mode.| | touchEnd | End of touch in touch guide mode. |
## AccessibilityExtensionAbility.onConnect ## AccessibilityExtensionAbility.onConnect
onConnect(): void; onConnect(): void;
Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can initialize service logic. This API can be overridden as required. Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can have the service logic initialized. This API can be overridden as required.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
None
**Example** **Example**
```ts ```ts
onConnect(): void { class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
console.log("AxExtensionAbility onConnect"); onConnect() {
} console.log('AxExtensionAbility onConnect');
}
};
``` ```
## AccessibilityExtensionAbility.onDisconnect ## AccessibilityExtensionAbility.onDisconnect
...@@ -137,16 +107,14 @@ Called when the **AccessibilityExtensionAbility** is disabled and disconnected f ...@@ -137,16 +107,14 @@ Called when the **AccessibilityExtensionAbility** is disabled and disconnected f
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
None
**Example** **Example**
```ts ```ts
onDisconnect(): void { class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
console.log("AxExtensionAbility onDisconnect"); onDisconnect() {
} console.log('AxExtensionAbility onDisconnect');
}
};
``` ```
## AccessibilityExtensionAbility.onAccessibilityEvent ## AccessibilityExtensionAbility.onAccessibilityEvent
...@@ -166,19 +134,21 @@ Called when an event that matches the specified bundle and event type occurs. In ...@@ -166,19 +134,21 @@ Called when an event that matches the specified bundle and event type occurs. In
**Example** **Example**
```ts ```ts
onAccessibilityEvent(event: AccessibilityEvent): void { class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
console.log("AxExtensionAbility onAccessibilityEvent"); onAccessibilityEvent(event) {
if (event.eventType == 'click') { console.log('AxExtensionAbility onAccessibilityEvent');
console.log("AxExtensionAbility onAccessibilityEvent: click"); if (event.eventType == 'click') {
console.log('AxExtensionAbility onAccessibilityEvent: click');
}
} }
} };
``` ```
## AccessibilityExtensionAbility.onKeyEvent ## AccessibilityExtensionAbility.onKeyEvent
onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean; onKeyEvent(keyEvent: KeyEvent): boolean;
Called when a physical key is pressed. In this API, you can determine whether to intercept the key event based on the service. Called when a physical key is pressed. In this API, you can determine whether to intercept an event based on the service.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core **System capability**: SystemCapability.BarrierFree.Accessibility.Core
...@@ -191,12 +161,14 @@ Called when a physical key is pressed. In this API, you can determine whether to ...@@ -191,12 +161,14 @@ Called when a physical key is pressed. In this API, you can determine whether to
**Example** **Example**
```ts ```ts
onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean { class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
console.log("AxExtensionAbility onKeyEvent"); onKeyEvent(keyEvent) {
if (keyEvent.keyCode == 22) { console.log('AxExtensionAbility onKeyEvent');
console.log("AxExtensionAbility onKeyEvent: intercept 22"); if (keyEvent.keyCode == 22) {
return true; console.log('AxExtensionAbility onKeyEvent: intercept 22');
return true;
}
return false;
} }
return false; };
}
``` ```
# Battery Info # Battery Info
>**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.
The Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. The Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status.
> **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.
## Modules to Import ## Modules to Import
...@@ -13,67 +12,100 @@ The Battery Info module provides APIs for querying the charger type, battery hea ...@@ -13,67 +12,100 @@ The Battery Info module provides APIs for querying the charger type, battery hea
import batteryInfo from '@ohos.batteryInfo'; import batteryInfo from '@ohos.batteryInfo';
``` ```
## System Capabilities
SystemCapability.PowerManager.BatteryManager
## Attributes ## Attributes
Describes battery information. Describes battery information.
| Name | Type | Readable | Writable | Description | **System capability**: SystemCapability.PowerManager.BatteryManager.Core
| ----------------------------- | ----------------------------------------- | -------- | -------- | ------------------------------------------------------------ |
| batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. | | Name | Type | Readable| Writable| Description |
| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. | | --------------- | ------------------- | ---- | ---- | ---------------------|
| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. | | batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage. |
| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | | chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the device. |
| voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. | | healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the device. |
| technology | string | Yes | No | Battery technology of the current device. | | pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the device. |
| batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. | | voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. |
| isBatteryPresent<sup>7+</sup> | boolean | Yes | No | Whether the battery is supported or present. | | technology | string | Yes | No | Battery technology of the device. |
| batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. |
**Example** | isBatteryPresent<sup>7+</sup> | boolean | Yes | No | Whether the battery is supported or present. |
| batteryCapacityLevel<sup>9+</sup> | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. |
```js | estimatedRemainingChargeTime<sup>9+</sup> | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. |
import batteryInfo from '@ohos.batteryInfo'; | totalEnergy<sup>9+</sup> | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. |
var batterySoc = batteryInfo.batterySOC; | nowCurrent<sup>9+</sup> | number | Yes | No | Battery current of the device, in unit of mA. This is a system API. |
``` | remainingEnergy<sup>9+</sup> | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. This is a system API.|
## BatteryPluggedType ## BatteryPluggedType
Enumerates charger types. Enumerates charger types.
| Name | Default Value | Description | **System capability**: SystemCapability.PowerManager.BatteryManager.Core
| -------- | ------------- | ----------------- |
| NONE | 0 | Unknown type. |
| AC | 1 | AC charger. |
| USB | 2 | USB charger. |
| WIRELESS | 3 | Wireless charger. |
| Name | Value | Description |
| -------- | ---- | ----------------- |
| NONE | 0 | Unknown type |
| AC | 1 | AC charger|
| USB | 2 | USB charger |
| WIRELESS | 3 | Wireless charger|
## BatteryChargeState ## BatteryChargeState
Enumerates charging states. Enumerates charging states.
| Name | Default Value | Description | **System capability**: SystemCapability.PowerManager.BatteryManager.Core
| ------- | ------------- | --------------------------------- |
| NONE | 0 | Unknown state. |
| ENABLE | 1 | The battery is being charged. |
| DISABLE | 2 | The battery is not being charged. |
| FULL | 3 | The battery is fully charged. |
| Name | Value | Description |
| ------- | ---- | --------------- |
| NONE | 0 | Unknown state. |
| ENABLE | 1 | The battery is being charged. |
| DISABLE | 2 | The battery is not being charged. |
| FULL | 3 | The battery is fully charged.|
## BatteryHealthState ## BatteryHealthState
Enumerates battery health states. Enumerates battery health states.
| Name | Default Value | Description | **System capability**: SystemCapability.PowerManager.BatteryManager.Core
| ----------- | ------------- | ------------------------------------ |
| UNKNOWN | 0 | Unknown state. | | Name | Value | Description |
| GOOD | 1 | The battery is in the healthy state. | | ----------- | ---- | -------------- |
| OVERHEAT | 2 | The battery is overheated. | | UNKNOWN | 0 | Unknown state. |
| OVERVOLTAGE | 3 | The battery voltage is over high. | | GOOD | 1 | The battery is in the healthy state. |
| COLD | 4 | The battery temperature is low. | | OVERHEAT | 2 | The battery is overheated. |
| DEAD | 5 | The battery is dead. | | OVERVOLTAGE | 3 | The battery voltage is over high. |
| COLD | 4 | The battery temperature is low. |
| DEAD | 5 | The battery is dead.|
## BatteryCapacityLevel<sup>9+</sup>
Enumerates battery levels.
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| Name | Value| Description |
| -------------- | ------ | ---------------------------- |
| LEVEL_NONE | 0 | Unknown battery level. |
| LEVEL_FULL | 1 | Full battery level. |
| LEVEL_HIGH | 2 | High battery level. |
| LEVEL_NORMAL | 3 | Normal battery level.|
| LEVEL_LOW | 4 | Low battery level. |
| LEVEL_CRITICAL | 5 | Ultra-low battery level.|
## CommonEventBatteryChangedCode<sup>9+</sup>
Enumerates keys for querying the additional information about the **COMMON_EVENT_BATTERY_CHANGED** event.
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| Name | Value| Description |
| -------------------- | ------ | -------------------------------------------------- |
| EXTRA_SOC | 0 | Remaining battery level in percentage. |
| EXTRA_VOLTAGE | 1 | Battery voltage of the device. |
| EXTRA_TEMPERATURE | 2 | Battery temperature of the device. |
| EXTRA_HEALTH_STATE | 3 | Battery health status of the device. |
| EXTRA_PLUGGED_TYPE | 4 | Type of the charger connected to the device. |
| EXTRA_MAX_CURRENT | 5 | Maximum battery current of the device. |
| EXTRA_MAX_VOLTAGE | 6 | Maximum battery voltage of the device. |
| EXTRA_CHARGE_STATE | 7 | Battery charging status of the device. |
| EXTRA_CHARGE_COUNTER | 8 | Number of battery charging times of the device. |
| EXTRA_PRESENT | 9 | Whether the battery is supported by the device or installed.|
| EXTRA_TECHNOLOGY | 10 | Battery technology of the device. |
# Battery Statistics
This module provides APIs for querying software and hardware power consumption statistics.
> **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.
>
> - The APIs provided by this module are system APIs.
## Modules to Import
```js
import batteryStats from '@ohos.batteryStatistics';
```
## batteryStats.getBatteryStats
getBatteryStats(): Promise<Array&lt;BatteryStatsInfo&gt;>
Obtains the power consumption information list, using a promise to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.BatteryStatistics
**Return value**
| Type | Description |
| ----------------------------------------------------- | ------------------------------- |
| Promise<Array<[BatteryStatsInfo](#batterystatsinfo)>> | Promise used to return the power consumption information list.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
```js
batteryStats.getBatteryStats()
.then(data => {
console.info('battery statistics info: ' + data);
})
.catch(err => {
console.error('get battery statisitics failed, err: ' + err);
});
```
## batteryStats.getBatteryStats
getBatteryStats(callback: AsyncCallback<Array&lt;BatteryStatsInfo&gt;>): void
Obtains the power consumption information list. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.BatteryStatistics
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<Array<[BatteryStatsInfo](#batterystatsinfo)>> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained. If the operation failed, **err** is an error object.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
```js
batteryStats.getBatteryStats((err, data) => {
if (typeof err === 'undefined') {
console.info('battery statistics info: ' + data);
} else {
console.error('get battery statisitics failed, err: ' + err);
}
});
```
## batteryStats.getAppPowerValue
getAppPowerValue(uid: number): number
Obtains the power consumption of an application.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.BatteryStatistics
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ----------- |
| uid | number | Yes | Application UID.|
**Return value**
| Type | Description |
| ------ | --------------------------------- |
| number | Power consumption of the application with this UID, in unit of mAh.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var value = batteryStats.getAppPowerValue(10021);
console.info('battery statistics value of app is: ' + value);
} catch(err) {
console.error('get battery statisitics value of app failed, err: ' + err);
}
```
## batteryStats.getAppPowerPercent
getAppPowerPercent(uid: number): number
Obtains the proportion of the power consumption of an application.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.BatteryStatistics
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ----------- |
| uid | number | Yes | Application UID.|
**Return value**
| Type | Description |
| ------ | ------------------------- |
| number | Proportion of the power consumption of an application with this UID.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var percent = batteryStats.getAppPowerPercent(10021);
console.info('battery statistics percent of app is: ' + percent);
} catch(err) {
console.error('get battery statisitics percent of app failed, err: ' + err);
}
```
## batteryStats.getHardwareUnitPowerValue
getHardwareUnitPowerValue(type: ConsumptionType): number
Obtains the power consumption of a hardware unit according to the consumption type.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.BatteryStatistics
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | -------------- |
| type | [ConsumptionType](#consumptiontype) | Yes | Power consumption type.|
**Return value**
| Type | Description |
| ------ | ------------------------------------------ |
| number | Power consumption of the hardware unit corresponding to the power consumption type, in unit of mAh.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent);
} catch(err) {
console.error('get battery statisitics percent of hardware failed, err: ' + err);
}
```
## batteryStats.getHardwareUnitPowerPercent
getHardwareUnitPowerPercent(type: ConsumptionType): number
Obtains the proportion of the power consumption of a hardware unit according to the power consumption type.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.BatteryStatistics
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ----------------------------------- | ---- | -------------- |
| type | [ConsumptionType](#consumptiontype) | Yes | Power consumption type.|
**Return value**
| Type | Description |
| ------ | ---------------------------------- |
| number | Proportion of the power consumption of the hardware unit corresponding to the power consumption type.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md).
| Code| Error Message |
| -------- | -------------- |
| 4600101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN);
console.info('battery statistics percent of hardware is: ' + percent);
} catch(err) {
console.error('get battery statisitics percent of hardware failed, err: ' + err);
}
```
## BatteryStatsInfo
Describes the device power consumption information.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.BatteryStatistics
### Attributes
| Name | Type | Readable| Writable| Description |
| ----- | ----------------------------------- | ---- | ---- | ---------------------- |
| uid | number | Yes | No | UID related to power consumption information. |
| type | [ConsumptionType](#consumptiontype) | Yes | No | Power consumption type. |
| power | number | Yes | No | Power consumption, in unit of mAh.|
## ConsumptionType
Enumerates power consumption types.
**System API**: This is a system API.
**System capability**: SystemCapability.PowerManager.BatteryStatistics
| Name | Value | Description |
| -------------------------- | ---- | ----------------------------- |
| CONSUMPTION_TYPE_INVALID | -17 | Unknown type. |
| CONSUMPTION_TYPE_APP | -16 | Power consumption of an application. |
| CONSUMPTION_TYPE_BLUETOOTH | -15 | Power consumption of Bluetooth. |
| CONSUMPTION_TYPE_IDLE | -14 | Power consumption when the CPU is idle.|
| CONSUMPTION_TYPE_PHONE | -13 | Power consumption of a phone call. |
| CONSUMPTION_TYPE_RADIO | -12 | Power consumption of wireless communication. |
| CONSUMPTION_TYPE_SCREEN | -11 | Power consumption of the screen. |
| CONSUMPTION_TYPE_USER | -10 | Power consumption of the user. |
| CONSUMPTION_TYPE_WIFI | -9 | Power consumption of Wi-Fi. |
# Brightness # Screen Brightness
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> 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.
The Brightness module provides an API for setting the screen brightness. The Brightness module provides an API for setting the screen brightness.
> **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.
>
> - The APIs provided by this module are system APIs.
## Modules to Import ## Modules to Import
...@@ -18,18 +20,30 @@ setValue(value: number): void ...@@ -18,18 +20,30 @@ setValue(value: number): void
Sets the screen brightness. Sets the screen brightness.
This is a system API and cannot be called by third-party applications. **System API**: This is a system API.
**System capability:** SystemCapability.PowerManager.DisplayPowerManager **System capability**: SystemCapability.PowerManager.DisplayPowerManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type | Mandatory| Description |
| ----- | ------ | ---- | ----------- | | ------ | ------ | ---- | ----------------------- |
| value | number | Yes | Brightness value, ranging from **0** to **255**.| | value | number | Yes | Brightness value. The value ranges from 0 to 255.|
**Error codes**
For details about the error codes, see [Screen Brightness Error Codes](../errorcodes/errorcode-brightness.md).
| Code | Error Message |
|---------|---------|
| 4700101 | Operation failed. Cannot connect to service.|
**Example** **Example**
```js ```js
brightness.setValue(128); try {
brightness.setValue(128);
} catch(err) {
console.error('set brightness failed, err: ' + err);
}
``` ```
# XML-to-JavaScript Conversion # @ohos.convertxml (XML-to-JavaScript Conversion)
The **convertxml** module provides APIs for converting XML text into JavaScript objects. The **convertxml** module provides APIs for converting XML text into JavaScript objects.
...@@ -36,6 +36,14 @@ Converts an XML text into a JavaScript object. ...@@ -36,6 +36,14 @@ Converts an XML text into a JavaScript object.
| ------ | ---------------------------- | | ------ | ---------------------------- |
| Object | JavaScript object.| | Object | JavaScript object.|
**Error codes**
For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
| 10200002 | Invalid xml string. |
**Example** **Example**
```js ```js
...@@ -46,13 +54,13 @@ let xml = ...@@ -46,13 +54,13 @@ let xml =
' <todo>Work</todo>' + ' <todo>Work</todo>' +
' <todo>Play</todo>' + ' <todo>Play</todo>' +
'</note>'; '</note>';
let conv = new convertxml.convertToJSObject(); let conv = new convertxml.ConvertXML()
let options = {trim : false, declarationKey:"_declaration", let options = {trim : false, declarationKey:"_declaration",
instructionKey : "_instruction", attributesKey : "_attributes", instructionKey : "_instruction", attributesKey : "_attributes",
textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype",
commentKey : "_comment", parentKey : "_parent", typeKey : "_type", commentKey : "_comment", parentKey : "_parent", typeKey : "_type",
nameKey : "_name", elementsKey : "_elements"} nameKey : "_name", elementsKey : "_elements"}
let result = JSON.stringify(conv.convert(xml, options)); let result = JSON.stringify(conv.convertToJSObject(xml, options));
console.log(result); console.log(result);
// Output (non-compact) // Output (non-compact)
// {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]} // {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]}
...@@ -60,14 +68,14 @@ console.log(result); ...@@ -60,14 +68,14 @@ console.log(result);
### convert<sup>(deprecated)</sup> ### convert<sup>(deprecated)</sup>
> **NOTE**
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [convertToJSObject9+](#converttojsobject9) instead.
convert(xml: string, options?: ConvertOptions) : Object convert(xml: string, options?: ConvertOptions) : Object
Converts an XML text into a JavaScript object. Converts an XML text into a JavaScript object.
> **NOTE**
>
> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [convertToJSObject<sup>9+</sup>](#converttojsobject9) instead.
**System capability**: SystemCapability.Utils.Lang **System capability**: SystemCapability.Utils.Lang
**Parameters** **Parameters**
......
...@@ -112,6 +112,8 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode ...@@ -112,6 +112,8 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
**Example** **Example**
```js ```js
let sinkDeviceDescriptor = "descriptor";
let srcInputDeviceId = 0;
try { try {
inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (error) => { inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (error) => {
if (error) { if (error) {
...@@ -160,6 +162,8 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode ...@@ -160,6 +162,8 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
**Example** **Example**
```js ```js
let sinkDeviceDescriptor = "descriptor";
let srcInputDeviceId = 0;
try { try {
inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then(() => { inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then(() => {
console.log(`Start Keyboard mouse crossing success.`); console.log(`Start Keyboard mouse crossing success.`);
...@@ -249,6 +253,7 @@ Checks whether screen hopping is enabled. This API uses an asynchronous callback ...@@ -249,6 +253,7 @@ Checks whether screen hopping is enabled. This API uses an asynchronous callback
**Example** **Example**
```js ```js
let deviceDescriptor = "descriptor";
try { try {
inputDeviceCooperate.getState(deviceDescriptor, (error, data) => { inputDeviceCooperate.getState(deviceDescriptor, (error, data) => {
if (error) { if (error) {
...@@ -324,7 +329,7 @@ try { ...@@ -324,7 +329,7 @@ try {
inputDeviceCooperate.on('cooperation', (data) => { inputDeviceCooperate.on('cooperation', (data) => {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`); console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`);
}); });
} catch (err) { } catch (error) {
console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
...@@ -342,7 +347,7 @@ Disables listening for screen hopping events. ...@@ -342,7 +347,7 @@ Disables listening for screen hopping events.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- | | -------- | ---------------------------- | ---- | ---------------------------- |
| type | string | Yes | Event type. The value is **cooperation**. | | type | string | Yes | Event type. The value is **cooperation**. |
| callback | AsyncCallback<void> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.| | callback | AsyncCallback\<void> | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.|
...@@ -350,25 +355,25 @@ Disables listening for screen hopping events. ...@@ -350,25 +355,25 @@ Disables listening for screen hopping events.
```js ```js
// Unregister a single callback. // Unregister a single callback.
callback: function(event) { function callback(event) {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`);
return false; return false;
} }
try { try {
inputDeviceCooperate.on('cooperation', this.callback); inputDeviceCooperate.on('cooperation', callback);
inputDeviceCooperate.off("cooperation", this.callback); inputDeviceCooperate.off("cooperation", callback);
} catch (error) { } catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
```js ```js
// Unregister all callbacks. // Unregister all callbacks.
callback: function(event) { function callback(event) {
console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`);
return false; return false;
} }
try { try {
inputDeviceCooperate.on('cooperation', this.callback); inputDeviceCooperate.on('cooperation', callback);
inputDeviceCooperate.off("cooperation"); inputDeviceCooperate.off("cooperation");
} catch (error) { } catch (error) {
console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
......
...@@ -333,7 +333,7 @@ inputDevice.getDevice(1).then((inputDevice)=>{ ...@@ -333,7 +333,7 @@ inputDevice.getDevice(1).then((inputDevice)=>{
## inputDevice.supportKeys<sup>9+</sup> ## inputDevice.supportKeys<sup>9+</sup>
supportKeys(deviceId: number, keys: Array&lt;KeyCode&gt;, callback: Callback&lt;Array&lt;boolean&gt;&gt;): void supportKeys(deviceId: number, keys: Array&lt;KeyCode&gt;, callback: AsyncCallback &lt;Array&lt;boolean&gt;&gt;): void
Obtains the key codes supported by the input device. This API uses an asynchronous callback to return the result. Obtains the key codes supported by the input device. This API uses an asynchronous callback to return the result.
...@@ -345,7 +345,7 @@ Obtains the key codes supported by the input device. This API uses an asynchrono ...@@ -345,7 +345,7 @@ Obtains the key codes supported by the input device. This API uses an asynchrono
| -------- | ------------------------------------ | ---- | --------------------------------- | | -------- | ------------------------------------ | ---- | --------------------------------- |
| deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| | deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
| keys | Array&lt;KeyCode&gt; | Yes | Key codes to be queried. A maximum of five key codes can be specified. | | keys | Array&lt;KeyCode&gt; | Yes | Key codes to be queried. A maximum of five key codes can be specified. |
| callback | Callback&lt;Array&lt;boolean&gt;&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;Array&lt;boolean&gt;&gt; | Yes | Callback used to return the result. |
**Example** **Example**
......
# MediaLibrary # @ohos.multimedia.medialibrary (Media Library Management)
> **NOTE** > **NOTE**
>
> The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. > The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -193,7 +192,7 @@ media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) { ...@@ -193,7 +192,7 @@ media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) {
### on<sup>8+</sup> ### on<sup>8+</sup>
on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback&lt;void&gt;): void on(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback: Callback&lt;void&gt;): void
Subscribes to the media library changes. This API uses an asynchronous callback to return the result. Subscribes to the media library changes. This API uses an asynchronous callback to return the result.
...@@ -215,7 +214,7 @@ media.on('imageChange', () => { ...@@ -215,7 +214,7 @@ media.on('imageChange', () => {
``` ```
### off<sup>8+</sup> ### off<sup>8+</sup>
off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback&lt;void&gt;): void off(type: 'deviceChange'&#124;'albumChange'&#124;'imageChange'&#124;'audioChange'&#124;'videoChange'&#124;'fileChange'&#124;'remoteFileChange', callback?: Callback&lt;void&gt;): void
Unsubscribes from the media library changes. This API uses an asynchronous callback to return the result. Unsubscribes from the media library changes. This API uses an asynchronous callback to return the result.
...@@ -885,7 +884,7 @@ Obtains information about online peer devices. This API uses a promise to return ...@@ -885,7 +884,7 @@ Obtains information about online peer devices. This API uses a promise to return
| Type | Description | | Type | Description |
| ------------------- | -------------------- | | ------------------- | -------------------- |
| Promise\<Array\<PeerInfo>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.| | Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
**Example** **Example**
...@@ -921,7 +920,7 @@ Obtains information about online peer devices. This API uses an asynchronous cal ...@@ -921,7 +920,7 @@ Obtains information about online peer devices. This API uses an asynchronous cal
| Type | Description | | Type | Description |
| ------------------- | -------------------- | | ------------------- | -------------------- |
| callback: AsyncCallback\<Array\<PeerInfo>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.| | callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.|
**Example** **Example**
...@@ -956,7 +955,7 @@ Obtains information about all peer devices. This API uses a promise to return th ...@@ -956,7 +955,7 @@ Obtains information about all peer devices. This API uses a promise to return th
| Type | Description | | Type | Description |
| ------------------- | -------------------- | | ------------------- | -------------------- |
| Promise\<Array\<PeerInfo>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.| | Promise\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
**Example** **Example**
...@@ -992,7 +991,7 @@ Obtains information about online peer devices. This API uses an asynchronous cal ...@@ -992,7 +991,7 @@ Obtains information about online peer devices. This API uses an asynchronous cal
| Type | Description | | Type | Description |
| ------------------- | -------------------- | | ------------------- | -------------------- |
| callback: AsyncCallback\<Array\<PeerInfo>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.| | callback: AsyncCallback\<Array\<[PeerInfo](#peerinfo8)>> | Promise used to return all peer devices, in an array of **PeerInfo** objects.|
**Example** **Example**
...@@ -1014,6 +1013,11 @@ async function example() { ...@@ -1014,6 +1013,11 @@ async function example() {
Provides APIs for encapsulating file asset attributes. Provides APIs for encapsulating file asset attributes.
> **NOTE**
>
> 1. The system attempts to parse the file content if the file is an audio or video file. The actual field values will be restored from the passed values during scanning on some devices.
> 2. Some devices may not support the modification of **orientation**. You are advised to use [ModifyImageProperty](js-apis-image.md#modifyimageproperty9) of the **image** module.
### Attributes ### Attributes
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -1025,7 +1029,7 @@ Provides APIs for encapsulating file asset attributes. ...@@ -1025,7 +1029,7 @@ Provides APIs for encapsulating file asset attributes.
| mimeType | string | Yes | No | Extended file attributes. | | mimeType | string | Yes | No | Extended file attributes. |
| mediaType<sup>8+</sup> | [MediaType](#mediatype8) | Yes | No | Media type. | | mediaType<sup>8+</sup> | [MediaType](#mediatype8) | Yes | No | Media type. |
| displayName | string | Yes | Yes | Display file name, including the file name extension. | | displayName | string | Yes | Yes | Display file name, including the file name extension. |
| title | string | Yes | Yes | Title in the file. | | title | string | Yes | Yes | Title in the file. By default, it carries the file name without extension. |
| relativePath<sup>8+</sup> | string | Yes | Yes | Relative public directory of the file. | | relativePath<sup>8+</sup> | string | Yes | Yes | Relative public directory of the file. |
| parent<sup>8+</sup> | number | Yes | No | Parent directory ID. | | parent<sup>8+</sup> | number | Yes | No | Parent directory ID. |
| size | number | Yes | No | File size, in bytes. | | size | number | Yes | No | File size, in bytes. |
...@@ -2486,29 +2490,33 @@ Enumerates media types. ...@@ -2486,29 +2490,33 @@ Enumerates media types.
Enumerates key file information. Enumerates key file information.
> **NOTE**
>
> The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
| Name | Value | Description | | Name | Value | Description |
| ------------- | ------------------- | ---------------------------------------------------------- | | ------------- | ------------------- | ---------------------------------------------------------- |
| ID | file_id | File ID. | | ID | "file_id" | File ID. |
| RELATIVE_PATH | relative_path | Relative public directory of the file. | | RELATIVE_PATH | "relative_path" | Relative public directory of the file. |
| DISPLAY_NAME | display_name | Display file name. | | DISPLAY_NAME | "display_name" | Display file name. |
| PARENT | parent | Parent directory ID. | | PARENT | "parent" | Parent directory ID. |
| MIME_TYPE | mime_type | Extended file attributes. | | MIME_TYPE | "mime_type" | Extended file attributes. |
| MEDIA_TYPE | media_type | Media type. | | MEDIA_TYPE | "media_type" | Media type. |
| SIZE | size | File size, in bytes. | | SIZE | "size" | File size, in bytes. |
| DATE_ADDED | date_added | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | | DATE_ADDED | "date_added" | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) |
| DATE_MODIFIED | date_modified | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | | DATE_MODIFIED | "date_modified" | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) |
| DATE_TAKEN | date_taken | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | | DATE_TAKEN | "date_taken" | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) |
| TITLE | title | Title in the file. | | TITLE | "title" | Title in the file. |
| ARTIST | artist | Artist of the file. | | ARTIST | "artist" | Artist of the file. |
| AUDIOALBUM | audio_album | Audio album. | | AUDIOALBUM | "audio_album" | Audio album. |
| DURATION | duration | Duration, in ms. | | DURATION | "duration" | Duration, in ms. |
| WIDTH | width | Image width, in pixels. | | WIDTH | "width" | Image width, in pixels. |
| HEIGHT | height | Image height, in pixels. | | HEIGHT | "height" | Image height, in pixels. |
| ORIENTATION | orientation | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| | ORIENTATION | "orientation" | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).|
| ALBUM_ID | bucket_id | ID of the album to which the file belongs. | | ALBUM_ID | "bucket_id" | ID of the album to which the file belongs. |
| ALBUM_NAME | bucket_display_name | Name of the album to which the file belongs. | | ALBUM_NAME | "bucket_display_name" | Name of the album to which the file belongs. |
## DirectoryType<sup>8+</sup> ## DirectoryType<sup>8+</sup>
...@@ -2573,8 +2581,6 @@ Describes the image size. ...@@ -2573,8 +2581,6 @@ Describes the image size.
Implements the media asset option. Implements the media asset option.
> **NOTE**
>
> This API is deprecated since API version 9. > This API is deprecated since API version 9.
**System capability**: SystemCapability.Multimedia.MediaLibrary.Core **System capability**: SystemCapability.Multimedia.MediaLibrary.Core
...@@ -2598,5 +2604,5 @@ Describes media selection option. ...@@ -2598,5 +2604,5 @@ Describes media selection option.
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| ----- | ------ | ---- | ---- | -------------------- | | ----- | ------ | ---- | ---- | -------------------- |
| type | string | Yes | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.| | type | 'image' &#124; 'video' &#124; 'media' | Yes | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.|
| count | number | Yes | Yes | Number of media assets selected. The value starts from 1, which indicates that one media asset can be selected. | | count | number | Yes | Yes | Number of media assets selected. The value starts from 1, which indicates that one media asset can be selected. |
# Power Manager # Power Manager
> ![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.
The Power Manager module provides APIs for rebooting and shutting down the system, as well as querying the screen status. The Power Manager module provides APIs for rebooting and shutting down the system, as well as querying the screen status.
> **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 ## Modules to Import
...@@ -12,42 +11,294 @@ The Power Manager module provides APIs for rebooting and shutting down the syste ...@@ -12,42 +11,294 @@ The Power Manager module provides APIs for rebooting and shutting down the syste
import power from '@ohos.power'; import power from '@ohos.power';
``` ```
## System Capability ## power.shutdown
SystemCapability.PowerManager.PowerManager.Core
## power.shutdownDevice shutdown(reason: string): void
shutdownDevice(reason: string): void
Shuts down the system. Shuts down the system.
This is a system API and cannot be called by third-party applications. **System API**: This is a system API.
**Required permission**: ohos.permission.REBOOT **Required permission**: ohos.permission.REBOOT
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ----- | | ------ | ------ | ---- | ----- |
| reason | string | Yes | Reason for system shutdown.| | reason | string | Yes | Reason for system shutdown.|
**Error codes**
For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md).
| Code | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
**Example** **Example**
```js ```js
power.shutdownDevice("shutdown_test"); try {
console.info('power_shutdown_device_test success') power.shutdown('shutdown_test');
} catch(err) {
console.error('shutdown failed, err: ' + err);
}
``` ```
## power.reboot<sup>9+</sup>
reboot(reason: string): void
Reboots the system.
**System API**: This is a system API.
**Required permission**: ohos.permission.REBOOT
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------- |
| reason | string | Yes | Reason for system reboot.|
**Error codes**
For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md).
| Code | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
power.reboot('reboot_test');
} catch(err) {
console.error('reboot failed, err: ' + err);
}
```
## power.isActive<sup>9+</sup>
isActive(): boolean
Checks whether the current device is active.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Error codes**
For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md).
| Code | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var isActive = power.isActive();
console.info('power is active: ' + isActive);
} catch(err) {
console.error('check active status failed, err: ' + err);
}
```
## power.wakeup<sup>9+</sup>
wakeup(detail: string): void
Wakes up a device.
**System API**: This is a system API.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------- |
| detail | string | Yes | Reason for wakeup.|
**Error codes**
For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md).
| Code | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
power.wakeup('wakeup_test');
} catch(err) {
console.error('wakeup failed, err: ' + err);
}
```
## power.suspend<sup>9+</sup>
suspend(): void
Hibernates a device.
**System API**: This is a system API.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Error codes**
For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md).
| Code | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
power.suspend();
} catch(err) {
console.error('suspend failed, err: ' + err);
}
```
## power.rebootDevice ## power.getPowerMode<sup>9+</sup>
getPowerMode(): DevicePowerMode
Obtains the power mode of this device.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Return value**
| Type | Description |
| ------------------------------------ | ---------- |
| [DevicePowerMode](#devicepowermode9) | Power mode.|
**Error codes**
For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md).
| Code | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var mode = power.getPowerMode();
console.info('power mode: ' + mode);
} catch(err) {
console.error('get power mode failed, err: ' + err);
}
```
## power.setPowerMode<sup>9+</sup>
setPowerMode(mode: DevicePowerMode, callback: AsyncCallback&lt;void&gt;): void
Sets the power mode of this device. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.POWER_OPTIMIZATION
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ |
| mode | [DevicePowerMode](#devicepowermode9) | Yes | Power mode. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the power mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md).
| Code | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
**Example**
```js
power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE, err => {
if (typeof err === 'undefined') {
console.info('set power mode to MODE_PERFORMANCE');
} else {
console.error('set power mode failed, err: ' + err);
}
});
```
## power.setPowerMode<sup>9+</sup>
setPowerMode(mode: DevicePowerMode): Promise&lt;void&gt;
Sets the power mode of this device. This API uses a promise to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.POWER_OPTIMIZATION
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------ | ---- | ---------- |
| mode | [DevicePowerMode](#devicepowermode9) | Yes | Power mode.|
**Return value**
| Type | Description |
| ------------------- | -------------------------------------- |
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md).
| Code | Error Message |
|---------|---------|
| 4900101 | Operation failed. Cannot connect to service.|
**Example**
```js
power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE)
.then(() => {
console.info('set power mode to MODE_PERFORMANCE');
})
.catch(err => {
console.error('set power mode failed, err: ' + err);
});
```
## power.rebootDevice<sup>(deprecated)</sup>
rebootDevice(reason: string): void rebootDevice(reason: string): void
> This API is deprecated since API version 9. You are advised to use [power.reboot](#powerreboot9) instead.
Reboots the system. Reboots the system.
**Required permission**: ohos.permission.REBOOT (to reboot) or ohos.permission.REBOOT_RECOVERY (to reboot and enter the recovery or updater mode) **Required permission**: ohos.permission.REBOOT
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Parameters** **Parameters**
...@@ -58,55 +309,73 @@ Reboots the system. ...@@ -58,55 +309,73 @@ Reboots the system.
**Example** **Example**
```js ```js
power.rebootDevice("reboot_test"); power.rebootDevice('reboot_test');
console.info('power_reboot_device_test success')
``` ```
## power.isScreenOn<sup>(deprecated)</sup>
## power.isScreenOn
isScreenOn(callback: AsyncCallback&lt;boolean&gt;): void isScreenOn(callback: AsyncCallback&lt;boolean&gt;): void
Checks the screen status of the current device. > This API is deprecated since API version 9. You are advised to use [power.isActive](#powerisactive9) instead.
Checks the screen status of the current device. This API uses an asynchronous callback to return the result.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ---------------------------------------- | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to obtain the return value.<br>Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the screen status obtained, where the value **true** indicates on and the value **false** indicates the opposite. Otherwise, **err** is an error object.|
**Example** **Example**
```js ```js
power.isScreenOn((error, screenOn) => { power.isScreenOn((err, data) => {
if (typeof error === "undefined") { if (typeof err === 'undefined') {
console.info('screenOn status is ' + screenOn); console.info('screen on status is ' + data);
} else { } else {
console.log('error: ' + error); console.error('check screen status failed, err: ' + err);
} }
}) })
``` ```
## power.isScreenOn<sup>(deprecated)</sup>
## power.isScreenOn
isScreenOn(): Promise&lt;boolean&gt; isScreenOn(): Promise&lt;boolean&gt;
Checks the screen status of the current device. > This API is deprecated since API version 9. You are advised to use [power.isActive](#powerisactive9) instead.
Checks the screen status of the current device. This API uses a promise to return the result.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
**Return value** **Return value**
| Type | Description | | Type | Description |
| ---------------------- | --------------------------------------- | | ---------------------- | -------------------------------------------------- |
| Promise&lt;boolean&gt; | Promise used to obtain the return value. <br/>Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| | Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that the screen is on, and the value **false** indicates the opposite.|
**Example** **Example**
```js ```js
power.isScreenOn() power.isScreenOn()
.then(screenOn => { .then(data => {
console.info('screenOn status is ' + screenOn); console.info('screen on status is ' + data);
}) })
.catch(error => { .catch(err => {
console.log('error: ' + error); console.error('check screen status failed, err: ' + err);
}) })
``` ```
## DevicePowerMode<sup>9+</sup>
Enumerates power modes.
**System capability:** SystemCapability.PowerManager.PowerManager.Core
| Name | Value | Description |
| ----------------------- | ---- | ---------------------- |
| MODE_NORMAL | 600 | Standard mode. It is the default value.|
| MODE_POWER_SAVE | 601 | Power saving mode. |
| MODE_PERFORMANCE | 602 | Performance mode. |
| MODE_EXTREME_POWER_SAVE | 603 | Ultra power saving mode. |
...@@ -2,10 +2,9 @@ ...@@ -2,10 +2,9 @@
The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data. The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data.
> **NOTE**<br/> > **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. > 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.
> - API version 9 is a canary version for trial use. The APIs of this version may be unstable.
## Modules to Import ## Modules to Import
......
# Battery Level # Battery Info
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** This module allows you to query the charging status and remaining power of a device.
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead.
> > **NOTE**
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead.
> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -16,40 +17,46 @@ import battery from '@system.battery'; ...@@ -16,40 +17,46 @@ import battery from '@system.battery';
## battery.getStatus ## battery.getStatus
getStatus(Object): void getStatus(options?: GetStatusOptions): void;
Obtains the current charging state and battery level. Obtains the current charging state and battery level.
**System capability**: SystemCapability.PowerManager.BatteryManager.Core **System capability**: SystemCapability.PowerManager.BatteryManager.Core
**Parameter** **Parameters**
| Name | Type | Mandatory | Description | | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;check&nbsp;result&nbsp;is&nbsp;obtained | | options | [GetStatusOptions](#getstatusoptions) | No| Object that contains the API calling result.|
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;check&nbsp;result&nbsp;fails&nbsp;to&nbsp;be&nbsp;obtained |
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete |
The following value will be returned when the check result is obtained.
| Name | Type | Description |
| -------- | -------- | -------- |
| charging | boolean | Whether&nbsp;the&nbsp;battery&nbsp;is&nbsp;being&nbsp;charged |
| level | number | Current&nbsp;battery&nbsp;level,&nbsp;which&nbsp;ranges&nbsp;from&nbsp;0.00&nbsp;to&nbsp;1.00. |
**Example** **Example**
```js ```js
export default { battery.getStatus({
getStatus() { success: function(data) {
battery.getStatus({ console.log('success get battery level:' + data.level);
success: function(data) { },
console.log('success get battery level:' + data.level); fail: function(data, code) {
}, console.error('fail to get battery level code:' + code + ', data: ' + data);
fail: function(data, code) { }
console.log('fail to get battery level code:' + code + ', data: ' + data); });
}, ```
});
}, ## GetStatusOptions
}
``` Object that contains the API calling result.
\ No newline at end of file
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ |
| success | (data: [BatteryResponse](#batteryresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BatteryResponse](#batteryresponse) type.|
| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when API call is complete. |
## BatteryResponse
Defines a response that returns the charging status and remaining power of the device.
| Name| Type| Description|
| -------- | -------- | -------- |
| charging | boolean | Whether the battery is being charged.|
| level | number | Current battery level, which ranges from **0.00** to **1.00**.|
# Thermal Manager # Thermal Manager
> **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.
This module provides thermal level-related callback and query APIs to obtain the information required for thermal control. This module provides thermal level-related callback and query APIs to obtain the information required for thermal control.
> **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 ## Modules to Import
...@@ -13,78 +11,168 @@ This module provides thermal level-related callback and query APIs to obtain the ...@@ -13,78 +11,168 @@ This module provides thermal level-related callback and query APIs to obtain the
import thermal from '@ohos.thermal'; import thermal from '@ohos.thermal';
``` ```
## thermal.registerThermalLevelCallback<sup>9+</sup>
## ThermalLevel registerThermalLevelCallback(callback: Callback&lt;ThermalLevel&gt;): void
Represents the thermal level. Subscribes to thermal level changes.
**System capability:** SystemCapability.PowerManager.ThermalManager **System capability:** SystemCapability.PowerManager.ThermalManager
| Name | Default Value | Description | **Parameters**
| ---------- | ---- | ---------------------------------------- |
| COOL | 0 | The device is cool, and services are not restricted.| | Name | Type | Mandatory| Description |
| NORMAL | 1 | The device is operational but is not cool. You need to pay attention to its heating.| | -------- | ---------------------------- | ---- | ------------------------------ |
| WARM | 2 | The device is warm. You need to stop or delay some imperceptible services.| | callback | Callback&lt;ThermalLevel&gt; | Yes | Callback used to return the result.|
| HOT | 3 | The device is heating up. You need to stop all imperceptible services and downgrade or reduce the load of other services.|
| OVERHEATED | 4 | The device is overheated. You need to stop all imperceptible services and downgrade or reduce the load of major services.| **Error codes**
| WARNING | 5 | The device is overheated and is about to enter the emergency state. You need to stop all imperceptible services and downgrade major services to the maximum extent.|
| EMERGENCY | 6 | The device has entered the emergency state. You need to stop all services except those for the emergency help purposes.| For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md).
| Code | Error Message |
|---------|---------|
| 4800101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
thermal.registerThermalLevelCallback(level => {
console.info('thermal level is: ' + level);
});
console.info('register thermal level callback success.');
} catch(err) {
console.error('register thermal level callback failed, err: ' + err);
}
```
## thermal.unregisterThermalLevelCallback<sup>9+</sup>
unregisterThermalLevelCallback(callback?: Callback\<void>): void
Unsubscribes from thermal level changes.
**System capability:** SystemCapability.PowerManager.ThermalManager
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------- | ---- | ---------------------------------------------- |
| callback | Callback&lt;void&gt; | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md).
| Code | Error Message |
|---------|---------|
| 4800101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
thermal.unregisterThermalLevelCallback(() => {
console.info('unsubscribe thermal level success.');
});
console.info('unregister thermal level callback success.');
} catch(err) {
console.error('unregister thermal level callback failed, err: ' + err);
}
```
## thermal.getLevel<sup>9+</sup>
getLevel(): ThermalLevel
Obtains the current thermal level.
**System capability:** SystemCapability.PowerManager.ThermalManager
**Return value**
## thermal.subscribeThermalLevel | Type | Description |
| ------------ | ------------ |
| ThermalLevel | Thermal level obtained.|
**Error codes**
For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md).
| Code | Error Message |
|---------|---------|
| 4800101 | Operation failed. Cannot connect to service.|
**Example**
```js
try {
var level = thermal.getLevel();
console.info('thermal level is: ' + level);
} catch(err) {
console.error('get thermal level failed, err: ' + err);
}
```
## thermal.subscribeThermalLevel<sup>(deprecated)</sup>
subscribeThermalLevel(callback: AsyncCallback&lt;ThermalLevel&gt;): void subscribeThermalLevel(callback: AsyncCallback&lt;ThermalLevel&gt;): void
> This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9) instead.
Subscribes to thermal level changes. Subscribes to thermal level changes.
**System capability:** SystemCapability.PowerManager.ThermalManager **System capability:** SystemCapability.PowerManager.ThermalManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------- | ---- | ---------------------------------------- | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback&lt;ThermalLevel&gt; | Yes | Callback used to obtain the return value.<br>The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.| | callback | AsyncCallback&lt;ThermalLevel&gt; | Yes | Callback used to return the result. The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.|
**Example** **Example**
```js ```js
var lev = 0; thermal.subscribeThermalLevel((level) => {
thermal.subscribeThermalLevel((lev) => { console.info('thermal level is: ' + level);
console.info("Thermal level is: " + lev); });
})
``` ```
## thermal.unsubscribeThermalLevel ## thermal.unsubscribeThermalLevel<sup>(deprecated)</sup>
unsubscribeThermalLevel(callback?: AsyncCallback\<void>): void unsubscribeThermalLevel(callback?: AsyncCallback\<void>): void
> This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9) instead.
Unsubscribes from thermal level changes. Unsubscribes from thermal level changes.
**System capability:** SystemCapability.PowerManager.ThermalManager **System capability:** SystemCapability.PowerManager.ThermalManager
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | --------------------- | | -------- | ------------------------- | ---- | ---------------------------------------------- |
| callback | AsyncCallback&lt;void&gt; | No | Callback without a return value.| | callback | AsyncCallback&lt;void&gt; | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.|
**Example** **Example**
```js ```js
thermal.unsubscribeThermalLevel(() => { thermal.unsubscribeThermalLevel(() => {
console.info("Unsubscribe completed."); console.info('unsubscribe thermal level success.');
}); });
``` ```
## thermal.getThermalLevel ## thermal.getThermalLevel<sup>(deprecated)</sup>
getThermalLevel(): ThermalLevel getThermalLevel(): ThermalLevel
> This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9) instead.
Obtains the current thermal level. Obtains the current thermal level.
**System capability:** SystemCapability.PowerManager.ThermalManager **System capability:** SystemCapability.PowerManager.ThermalManager
**Return value**: **Return value**
| Type | Description | | Type | Description |
| ------------ | ------ | | ------------ | ------ |
...@@ -93,6 +181,22 @@ Obtains the current thermal level. ...@@ -93,6 +181,22 @@ Obtains the current thermal level.
**Example** **Example**
```js ```js
var lev = thermal.getThermalLevel(); var level = thermal.getThermalLevel();
console.info("Thermal level is: " + lev); console.info('thermal level is: ' + level);
``` ```
## ThermalLevel
Represents the thermal level.
**System capability:** SystemCapability.PowerManager.ThermalManager
| Name | Value | Description |
| ---------- | ---- | ------------------------------------------------------------ |
| COOL | 0 | The device is cool, and services are not restricted. |
| NORMAL | 1 | The device is operational but is not cool. You need to pay attention to its heating.|
| WARM | 2 | The device is warm. You need to stop or delay some imperceptible services.|
| HOT | 3 | The device is heating up. You need to stop all imperceptible services and downgrade or reduce the load of other services.|
| OVERHEATED | 4 | The device is overheated. You need to stop all imperceptible services and downgrade or reduce the load of major services.|
| WARNING | 5 | The device is overheated and is about to enter the emergency state. You need to stop all imperceptible services and downgrade major services to the maximum extent.|
| EMERGENCY | 6 | The device has entered the emergency state. You need to stop all services except those for the emergency help purposes.|
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册