提交 42e787f8 编写于 作者: W wangkailong 提交者: Gitee

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

Signed-off-by: Nwangkailong <wangkailong6@huawei.com>
......@@ -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-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-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-router.md @huaweimaxuchu @HelloCrease @niulihua @tomatodevboy
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
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-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-router.md @HelloCrease
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
```
# FAQs
- [Ability Framework Development](faqs-ability.md)
- [Bundle Management Development](faqs-bundle.md)
- [ArkUI (eTS) Development](faqs-ui-ets.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)
- [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)
- [Media Development](faqs-media.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)
- [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
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?
......@@ -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.
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
## 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
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)
......@@ -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
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:
```
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**.
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**.
......@@ -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).
## 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
......
# 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
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.
```
"requestPermissions": [
{
......@@ -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.
```
private requestPermissions() {
let permissionList: Array<string> = [
......@@ -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.
......@@ -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.|
|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.|
|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.|
......
# @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 APIs of this module can be used only in the stage model.
> 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
......@@ -18,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens
**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
......@@ -32,36 +30,10 @@ Defines an accessibility event.
| 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.|
| 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
Enumerates gesture types.
......@@ -89,7 +61,7 @@ Enumerates gesture types.
## PageUpdateType
Enumerates the page refresh types.
Enumerates the page update types.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
......@@ -106,27 +78,25 @@ Enumerates the touch guide event types.
| Name | Description |
| ---------- | ------------ |
| touchBegin | A touch starts in touch guide mode.|
| touchEnd | A touch ends in touch guide mode.|
| touchBegin | Start of touch in touch guide mode. |
| touchEnd | End of touch in touch guide mode. |
## AccessibilityExtensionAbility.onConnect
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
**Parameters**
None
**Example**
```ts
onConnect(): void {
console.log("AxExtensionAbility onConnect");
}
class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
onConnect() {
console.log('AxExtensionAbility onConnect');
}
};
```
## AccessibilityExtensionAbility.onDisconnect
......@@ -137,16 +107,14 @@ Called when the **AccessibilityExtensionAbility** is disabled and disconnected f
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
**Parameters**
None
**Example**
```ts
onDisconnect(): void {
console.log("AxExtensionAbility onDisconnect");
}
class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
onDisconnect() {
console.log('AxExtensionAbility onDisconnect');
}
};
```
## AccessibilityExtensionAbility.onAccessibilityEvent
......@@ -166,19 +134,21 @@ Called when an event that matches the specified bundle and event type occurs. In
**Example**
```ts
onAccessibilityEvent(event: AccessibilityEvent): void {
console.log("AxExtensionAbility onAccessibilityEvent");
if (event.eventType == 'click') {
console.log("AxExtensionAbility onAccessibilityEvent: click");
class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
onAccessibilityEvent(event) {
console.log('AxExtensionAbility onAccessibilityEvent');
if (event.eventType == 'click') {
console.log('AxExtensionAbility onAccessibilityEvent: click');
}
}
}
};
```
## 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
......@@ -191,12 +161,14 @@ Called when a physical key is pressed. In this API, you can determine whether to
**Example**
```ts
onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean {
console.log("AxExtensionAbility onKeyEvent");
if (keyEvent.keyCode == 22) {
console.log("AxExtensionAbility onKeyEvent: intercept 22");
return true;
class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
onKeyEvent(keyEvent) {
console.log('AxExtensionAbility onKeyEvent');
if (keyEvent.keyCode == 22) {
console.log('AxExtensionAbility onKeyEvent: intercept 22');
return true;
}
return false;
}
return false;
}
};
```
# 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.
> **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
......@@ -13,67 +12,100 @@ The Battery Info module provides APIs for querying the charger type, battery hea
import batteryInfo from '@ohos.batteryInfo';
```
## System Capabilities
SystemCapability.PowerManager.BatteryManager
## Attributes
Describes battery information.
| Name | Type | Readable | Writable | Description |
| ----------------------------- | ----------------------------------------- | -------- | -------- | ------------------------------------------------------------ |
| batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. |
| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. |
| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. |
| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. |
| voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. |
| technology | string | Yes | No | Battery technology of the current device. |
| batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. |
| isBatteryPresent<sup>7+</sup> | boolean | Yes | No | Whether the battery is supported or present. |
**Example**
```js
import batteryInfo from '@ohos.batteryInfo';
var batterySoc = batteryInfo.batterySOC;
```
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| Name | Type | Readable| Writable| Description |
| --------------- | ------------------- | ---- | ---- | ---------------------|
| batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage. |
| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the device. |
| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the device. |
| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the device. |
| voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. |
| technology | string | Yes | No | Battery technology of the device. |
| batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. |
| 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. |
| estimatedRemainingChargeTime<sup>9+</sup> | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. |
| totalEnergy<sup>9+</sup> | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. |
| 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
Enumerates charger types.
| Name | Default Value | Description |
| -------- | ------------- | ----------------- |
| NONE | 0 | Unknown type. |
| AC | 1 | AC charger. |
| USB | 2 | USB charger. |
| WIRELESS | 3 | Wireless charger. |
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| Name | Value | Description |
| -------- | ---- | ----------------- |
| NONE | 0 | Unknown type |
| AC | 1 | AC charger|
| USB | 2 | USB charger |
| WIRELESS | 3 | Wireless charger|
## BatteryChargeState
Enumerates charging states.
| Name | Default 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. |
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| 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
Enumerates battery health states.
| Name | Default Value | Description |
| ----------- | ------------- | ------------------------------------ |
| UNKNOWN | 0 | Unknown state. |
| GOOD | 1 | The battery is in the healthy state. |
| OVERHEAT | 2 | The battery is overheated. |
| OVERVOLTAGE | 3 | The battery voltage is over high. |
| COLD | 4 | The battery temperature is low. |
| DEAD | 5 | The battery is dead. |
**System capability**: SystemCapability.PowerManager.BatteryManager.Core
| Name | Value | Description |
| ----------- | ---- | -------------- |
| UNKNOWN | 0 | Unknown state. |
| GOOD | 1 | The battery is in the healthy state. |
| OVERHEAT | 2 | The battery is overheated. |
| 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
> ![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.
# 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
......@@ -18,18 +20,30 @@ setValue(value: number): void
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**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----------- |
| value | number | Yes | Brightness value, ranging from **0** to **255**.|
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ----------------------- |
| 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**
```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.
......@@ -36,6 +36,14 @@ Converts an XML text into a 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**
```js
......@@ -46,13 +54,13 @@ let xml =
' <todo>Work</todo>' +
' <todo>Play</todo>' +
'</note>';
let conv = new convertxml.convertToJSObject();
let conv = new convertxml.ConvertXML()
let options = {trim : false, declarationKey:"_declaration",
instructionKey : "_instruction", attributesKey : "_attributes",
textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype",
commentKey : "_comment", parentKey : "_parent", typeKey : "_type",
nameKey : "_name", elementsKey : "_elements"}
let result = JSON.stringify(conv.convert(xml, options));
let result = JSON.stringify(conv.convertToJSObject(xml, options));
console.log(result);
// 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"}]}]}]}
......@@ -60,14 +68,14 @@ console.log(result);
### 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
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
**Parameters**
......
# Battery Level
# Battery Info
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> - 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.
>
> - 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.
This module allows you to query the charging status and remaining power of a device.
> **NOTE**
> - 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
......@@ -16,40 +17,46 @@ import battery from '@system.battery';
## battery.getStatus
getStatus(Object): void
getStatus(options?: GetStatusOptions): void;
Obtains the current charging state and battery level.
**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 |
| 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. |
| options | [GetStatusOptions](#getstatusoptions) | No| Object that contains the API calling result.|
**Example**
```js
export default {
getStatus() {
battery.getStatus({
success: function(data) {
console.log('success get battery level:' + data.level);
},
fail: function(data, code) {
console.log('fail to get battery level code:' + code + ', data: ' + data);
},
});
},
}
```
\ No newline at end of file
battery.getStatus({
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);
}
});
```
## GetStatusOptions
Object that contains the API calling result.
| 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**.|
......@@ -22,38 +22,39 @@ Creates a progress indicator.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| value | number | Yes| Current progress.|
| value | number | Yes| Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used.|
| total | number | No| Total progress.<br>Default value: **100**|
| type<sup>8+</sup> | ProgressType | No| Type of the progress indicator.<br>Default value: **ProgressType.Linear**|
| style<sup>deprecated</sup> | ProgressStyle | No| Style the progress indicator.<br>This parameter is deprecated since API version 8. You are advised to use **type** instead.<br>Default value: **ProgressStyle.Linear**|
| type<sup>8+</sup> | [ProgressType](#progresstype) | No| Style the progress indicator.<br>Default value: **ProgressType.Linear**|
| style<sup>deprecated</sup> | [ProgressStyle](#progressstyle) | No| Type of the progress indicator.<br>This parameter is deprecated since API version 8. You are advised to use **type** instead.<br>Default value: **ProgressStyle.Linear**|
## ProgressType
| Name| Description|
| -------- | -------- |
| Linear | Linear type.|
| Linear | Linear type. Since API version 9, the progress indicator adaptively switches to vertical layout if the height is greater than the width.|
| Ring<sup>8+</sup> | Indeterminate ring type. The ring fills up as the progress increases.|
| Eclipse<sup>8+</sup> | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.|
| ScaleRing<sup>8+</sup> | Determinate ring type, which is similar to the clock scale.|
| Capsule<sup>8+</sup> | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type.|
| ScaleRing<sup>8+</sup> | Determinate ring type, which is similar to the clock scale. Since API version 9, when the outer circles of scales overlap, the progress indicator is automatically converted to the **Ring** type.|
| Capsule<sup>8+</sup> | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.|
## ProgressStyle
| Name | Description |
| --------- | ------------------------------------------------------------ |
| Linear | Linear type. |
| Ring | Indeterminate ring type. The ring fills up as the progress increases. |
| Linear | Linear type.|
| Ring | Indeterminate ring type. The ring fills up as the progress increases.|
| Eclipse | Eclipse type, which visualizes the progress in a way similar to the moon waxing from new to full.|
| ScaleRing | Determinate ring type, which is similar to the clock scale. |
| Capsule | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type.|
| ScaleRing | Determinate ring type, which is similar to the clock scale.|
| Capsule | Capsule type. At both ends, the progress indicator works in a same manner as the eclipse type. In the middle part of the capsule, the progress indicator works in a same manner as the linear type. If the height is greater than the width, the progress indicator adaptively switches to vertical layout.|
## Attributes
| Name| Type| Description|
| -------- | -------- | -------- |
| value | number | Current progress.|
| value | number | Current progress. If the value is less than 0, the value **0** is used. If the value is greater than that of **total**, the value of **total** is used. Invalid values do not take effect.|
| color | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.|
| style<sup>8+</sup> | {<br>strokeWidth?: [Length](ts-types.md#length),<br>scaleCount?: number,<br>scaleWidth?: [Length](ts-types.md#length)<br>} | Component style.<br>- **strokeWidth**: stroke width of the progress indicator.<br>- **scaleCount**: number of divisions on the determinate ring-type process indicator.<br>- **scaleWidth**: scale bar width of the determinate ring-type process indicator. If it is greater than the progress indicator width, the default value is used instead.|
| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the progress indicator.|
| style<sup>8+</sup> | {<br>strokeWidth?: [Length](ts-types.md#length),<br>scaleCount?: number,<br>scaleWidth?: [Length](ts-types.md#length)<br>} | Component style.<br>- **strokeWidth**: stroke width of the progress indicator. It cannot be set in percentage. Since API version 9, if the stroke width of the ring progress bar is greater than or equal to the radius, the width is changed to half of the radius.<br>Default value: **4.0Vp**<br>- **scaleCount**: number of divisions on the determinate ring-type process indicator.<br>Default value: **120**<br>- **scaleWidth**: scale width of the ring progress bar. It cannot be set in percentage. If it is greater than the value of **strokeWidth**, the default scale width is used.<br>Default value: **2.0Vp**|
## Example
......@@ -69,6 +70,7 @@ struct ProgressExample {
Progress({ value: 10, type: ProgressType.Linear }).width(200)
Progress({ value: 20, total: 150, type: ProgressType.Linear }).color(Color.Grey).value(50).width(200)
Text('Eclipse Progress').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row({ space: 40 }) {
Progress({ value: 10, type: ProgressType.Eclipse }).width(100)
......@@ -83,6 +85,16 @@ struct ProgressExample {
.style({ strokeWidth: 15, scaleCount: 15, scaleWidth: 5 })
}
// scaleCount vs. scaleWidth
Row({ space: 40 }) {
Progress({ value: 20, total: 150, type: ProgressType.ScaleRing })
.color(Color.Grey).value(50).width(100)
.style({ strokeWidth: 20, scaleCount: 20, scaleWidth: 5 })
Progress({ value: 20, total: 150, type: ProgressType.ScaleRing })
.color(Color.Grey).value(50).width(100)
.style({ strokeWidth: 20, scaleCount: 30, scaleWidth: 3 })
}
Text('Ring Progress').fontSize(9).fontColor(0xCCCCCC).width('90%')
Row({ space: 40 }) {
Progress({ value: 10, type: ProgressType.Ring }).width(100)
......@@ -105,4 +117,4 @@ struct ProgressExample {
}
```
![en-us_image_0000001212378432](figures/en-us_image_0000001212378432.gif)
![progress](figures/progress.png)
......@@ -3,9 +3,13 @@
- Ability Framework
- [Ability Error Codes](errorcode-ability.md)
- [Distributed Scheduler Error Codes](errorcode-DistributedSchedule.md)
- [Form Error Codes](errorcode-form.md)
- Bundle Management
- [Bundle Error Codes](errorcode-bundle.md)
- [zlib Error Codes](errorcode-zlib.md)
- Common Event and Notification
- [Event Error Codes](errorcode-CommonEventService.md)
- [DistributedNotificationService Error Codes](errorcode-DistributedNotificationService.md)
- UI Page
- [promptAction Error Codes](errorcode-promptAction.md)
- [Router Error Codes](errorcode-router.md)
......@@ -30,27 +34,38 @@
- [HUKS Error Codes](errorcode-huks.md)
- Data Management
- [RDB Error Codes](errorcode-data-rdb.md)
- [Distributed KV Store Error Codes](errorcode-distributedKVStore.md)
- [Preferences Error Codes](errorcode-preferences.md)
- Network Management
- [Upload and Download Error Codes](errorcode-request.md)
- Connectivity
- [NFC Error Codes](errorcode-nfc.md)
- [RPC Error Codes](errorcode-rpc.md)
- Basic Features
- [Accessibility Error Codes](errorcode-accessibility.md)
- [FaultLogger Error Codes](errorcode-faultlogger.md)
- [Application Event Logging Error Codes](errorcode-hiappevent.md)
- [HiSysEvent Error Codes](errorcode-hisysevent.md)
- [HiDebug Error Codes](errorcode-hiviewdfx-hidebug.md)
- [Input Method Framework Error Codes](errorcode-inputmethod-framework.md)
- [Pasteboard Error Codes](errorcode-pasteboard.md)
- [Screen Lock Management Error Codes](errorcode-screenlock.md)
- [Webview Error Codes](errorcode-webview.md)
- Account Management
- [Account Error Codes](errorcode-account.md)
- [App Account Error Codes](errorcode-app-account.md)
- Device Management
- [Power Consumption Statistics Error Codes](errorcode-batteryStatistics.md)
- [Brightness Error Codes](errorcode-brightness.md)
- [Power Manager Error Codes](errorcode-power.md)
- [Running Lock Error Codes](errorcode-runninglock.md)
- [Thermal Manager Error Codes](errorcode-thermal.md)
- [Device Management Error Codes](errorcode-device-manager.md)
- [Location Subsystem Error Codes](errorcode-geoLocationManager.md)
- [Screen Hopping Error Codes](errorcode-multimodalinput.md)
- [Sensor Error Codes](errorcode-sensor.md)
- [Vibrator Error Codes](errorcode-vibrator.md)
- [System Parameter Error Codes](errorcode-system-parameterV9.md)
- [USB Error Codes](errorcode-usb.md)
- Language Base Class Library
- [Buffer Error Codes](errorcode-buffer.md)
- [containers Error Codes](errorcode-containers.md)
- Language Base Class Library
- [Utils Error Codes](errorcode-utils.md)
# Power Consumption Statistics Error Codes
## 4600101 Service Connection Failure
**Error Message**
Operation failed. Cannot connect to service.
**Description**
This error code is reported for a service connection failure.
**Possible Causes**
1. The system service stops running.
2. The internal communication of system services is abnormal.
**Solution**
Check whether the system services are running properly.
1. Run the following command on the console to view the current system service list:
```bash
> hdc shell hidumper -ls
```
2. Check whether **BatteryStatisticsService** is included in the system service list.
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册