提交 b4b4489e 编写于 作者: zyjhandsome's avatar zyjhandsome

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

......@@ -48,7 +48,7 @@ arkXtest is divided into two parts: unit test framework and UI test framework.
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
Hardware for running test scripts: PC connected to an OpenHarmony device, such as the RK3568 development board
### Setting Up the Environment
......@@ -63,8 +63,8 @@ Hardware for running test scripts: PC connected to a OpenHarmony device, such as
## Writing a Unit Test Script
```TS
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium'
import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
const delegator = abilityDelegatorRegistry.getAbilityDelegator()
export default function abilityTest() {
......@@ -197,11 +197,12 @@ The framework supports multiple test case execution modes, which are triggered b
| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true |
| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function |
| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 |
| size | Size of the test case to be executed. | small, medium, large | -s size small |
| size | Size of the test case to be executed. | small, medium, large | -s size small |
| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 |
**Running Commands**
Configure hdc-related environment variables, and then perform the following:
> Configure hdc-related environment variables, and then perform the following:
- Open the CLI.
- Run the **aa test** commands.
......@@ -260,12 +261,18 @@ Example 9: Execute test cases at the specified level.
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s level 0
```
Example 10: Execute test cases with the specified level.
Example 10: Execute test cases with the specified size.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s size small
```
Example 11: Execute test cases for a specified number of times.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s stress 1000
```
**Viewing the Test Result**
- During test execution in the CLI, the log information similar to the following is displayed:
......@@ -394,11 +401,11 @@ Run the following command, restart the device, and execute the test case again:
hdc shell param set persist.ace.testmode.enabled 1
```
#### The failure log contains "uitest-api dose not allow calling concurrently"
#### The failure log contains "uitest-api does 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".
The UI test case fails to be executed. The HiLog file contains the error message "uitest-api does not allow calling concurrently".
**Possible Causes**
......@@ -412,11 +419,11 @@ The UI test case fails to be executed. The HiLog file contains the error message
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"
#### The failure log contains "does 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".
The UI test case fails to be executed. The HiLog file contains the error message "does not exist on current UI! Check if the UI has changed after you got the widget object".
**Possible Causes**
......
......@@ -15,11 +15,11 @@ import pointer from '@ohos.multimodalInput.pointer';
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 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. |
| pointer | function getPointerStyle(windowId: number, callback: AsyncCallback\<PointerStyle>): void; | Obtains the mouse pointer style. |
## Hiding the Mouse Pointer
......
......@@ -39,7 +39,7 @@ Fault management is an important way for applications to deliver a better user e
- Fault query indicates that [faultLogger](../reference/apis/js-apis-faultLogger.md) obtains the fault information using its query API.
The figure below does not illustrate the time when [faultLogger](../reference/apis/js-apis-faultLogger.md) is called. You can refer to [LastExitReason](../reference/apis/js-apis-application-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis/js-apis-faultLogger.md) to query the information about the last fault.
The figure below does not illustrate the time when [faultLogger](../reference/apis/js-apis-faultLogger.md) is called. You can refer to [LastExitReason](../reference/apis/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis/js-apis-faultLogger.md) to query the information about the last fault.
![Fault rectification process](./figures/fault_rectification.png)
It is recommended that you call [errorManager](../reference/apis/js-apis-application-errorManager.md) to process the exception. After the processing is complete, you can call the status saving API and restart the application.
......@@ -134,7 +134,7 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state,
- Restore data.
After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onSaveState(state, wantParams)** of **EntryAbility** is called, and the saved data is in **parameters** of **want**.
After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onCreate(want, launchParam)** of **EntryAbility** is called, and the saved data is in **parameters** of **want**.
```ts
storage: LocalStorage
......
# HiLog Development
## Introduction
## Overview
HiLog is the log system of OpenHarmony that provides logging for the system framework, services, and applications to record information on user operations and system running status.
> **NOTE**
>
> This development guide is applicable only when you use Native APIs for application development. For details about the APIs, see [HiLog Native API Reference](https://gitee.com/openharmony-sig/interface_native_header/blob/master/en/native_sdk/dfx/log.h).
## Available APIs
| API/Macro| Description|
| -------- | -------- |
| int OH_LOG_Print(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...) | Outputs logs based on the specified log type, log level, service domain, log tag, and variable parameters determined by the format specifier and privacy identifier in the printf format.|
| int OH_LOG_Print(LogType type, LogLevel level, unsigned int domain, const char *tag, const char *fmt, ...) | Outputs logs based on the specified log type, log level, service domain, log tag, and variable parameters determined by the format specifier and privacy identifier in the printf format.<br>Input parameters: See [Parameter Description](#parameter-description).<br>Output parameters: None<br>Return value: total number of bytes if log printing is successful; **-1** otherwise.|
| #define OH_LOG_DEBUG(type, ...) ((void)OH_LOG_Print((type), LOG_DEBUG, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__))| Outputs DEBUG logs. This is a function-like macro.|
| #define OH_LOG_INFO(type, ...) ((void)OH_LOG_Print((type), LOG_INFO, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs INFO logs. This is a function-like macro.|
| #define OH_LOG_WARN(type, ...) ((void)OH_LOG_Print((type), LOG_WARN, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs WARN logs. This is a function-like macro.|
| #define OH_LOG_ERROR(type, ...) ((void)OH_LOG_Print((type), LOG_ERROR, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs ERROR logs. This is a function-like macro.|
| #define OH_LOG_FATAL(type, ...) ((void)OH_LOG_Print((type), LOG_FATAL, LOG_DOMAIN, LOG_TAG, \_*VA*ARGS__)) | Outputs FATAL logs. This is a function-like macro.|
| bool OH_LOG_IsLoggable(unsigned int domain, const char *tag, LogLevel level) | Checks whether logs of the specified service domain, tag, and level can be printed.<br>Input arguments:<br>- **domain**: service domain.<br>- **tag**: log tag.<br>- **level**: log level.<br>Output arguments: none<br>Return value: Returns **true** if the specified logs can be printed; returns **false** otherwise.|
| bool OH_LOG_IsLoggable(unsigned int domain, const char *tag, LogLevel level) | Checks whether logs of the specified service domain, tag, and level can be printed.<br>Input parameters: See [Parameter Description](#parameter-description).<br>Output arguments: none<br>Return value: **true** if the specified logs can be printed; **false** otherwise.|
## Parameter Description
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| type | enum | Yes | Enum of log printing types. The default value is **LOG_APP** for application logs.|
| level | enum | Yes | Log printing level. For details, see [Log Level](#loglevel).|
| domain | number | Yes | Service domain of logs. The value ranges from **0x0** to **0xFFFF**.<br>You can define the value as required. |
| tag | string | Yes | Log tag in the string format. You are advised to use this parameter to identify a particular service behavior or the class holding the ongoing method.|
| fmt | string | Yes | Format string used to output logs in a specified format. It can contain several parameters, where the parameter type and privacy identifier are mandatory.<br>Parameters labeled **{public}** are public data and are displayed in plaintext; parameters labeled **{private}** (default value) are private data and are filtered by **\<private>**.|
| args | any[] | Yes | Variable-length parameter list corresponding to the format string. The number and type of parameters must map to the identifier in the format string.|
## LogLevel
Log level.
| Name | Value | Description |
| ----- | ------ | ------------------------------------------------------------ |
| DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.|
| INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,<br>Log level used to record information about unexpected exceptions, such as network signal loss and login failure.<br>These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.|
| WARN | 5 | Log level used to record severe, unexpected faults that have little impact on users and can be rectified by the programs themselves or through simple operations.|
| ERROR | 6 | Log level used to record program or functional errors that affect the normal running or use of the functionality and can be fixed at a high cost, for example, by resetting data.|
| FATAL | 7 | Log level used to record program or functionality crashes that cannot be rectified.
## Development Examples
1. Include the **hilog** header file in the source file.
1. Add the link of **libhilog_ndk.z.so** to **CMakeLists.txt**:
```
target_link_libraries(entry PUBLIC libhilog_ndk.z.so)
```
2. Include the **hilog** header file in the source file, and define the **domain** and **tag** macros.
```c++
#include "hilog/log.h"
```
2. Define the **domain** and **tag** macros.
```c++
#undef LOG_DOMAIN
#undef LOG_TAG
#define LOG_DOMAIN 0x3200 // Service domain. The value ranges from 0xD0000 to 0xDFFFF.
#define LOG_TAG "MY_TAG"
#define LOG_DOMAIN 0x3200 // Global domain, which identifies the service domain.
#define LOG_TAG "MY_TAG" // Global tag, which identifies the module log tag.
```
3. Print logs. For example, to print INFO logs, use the following code:
3. Print logs. For example, to print ERROR logs, use the following code:
```c++
OH_LOG_INFO(LOG_APP, "Failed to visit %{private}s, reason:%{public}d.", url, errno);
OH_LOG_ERROR(LOG_APP, "Failed to visit %{private}s, reason:%{public}d.", url, errno);
```
4. View the output log information.
```
12-11 12:21:47.579 2695 2695 I A03200/MY_TAG: Failed to visit <private>, reason:11.
12-11 12:21:47.579 2695 2695 E A03200/MY_TAG: Failed to visit <private>, reason:11.
```
......@@ -87,7 +87,7 @@ The development process consists of the following main steps:
The required model can be downloaded directly or obtained using the model conversion tool.
- If the downloaded model is in the `.ms` format, you can use it directly for inference. The following uses the **mobilenetv2.ms** model as an example.
- If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/zh-CN/r1.5/use/downloads.html#id1) to convert it to the `.ms` format.
- If the downloaded model uses a third-party framework, such as TensorFlow, TensorFlow Lite, Caffe, or ONNX, you can use the [model conversion tool](https://www.mindspore.cn/lite/docs/en/r1.5/use/downloads.html#id1) to convert it to the `.ms` format.
2. Create a context, and set parameters such as the number of runtime threads and device type.
......
......@@ -9,7 +9,7 @@ The **AccessibilityExtensionAbility** module provides accessibility extension ca
## Modules to Import
```ts
import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility'
import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility';
```
## Attributes
......@@ -31,7 +31,7 @@ Defines an accessibility event.
| Name | Type | Readable | Writable | Description |
| --------- | ---------------------------------------- | ---- | ---- | ---------- |
| 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](js-apis-inner-application-accessibilityExtensionContext.md#accessibilityelement9) | Yes | No | Target component where the event occurs.|
| timeStamp | number | Yes | No | Timestamp of the event. |
## GestureType
......@@ -78,8 +78,8 @@ Enumerates the touch guide event types.
| Name | Description |
| ---------- | ------------ |
| touchBegin | Start of touch in touch guide mode. |
| touchEnd | End of touch in touch guide mode. |
| touchBegin | Start of touch in touch guide mode.|
| touchEnd | End of touch in touch guide mode.|
## AccessibilityExtensionAbility.onConnect
......@@ -137,7 +137,7 @@ Called when an event that matches the specified bundle and event type occurs. In
class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
onAccessibilityEvent(event) {
console.log('AxExtensionAbility onAccessibilityEvent');
if (event.eventType == 'click') {
if (event.eventType === 'click') {
console.log('AxExtensionAbility onAccessibilityEvent: click');
}
}
......@@ -164,7 +164,7 @@ Called when a physical key is pressed. In this API, you can determine whether to
class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility {
onKeyEvent(keyEvent) {
console.log('AxExtensionAbility onKeyEvent');
if (keyEvent.keyCode == 22) {
if (keyEvent.keyCode === 22) {
console.log('AxExtensionAbility onKeyEvent: intercept 22');
return true;
}
......
......@@ -2,9 +2,11 @@
The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status.
> **NOTE**<br>
> **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
```js
......@@ -20,18 +22,18 @@ Describes battery information.
| 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. |
| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging status of the device. |
| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health status 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.|
| estimatedRemainingChargeTime<sup>9+</sup> | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. **System API**: This is a system API. |
| totalEnergy<sup>9+</sup> | number | Yes | No | Total battery capacity of the device, in unit of mAh. **System API**: This is a system API. |
| nowCurrent<sup>9+</sup> | number | Yes | No | Battery current of the device, in unit of mA. **System API**: This is a system API. |
| remainingEnergy<sup>9+</sup> | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. **System API**: This is a system API.|
## BatteryPluggedType
......@@ -41,10 +43,10 @@ Enumerates charger types.
| Name | Value | Description |
| -------- | ---- | ----------------- |
| NONE | 0 | Unknown type |
| AC | 1 | AC charger|
| USB | 2 | USB charger |
| WIRELESS | 3 | Wireless charger|
| NONE | 0 | Unknown charger type. |
| AC | 1 | AC charger.|
| USB | 2 | USB charger. |
| WIRELESS | 3 | Wireless charger.|
## BatteryChargeState
......@@ -82,14 +84,15 @@ Enumerates battery levels.
| 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.|
| LEVEL_WARNING | 5 | Alarm battery level.|
| LEVEL_CRITICAL | 6 | Ultra-low battery level.|
| LEVEL_SHUTDOWN | 7 | Power-down battery level.|
## CommonEventBatteryChangedCode<sup>9+</sup>
## CommonEventBatteryChangedKey<sup>9+</sup>
Enumerates keys for querying the additional information about the **COMMON_EVENT_BATTERY_CHANGED** event.
......@@ -97,14 +100,12 @@ Enumerates keys for querying the additional information about the **COMMON_EVENT
| 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. |
| EXTRA_SOC | "soc" | Remaining battery level in percentage. |
| EXTRA_CHARGE_STATE | "chargeState" | Battery charging status of the device. |
| EXTRA_HEALTH_STATE | "healthState" | Battery health status of the device. |
| EXTRA_PLUGGED_TYPE | "pluggedType" | Type of the charger connected to the device. |
| EXTRA_VOLTAGE | "voltage" | Battery voltage of the device. |
| EXTRA_TECHNOLOGY | "technology" | Battery technology of the device. |
| EXTRA_TEMPERATURE | "temperature" | Battery temperature of the device. |
| EXTRA_PRESENT | "present" | Whether the battery is supported by the device or installed.|
| EXTRA_CAPACITY_LEVEL | "capacityLevel" | Battery level of the device. |
......@@ -722,7 +722,7 @@ Subscribes to service status changes.
| Name | Type | Mandatory| Description |
| ------------- | -------------------- | ---- | ------------------------------------------------------------ |
| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.|
| deathCallback | Callback&lt;void&gt; | Yes | Callback invoked to service status changes. |
| deathCallback | Callback&lt;void&gt; | Yes | Callback invoked to return service status changes. |
**Example**
......@@ -2847,7 +2847,7 @@ try {
### get
get(key: string, callback: AsyncCallback<boolean | string| number | Uint8Array>): void
get(key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void
Obtains the value of the specified key. This API uses an asynchronous callback to return the result.
......@@ -2898,7 +2898,7 @@ try {
### get
get(key: string): Promise&lt;boolean | string| number | Uint8Array&gt;
get(key: string): Promise&lt;boolean | string | number | Uint8Array&gt;
Obtains the value of the specified key. This API uses a promise to return the result.
......@@ -4849,7 +4849,7 @@ Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkv
### get
get(key: string, callback: AsyncCallback<boolean | string| number | Uint8Array>): void
get(key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void
Obtains the value of the specified key for this device. This API uses an asynchronous callback to return the result.
......@@ -4900,7 +4900,7 @@ try {
### get
get(key: string): Promise&lt;boolean | string| number | Uint8Array&gt;
get(key: string): Promise&lt;boolean | string | number | Uint8Array&gt;
Obtains the value of the specified key for this device. This API uses a promise to return the result.
......@@ -4952,7 +4952,7 @@ try {
### get
get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean|string|number|Uint8Array&gt;): void
get(deviceId: string, key: string, callback: AsyncCallback&lt;boolean | string | number | Uint8Array&gt;): void
Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result.
......@@ -5004,7 +5004,7 @@ try {
### get
get(deviceId: string, key: string): Promise&lt;boolean|string|number|Uint8Array&gt;
get(deviceId: string, key: string): Promise&lt;boolean | string | number | Uint8Array&gt;
Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result.
......
......@@ -35,7 +35,7 @@ Enables a device administrator application based on the specified bundle name an
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | --------------------------------------------------------------- |
......@@ -87,7 +87,7 @@ Enables a device administrator application for the specified user based on the s
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | --------------------------------------------------------------- |
......@@ -144,7 +144,7 @@ Enables a device administrator application based on the specified bundle name an
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | --------------------------------------------------------------- |
......@@ -190,7 +190,7 @@ Disables a device common administrator application based on the specified bundle
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------------------- |
......@@ -234,7 +234,7 @@ Disables a device common administrator application for the specified user based
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------------------- |
......@@ -283,7 +283,7 @@ Disables a device common administrator application based on the specified bundle
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------------------- |
......@@ -322,7 +322,7 @@ Disables a device super administrator application based on the specified bundle
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------------------- |
......@@ -367,7 +367,7 @@ Disables a device super administrator application based on the specified bundle
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------------------- |
......@@ -571,7 +571,7 @@ Sets the enterprise information of a device administrator application. This API
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------- |
......@@ -624,7 +624,7 @@ Sets the enterprise information of a device administrator application. This API
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------- |
......@@ -665,7 +665,7 @@ Obtains the enterprise information of a device administrator application. This A
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------- |
......@@ -712,7 +712,7 @@ Obtains the enterprise information of a device administrator application. This A
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------- |
......@@ -755,7 +755,7 @@ Subscribes to system management events. This API uses an asynchronous callback t
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
|ID| Error Message |
| ------- | ----------------------------------------------------- |
......@@ -804,7 +804,7 @@ Subscribes to system management events. This API uses a promise to return the re
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------- |
......@@ -847,7 +847,7 @@ Unsubscribes from system management events. This API uses an asynchronous callba
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------- |
......@@ -896,7 +896,7 @@ Unsubscribes from system management events. This API uses an asynchronous callba
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ----------------------------------------------------- |
......
......@@ -34,7 +34,7 @@ Sets the system time. This API uses an asynchronous callback to return the resul
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
......@@ -82,7 +82,7 @@ Sets the system time. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
......
# @ohos.enterprise.deviceControl (Device Control Management)
The **deviceControl** module provides APIs for device control, which can only be called by device administrator applications.
> **NOTE**
>
> The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
```js
import deviceControl from '@ohos.enterprise.deviceControl'
```
## deviceControl.resetFactory
resetFactory(admin: Want, callback: AsyncCallback\<void>): void
Restores factory settings. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_RESET_DEVICE
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the setting is successful, **err** is **null**. Otherwise, **err** is an error object.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example:**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
deviceControl.resetFactory(wantTemp, (error) => {
if (error) {
console.log("error code:" + error.code + " error message:" + error.message);
}
})
```
## deviceControl.resetFactory
resetFactory(admin: Want): Promise\<void>
Restores factory settings. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ENTERPRISE_RESET_DEVICE
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ----------------------------------- | ---- | ------- |
| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.|
**Return value**
| Type | Description |
| ----- | ----------------------------------- |
| Promise\<void> | Promise that returns no value.|
**Error codes**
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
| 9200001 | the application is not an administrator of the device. |
| 9200002 | the administrator application does not have permission to manage the device. |
**Example:**
```js
let wantTemp = {
bundleName: "bundleName",
abilityName: "abilityName",
};
deviceControl.resetFactory(wantTemp).then(() => {
}).catch((error) => {
console.log("error code:" + error.code + " error message:" + error.message);
})
```
......@@ -33,7 +33,7 @@ Obtains the device serial number. This API uses an asynchronous callback to retu
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
......@@ -82,7 +82,7 @@ Obtains the device serial number. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
......@@ -124,7 +124,7 @@ Obtains the device version number. This API uses an asynchronous callback to ret
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
......@@ -173,7 +173,7 @@ Obtains the device version number. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
......@@ -215,7 +215,7 @@ Obtains the device name. This API uses an asynchronous callback to return the re
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
......@@ -264,7 +264,7 @@ Obtains the device name. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
For details about the error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md).
| ID| Error Message |
| ------- | ---------------------------------------------------------------------------- |
......
......@@ -17,7 +17,7 @@ import fileAccess from '@ohos.file.fileAccess';
getFileAccessAbilityInfo( ) : Promise&lt;Array&lt;Want&gt;&gt;
Obtains information about all wants with **extension** set to **fileAcesss** in the system. A want is a basic communication component used to start services. This API uses a promise to return the result.
Obtains information about all wants with **extension** set to **fileAccess** in the system. A want is a basic communication component used to start services. This API uses a promise to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -25,9 +25,9 @@ Obtains information about all wants with **extension** set to **fileAcesss** in
**Return value**
| Type| Description|
| --- | -- |
| Promise&lt;Array&lt;Want&gt;&gt; | Promise used to return the **want** information obtained.|
| Type| Description|
| --- | -- |
| Promise&lt;Array&lt;Want&gt;&gt; | Promise used to return the **want** information obtained.|
**Example**
......@@ -47,7 +47,7 @@ Obtains information about all wants with **extension** set to **fileAcesss** in
getFileAccessAbilityInfo(callback: AsyncCallback&lt;Array&lt;Want&gt;&gt;): void;
Obtains information about all wants with **extension** set to **fileAcesss** in the system. A want is a basic communication component used to start services. This API uses an asynchronous callback to return the result.
Obtains information about all wants with **extension** set to **fileAccess** in the system. A want is a basic communication component used to start services. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -55,9 +55,9 @@ Obtains information about all wants with **extension** set to **fileAcesss** in
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;Array&lt;Want&gt;&gt; | Yes| Promise used to return the **want** information obtained.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;Array&lt;Want&gt;&gt; | Yes| Promise used to return the **want** information obtained.|
**Example**
......@@ -89,16 +89,16 @@ Synchronously creates a **Helper** object to connect to the specified wants. The
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| context | Context | Yes| Context of the ability.|
| wants | Array&lt;Want&gt; | Yes| Wants to connect.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| context | Context | Yes| Context of the ability.|
| wants | Array&lt;Want&gt; | Yes| Wants to connect.|
**Return value**
| Type| Description|
| --- | -- |
| FileAccessHelper | **Helper** object created.|
| Type| Description|
| --- | -- |
| FileAccessHelper | **Helper** object created.|
**Example**
......@@ -114,7 +114,7 @@ Synchronously creates a **Helper** object to connect to the specified wants. The
},
]
try {
// this.context is passed by MainAbility.
// this.context is passed by EntryAbility.
fileAccessHelper = fileAccess.createFileAccessHelper(this.context, wantInfos);
if (!fileAccessHelper)
console.error("createFileAccessHelper interface returns an undefined object");
......@@ -136,15 +136,15 @@ Synchronously creates a **Helper** object to connect to all file management serv
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| context | Context | Yes| Context of the ability.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| context | Context | Yes| Context of the ability.|
**Return value**
| Type| Description|
| --- | -- |
| FileAccessHelper | **Helper** object created.|
| Type| Description|
| --- | -- |
| FileAccessHelper | **Helper** object created.|
**Example**
......@@ -153,7 +153,7 @@ Synchronously creates a **Helper** object to connect to all file management serv
let fileAccesssHelperAllServer = null;
// Create a Helper object to interact with all file management services configured with fileAccess in the system.
try {
// this.context is passed by MainAbility.
// this.context is passed by EntryAbility.
fileAccesssHelperAllServer = fileAccess.createFileAccessHelper(this.context);
if (!fileAccesssHelperAllServer)
console.error("createFileAccessHelper interface returns an undefined object");
......@@ -167,8 +167,7 @@ Synchronously creates a **Helper** object to connect to all file management serv
getRoots( ) : Promise&lt;RootIterator&gt;
Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which
returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext).
Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext).
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -176,9 +175,9 @@ returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext).
**Return value**
| Type| Description|
| --- | -- |
| Promise&lt;RootIterator&gt; | Promise used to return the **RootIterator** object obtained.|
| Type| Description|
| --- | -- |
| Promise&lt;RootIterator&gt; | Promise used to return the **RootIterator** object obtained.|
**Example**
......@@ -211,8 +210,7 @@ returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext).
getRoots(callback:AsyncCallback&lt;RootIterator&gt;) : void;
Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses an asynchronous callback to return the result.
The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo) through [next()](#rootiteratornext).
Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses an asynchronous callback to return the result. The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo) through [next()](#rootiteratornext).
**System capability**: SystemCapability.FileManagement.UserFileService
......@@ -220,9 +218,9 @@ The callback has a **RootIterator** object, which returns [RootInfo](#rootinfo)
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;RootIterator&gt; | Yes| Promise used to return the **RootIterator** object obtained.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| callback | AsyncCallback&lt;RootIterator&gt; | Yes| Promise used to return the **RootIterator** object obtained.|
**Example**
......@@ -263,16 +261,16 @@ Synchronously obtains the **FileIterator** object of the first-level files (file
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
**Return value**
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
**Example**
......@@ -314,15 +312,15 @@ Recursively obtains the **FileIterator** object of the files matching the condit
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
**Return value**
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
**Example**
......@@ -364,15 +362,15 @@ Synchronously obtains the **FileIterator** object of the next-level files (file
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
**Return value**
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
**Example**
......@@ -414,16 +412,16 @@ Recursively obtains the **FileIterator** object of the files matching the condit
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
| Name| Type| Mandatory| Description|
| --- | --- | -- | -- |
| filter | Filter | No| **Filter** object. |
**Return value**
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
| Type| Description|
| --- | -- |
| FileIterator | **FileIterator** object obtained.|
**Example**
......@@ -465,10 +463,10 @@ Creates a file in a directory. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the parent directory for the file to create.|
| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the parent directory for the file to create.|
| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
**Return value**
......@@ -510,11 +508,11 @@ Creates a file in a directory. This API uses an asynchronous callback to return
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the parent directory for the file to create.|
| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the file created.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the parent directory for the file to create.|
| displayName | string | Yes| Name of the file to create. By default, the name of a local file must contain the file name extension.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the file created.|
**Example**
......@@ -550,10 +548,10 @@ Creates a folder in a directory. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| parentUri | string | Yes| URI of the parent directory for the folder to create.|
| displayName | string | Yes| Name of the folder to create.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| parentUri | string | Yes| URI of the parent directory for the folder to create.|
| displayName | string | Yes| Name of the folder to create.|
**Return value**
......@@ -595,11 +593,11 @@ Creates a folder in a directory. This API uses an asynchronous callback to retur
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| parentUri | string | Yes| URI of the parent directory for the folder to create.|
| displayName | string | Yes| Name of the folder to create.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the folder created.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| parentUri | string | Yes| URI of the parent directory for the folder to create.|
| displayName | string | Yes| Name of the folder to create.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the folder created.|
**Example**
......@@ -635,16 +633,16 @@ Opens a file. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file to open.|
| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file to open.|
| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
**Return value**
| Type| Description|
| --- | -- |
| Promise&lt;number&gt; | Promise used to return the handle to the file opened.|
| Promise&lt;number&gt; | Promise used to return the file descriptor of the file opened.|
**Example**
......@@ -673,11 +671,11 @@ Opens a file. This API uses an asynchronous callback to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file to open.|
| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
| callback | AsyncCallback&lt;number&gt; | Yes| Promise used to return the handle to the file opened.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file to open.|
| flags | [OPENFLAGS](#openflags) | Yes| File open mode.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the file descriptor of the file opened.|
**Example**
......@@ -712,9 +710,9 @@ Deletes a file or folder. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or folder to delete.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or folder to delete.|
**Return value**
......@@ -751,10 +749,10 @@ Deletes a file or folder. This API uses an asynchronous callback to return the r
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or folder to delete.|
| callback | AsyncCallback&lt;number&gt; | Yes| Promise used to return the result.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or folder to delete.|
| callback | AsyncCallback&lt;number&gt; | Yes| Promise used to return the result.|
**Example**
......@@ -789,10 +787,10 @@ Moves a file or folder. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFile | string | Yes| URI of the file or folder to move.|
| destFile | string | Yes| URI of the folder to which the file or folder will be moved.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFile | string | Yes| URI of the file or folder to move.|
| destFile | string | Yes| URI of the folder to which the file or folder will be moved.|
**Return value**
......@@ -829,11 +827,11 @@ Moves a file or folder. This API uses an asynchronous callback to return the res
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFile | string | Yes| URI of the file or folder to move.|
| destFile | string | Yes| URI of the folder to which the file or folder will be moved.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the file or folder in the destination directory.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFile | string | Yes| URI of the file or folder to move.|
| destFile | string | Yes| URI of the folder to which the file or folder will be moved.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the file or folder in the destination directory.|
**Example**
......@@ -869,10 +867,10 @@ Renames a file or folder. This API uses a promise to return the result.
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or folder to rename.|
| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or folder to rename.|
| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.|
**Return value**
......@@ -908,11 +906,11 @@ Renames a file or folder. This API uses an asynchronous callback to return the r
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or folder to rename.|
| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the renamed file or folder.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| uri | string | Yes| URI of the file or folder to rename.|
| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.|
| callback | AsyncCallback&lt;string&gt; | Yes| Promise used to return the URI of the renamed file or folder.|
**Example**
......@@ -947,9 +945,9 @@ Checks whether a file or folder exists. This API uses a promise to return the re
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFileUri | string | Yes| URI of the file or folder.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFileUri | string | Yes| URI of the file or folder.|
**Return value**
......@@ -988,10 +986,10 @@ Checks whether a file or folder exists. This API uses an asynchronous callback t
**Parameters**
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFileUri | string | Yes| URI of the file or folder.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Promise used to return the result.|
| Name| Type| Mandatory| Description|
| --- | --- | --- | -- |
| sourceFileUri | string | Yes| URI of the file or folder.|
| callback | AsyncCallback&lt;boolean&gt; | Yes| Promise used to return the result.|
**Example**
......
......@@ -278,7 +278,7 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur
import window from '@ohos.window';
window.getTopWindow((error, win) => {
win.getProperties((error, properties) => {
win.getWindowProperties((error, properties) => {
let windowId = properties.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
......@@ -321,7 +321,7 @@ Obtains the mouse pointer style. This API uses a promise to return the result.
import window from '@ohos.window';
window.getTopWindow((error, win) => {
win.getProperties((error, properties) => {
win.getWindowProperties((error, properties) => {
let windowId = properties.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
......@@ -360,7 +360,7 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t
import window from '@ohos.window';
window.getTopWindow((error, win) => {
win.getProperties((error, properties) => {
win.getWindowProperties((error, properties) => {
let windowId = properties.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
......@@ -398,7 +398,7 @@ Sets the mouse pointer style. This API uses a promise to return the result.
import window from '@ohos.window';
window.getTopWindow((error, win) => {
win.getProperties((error, properties) => {
win.getWindowProperties((error, properties) => {
let windowId = properties.id;
if (windowId < 0) {
console.log(`Invalid windowId`);
......
......@@ -286,95 +286,6 @@ Uploads files. This API uses an asynchronous callback to return the result.
});
```
## request.upload<sup>(deprecated)</sup>
upload(context: BaseContext, config: UploadConfig): Promise&lt;UploadTask&gt;
Uploads files. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[UploadTask](#uploadtask)&gt; | Promise used to return the **UploadTask** object.|
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'http://patch',
header: { key1: "value1", key2: "value2" },
method: "POST",
files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
data: [{ name: "name123", value: "123" }],
};
request.upload(globalThis.abilityContext, uploadConfig).then((data) => {
uploadTask = data;
}).catch((err) => {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
});
```
## request.upload<sup>(deprecated)</sup>
upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback&lt;UploadTask&gt;): void
Uploads files. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Upload
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.|
| callback | AsyncCallback&lt;[UploadTask](#uploadtask)&gt; | Yes| Callback used to return the **UploadTask** object.|
**Example**
```js
let uploadTask;
let uploadConfig = {
url: 'http://patch',
header: { key1: "value1", key2: "value2" },
method: "POST",
files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }],
data: [{ name: "name123", value: "123" }],
};
request.upload(globalThis.abilityContext, uploadConfig, (err, data) => {
if (err) {
console.error('Failed to request the upload. Cause: ' + JSON.stringify(err));
return;
}
uploadTask = data;
});
```
## UploadTask
Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile<sup>9+</sup>](#requestuploadfile9) in promise mode or [request.uploadFile<sup>9+</sup>](#requestuploadfile9-1) in callback mode.
......@@ -398,7 +309,7 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).|
| callback | function | Yes| Callback for the upload progress event.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -432,7 +343,7 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).|
| callback | function | Yes| Callback for the HTTP Response Header event.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -465,7 +376,7 @@ Subscribes to an upload event. This API uses an asynchronous callback to return
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | Yes| Callback used to return the result.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -507,7 +418,7 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).|
| callback | function | No| Callback for the upload progress event.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -541,7 +452,7 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).|
| callback | function | No| Callback for the HTTP Response Header event.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -573,7 +484,7 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret
| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.|
| callback | Callback&lt;Array&lt;TaskState&gt;&gt; | No| Callback used to return the result.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -952,82 +863,6 @@ Downloads files. This API uses an asynchronous callback to return the result.
});
```
## request.download<sup>(deprecated)</sup>
download(context: BaseContext, config: DownloadConfig): Promise&lt;DownloadTask&gt;
Downloads files. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[DownloadTask](#downloadtask)&gt; | Promise used to return the result.|
**Example**
```js
let downloadTask;
request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => {
downloadTask = data;
}).catch((err) => {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
})
```
## request.download<sup>(deprecated)</sup>
download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&lt;DownloadTask&gt;): void;
Downloads files. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1).
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.MiscServices.Download
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.|
| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.|
| callback | AsyncCallback&lt;[DownloadTask](#downloadtask)&gt; | Yes| Callback used to return the result.|
**Example**
```js
let downloadTask;
request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap',
filePath: 'xxx/xxxxx.hap'}, (err, data) => {
if (err) {
console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
return;
}
downloadTask = data;
});
```
## DownloadTask
Implements file downloads. Before using any APIs of this class, you must obtain a **DownloadTask** object through [request.downloadFile<sup>9+</sup>](#requestdownloadfile9) in promise mode or [request.downloadFile<sup>9+</sup>](#requestdownloadfile9-1) in callback mode.
......@@ -1050,7 +885,7 @@ Subscribes to a download event. This API uses an asynchronous callback to return
| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).|
| callback | function | Yes| Callback for the download progress event.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -1084,7 +919,7 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re
| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).|
| callback | function | No| Callback for the download progress event.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -1172,7 +1007,7 @@ Subscribes to the download task failure event. This API uses an asynchronous cal
| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).|
| callback | function | Yes| Callback for the download task failure event.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -1205,7 +1040,7 @@ Unsubscribes from the download task failure event. This API uses an asynchronous
| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).|
| callback | function | No| Callback for the download task failure event.|
Parameters of the callback function
Parameters of the callback function
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
......@@ -1265,7 +1100,7 @@ Deletes this download task. This API uses an asynchronous callback to return the
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task deletion result. |
| callback | AsyncCallback&lt;boolean&gt; | Yes| Callback used to return the task deletion result.|
**Example**
......
......@@ -47,7 +47,7 @@ Provides data items for setting the display effects.
| ANIMATOR_DURATION_SCALE | string | Yes | Yes | Scale factor for the animation duration. This affects the start delay and duration of all such animations.<br>If the value is **0**, the animation ends immediately. The default value is **1**.|
| TRANSITION_ANIMATION_SCALE | string | Yes | Yes | Scale factor for transition animations.<br>The value **0** indicates that the transition animations are disabled. |
| WINDOW_ANIMATION_SCALE | string | Yes | Yes | Scale factor for normal window animations.<br>The value **0** indicates that window animations are disabled. |
| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.<br>**1**: Display color inversion is enabled.<br>**0**: Display color inversion is disabled. |
| DISPLAY_INVERSION_STATUS | string | Yes | Yes | Whether display color inversion is enabled.<br>**1**: Display color inversion is enabled.<br>**0**: Display color inversion is disabled.|
## general
......@@ -185,121 +185,6 @@ Provides data items for setting wireless network information.
| WIFI_STATUS | string | Yes | Yes | Whether Wi-Fi is available.<br>**true**: Wi-Fi is available.<br>**false**: Wi-Fi is unavailable.|
| WIFI_WATCHDOG_STATUS | string | Yes | Yes | Whether Wi-Fi watchdog is available.<br>**true**: Wi-Fi watchdog is available.<br>**false**: Wi-Fi watchdog is unavailable.|
## setting.getURI
getURI(name: string, callback: AsyncCallback\<object>): void
Obtains the URI of a data item. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
| callback | AsyncCallback\<object> | Yes | Callback used to obtain the URI of the data item. |
**Example**
```js
settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS, (uri) => {
console.log(`callback:uri -> ${JSON.stringify(uri)}`)
})
```
## setting.getURI
getURI(name: string): Promise\<object>
Obtains the URI of a data item. This API uses a promise to return the result.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
**Return value**
| Type | Description |
| ---------------- | ------------------------------------ |
| Promise\<object> | Promise used to return the URI of the data item.|
**Example**
```js
settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS).then((uri) => {
console.log(`promise:uri -> ${JSON.stringify(uri)}`)
})
```
## setting.getValue
getValue(dataAbilityHelper: DataAbilityHelper, name: string, callback: AsyncCallback\<object>): void
Obtains the value of a data item in the database. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br> - Existing data items in the database<br>- Custom data items|
| callback | AsyncCallback\<object> | Yes | Callback used to return the value of the data item. |
**Example**
```js
import featureAbility from '@ohos.ability.featureAbility';
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, (err, value) => {
if (err) {
console.error(`Failed to get the setting. ${err.message} `);
return;
}
console.log(`callback:value -> ${JSON.stringify(value)}`)
});
```
## setting.getValue
getValue(dataAbilityHelper: DataAbilityHelper, name: string): Promise\<object>
Obtains the value of a data item in the database. This API uses a promise to return the result.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br> - Existing data items in the database<br>- Custom data items|
**Return value**
| Type | Description |
| ---------------- | ----------------------------------- |
| Promise\<object> | Promise used to return the value of the data item.|
**Example**
```js
import featureAbility from '@ohos.ability.featureAbility';
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS).then((value) => {
console.log(`promise:value -> ${JSON.stringify(value)}`)
});
```
## settings.setValue
......@@ -325,9 +210,11 @@ Sets the value for a data item. This API uses an asynchronous callback to return
```js
import featureAbility from '@ohos.ability.featureAbility';
// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update the value of the data item.)
// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update its value.)
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
// @ts-ignore
// The value of the data item is a string.
settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100', (status) => {
console.log('Callback return whether value is set.');
});
......@@ -365,6 +252,8 @@ import featureAbility from '@ohos.ability.featureAbility';
// Update the value of SCREEN_BRIGHTNESS_STATUS. (As this data item exists in the database, the setValue API will update the value of the data item.)
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
// @ts-ignore
// The value of the data item is a string.
settings.setValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '100').then((status) => {
console.log('Callback return whether value is set.');
});
......@@ -500,12 +389,154 @@ Obtains the URI of a data item.
let urivar = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
```
## settings.getValueSync<sup>8+</sup>
## setting.getURI<sup>(deprecated)</sup>
getURI(name: string, callback: AsyncCallback\<object>): void
Obtains the URI of a data item. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
| callback | AsyncCallback\<object> | Yes | Callback used to obtain the URI of the data item. |
**Example**
```js
settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS, (uri) => {
console.log(`callback:uri -> ${JSON.stringify(uri)}`)
})
```
## setting.getURI<sup>(deprecated)</sup>
getURI(name: string): Promise\<object>
Obtains the URI of a data item. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
**Return value**
| Type | Description |
| ---------------- | ------------------------------------ |
| Promise\<object> | Promise used to return the URI of the data item.|
**Example**
```js
settings.getURI(settings.display.SCREEN_BRIGHTNESS_STATUS).then((uri) => {
console.log(`promise:uri -> ${JSON.stringify(uri)}`)
})
```
## setting.getValue<sup>(deprecated)</sup>
getValue(dataAbilityHelper: DataAbilityHelper, name: string, callback: AsyncCallback\<object>): void
Obtains the value of a data item in the database. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9.
**Model restriction**: This API can be used only in the FA model.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br> - Existing data items in the database<br>- Custom data items|
| callback | AsyncCallback\<object> | Yes | Callback used to return the value of the data item. |
**Example**
```js
import featureAbility from '@ohos.ability.featureAbility';
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, (err, value) => {
if (err) {
console.error(`Failed to get the setting. ${err.message} `);
return;
}
console.log(`callback:value -> ${JSON.stringify(value)}`)
});
```
## setting.getValue<sup>(deprecated)</sup>
getValue(dataAbilityHelper: DataAbilityHelper, name: string): Promise\<object>
Obtains the value of a data item in the database. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 7 and deprecated since API version 9.
**Model restriction**: This API can be used only in the FA model.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br> - Existing data items in the database<br>- Custom data items|
**Return value**
| Type | Description |
| ---------------- | ----------------------------------- |
| Promise\<object> | Promise used to return the value of the data item.|
**Example**
```js
import featureAbility from '@ohos.ability.featureAbility';
let uri = settings.getUriSync(settings.display.SCREEN_BRIGHTNESS_STATUS);
let helper = featureAbility.acquireDataAbilityHelper(uri);
settings.getValue(helper, settings.display.SCREEN_BRIGHTNESS_STATUS).then((value) => {
console.log(`promise:value -> ${JSON.stringify(value)}`)
});
```
## settings.getValueSync<sup>(deprecated)</sup>
getValueSync(dataAbilityHelper: DataAbilityHelper, name: string, defValue: string): string
Obtains the value of a data item. Unlike **getValue**, this API returns the result synchronously.
> **NOTE**
>
> This API is supported since API version 8 and deprecated since API version 9.
**Model restriction**: This API can be used only in the FA model.
**System capability**: SystemCapability.Applications.settings.Core
**Parameters**
......@@ -514,7 +545,7 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu
| ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ |
| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. |
| name | string | Yes | Name of the target data item. Data items can be classified as follows:<br>- Existing data items in the database<br>- Custom data items|
| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed. |
| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed.|
**Return value**
......@@ -533,7 +564,7 @@ let helper = featureAbility.acquireDataAbilityHelper(uri);
let value = settings.getValueSync(helper, settings.display.SCREEN_BRIGHTNESS_STATUS, '10');
```
## settings.setValueSync<sup>8+</sup>
## settings.setValueSync<sup>(deprecated)</sup>
setValueSync(dataAbilityHelper: DataAbilityHelper, name: string, value: string): boolean
......@@ -541,6 +572,12 @@ Sets the value for a data item. Unlike **setValue**, this API returns the result
If the specified data item exists in the database, the **setValueSync** method updates the value of the data item. If the data item does not exist in the database, the **setValueSync** method inserts the data item into the database.
> **NOTE**
>
> This API is supported since API version 8 and deprecated since API version 9.
**Model restriction**: This API can be used only in the FA model.
**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS (available only to system applications)
**System capability**: SystemCapability.Applications.settings.Core
......
......@@ -21,8 +21,6 @@ fetch(Object): void
Obtains data through a network.
**Required permission**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
**Parameters**
......@@ -33,8 +31,8 @@ Obtains data through a network.
| header | Object | No| Request header.|
| method | string | No| Request method. The default value is **GET**. The value can be **OPTIONS**, **GET**, **HEAD**, **POST**, **PUT**, **DELETE **or **TRACE**.|
| responseType | string | No| Response type. The return type can be text or JSON. By default, the return type is determined based on **Content-Type** in the header returned by the server. For details, see return values in the **success** callback.|
| success | Function | No| Called when the data is obtained successfully.|
| fail | Function | No| Called when the data failed to be obtained.|
| success | Function | No| Called when data is obtained successfully. The return value is [FetchResponse](#fetchresponse). |
| fail | Function | No| Called when data failed to be obtained.|
| complete | Function | No| Called when the execution is complete.|
**Table 1** Mapping between data and Content-Type
......@@ -46,7 +44,7 @@ Obtains data through a network.
| Object | Not set| The default value of **Content-Type** is **application/x-www-form-urlencoded**. The **data** value is encoded based on the URL rule and appended in the request body.|
| Object | application/x-www-form-urlencoded | The value of data is encoded based on the URL rule and is used as the request body.|
Return values in the **success** callback
## FetchResponse
| Name| Type| Description|
| -------- | -------- | -------- |
......
......@@ -33,22 +33,15 @@ Obtains the network type.
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;successful. |
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;operation&nbsp;fails. |
| complete | Function | No | Called&nbsp;when&nbsp;the&nbsp;execution&nbsp;is&nbsp;complete |
| success | Function | No | Called when the execution is successful. The return value is [NetworkResponse](#networkresponse). |
| fail | Function | No | Called when the operation fails. |
| complete | Function | No | Called when the execution is complete |
The following value will be returned when the multimedia volume is obtained.
Return value of the **fail** callback:
| Parameter | Type | Description |
| -------- | -------- | -------- |
| metered | boolean | Whether&nbsp;the&nbsp;billing&nbsp;is&nbsp;based&nbsp;on&nbsp;the&nbsp;data&nbsp;volume. |
| type | string | Network&nbsp;type.&nbsp;The&nbsp;value&nbsp;can&nbsp;be&nbsp;**2G**,&nbsp;**3G**,&nbsp;**4G**,&nbsp;**5G**,&nbsp;**WiFi**,&nbsp;or&nbsp;**none**. |
One of the following error codes will be returned if the operation fails.
| Error&nbsp;Code | Description |
| Error Code | Description |
| -------- | -------- |
| 602 | The&nbsp;current&nbsp;permission&nbsp;is&nbsp;not&nbsp;declared. |
| 602 | The current permission is not declared. |
**Example**
......@@ -80,22 +73,15 @@ Listens to the network connection state. If this method is called multiple times
| Name | Type | Mandatory | Description |
| -------- | -------- | -------- | -------- |
| success | Function | No | Called&nbsp;when&nbsp;the&nbsp;network&nbsp;connection&nbsp;state&nbsp;changes |
| fail | Function | No | Called&nbsp;when&nbsp;the&nbsp;multimedia&nbsp;volume&nbsp;fails&nbsp;to&nbsp;be&nbsp;obtained. |
| success | Function | No | Called when the network connection state changes |
| fail | Function | No | Called when the multimedia volume fails to be obtained. |
The following value will be returned when the multimedia volume is obtained.
| Parameter | Type | Description |
| -------- | -------- | -------- |
| metered | boolean | Whether&nbsp;the&nbsp;billing&nbsp;is&nbsp;based&nbsp;on&nbsp;the&nbsp;data&nbsp;volume. |
| type | string | Network&nbsp;type.&nbsp;The&nbsp;value&nbsp;can&nbsp;be&nbsp;**2G**,&nbsp;**3G**,&nbsp;**4G**,&nbsp;**5G**,&nbsp;**WiFi**,&nbsp;or&nbsp;**none**. |
Return value of the **fail** callback:
One of the following error codes will be returned if the listening fails.
| Error&nbsp;Code | Description |
| Error Code | Description |
| -------- | -------- |
| 602 | The&nbsp;current&nbsp;permission&nbsp;is&nbsp;not&nbsp;declared. |
| 200 | The&nbsp;subscription&nbsp;fails. |
| 602 | The current permission is not declared. |
| 200 | The subscription fails. |
**Example**
......@@ -131,4 +117,11 @@ export default {
network.unsubscribe();
},
}
```
\ No newline at end of file
```
## NetworkResponse
| Parameter | Type | Description |
| -------- | -------- | -------- |
| metered | boolean | Whether the billing is based on the data volume. |
| type | string | Network type. The value can be **2G**, **3G**, **4G**, **5G**, **WiFi**, or **none**. |
\ No newline at end of file
......@@ -51,7 +51,7 @@ export default {
## storage.set
get(options: SetStorageOptions): void
set(options: SetStorageOptions): void
Sets the value in the cache based on the specified key.
......@@ -167,8 +167,8 @@ export default {
| key | string | Yes | Key of the data to set. |
| value | string | Yes | New value to set. The length must be less than 128 bytes. |
| success | () => void | No | Called when **storage.set()** is called successfully. |
| fail | (data: string, code: number) => void | No | Called to return the result when **storage.get()** fails to be called. **data** is the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when **storage.get()** is complete. |
| fail | (data: string, code: number) => void | No | Called to return the result when **storage.set()** fails to be called. **data** is the error information, and **code** indicates the error code. |
| complete | () => void | No | Called when **storage.set()** is complete. |
## ClearStorageOptions
......
......@@ -278,6 +278,8 @@ Sets whether to enable web debugging.
| ------------------ | ------- | ---- | ------------- |
| webDebuggingAccess | boolean | Yes | Whether to enable web debugging.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
......@@ -305,7 +307,7 @@ struct WebComponent {
### loadUrl
loadUrl(url: string | Resource, headers?: Array\<HeaderV9>): void
loadUrl(url: string | Resource, headers?: Array\<WebHeader>): void
Loads a specified URL.
......@@ -316,7 +318,7 @@ Loads a specified URL.
| Name | Type | Mandatory| Description |
| ------- | ---------------- | ---- | :-------------------- |
| url | string \| Resource | Yes | URL to load. |
| headers | Array\<[HeaderV9](#headerv9)> | No | Additional HTTP request header of the URL.|
| headers | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the URL.|
**Error codes**
......@@ -344,6 +346,7 @@ struct WebComponent {
Button('loadUrl')
.onClick(() => {
try {
// The URL to be loaded is of the string type.
this.controller.loadUrl('www.example.com');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
......@@ -355,6 +358,69 @@ struct WebComponent {
}
```
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// The headers parameter is carried.
this.controller.loadUrl('www.example.com', [{headerKey: "headerKey", headerValue: "headerValue"}]);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.webDebuggingAccess(true)
}
}
}
```
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// The URL to be loaded is of the Resource type.
this.controller.loadUrl($rawfile('xxx.html'));
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
```html
<!-- xxx.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
### loadData
loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void
......@@ -829,7 +895,7 @@ struct WebComponent {
### getHitTest
getHitTest(): HitTestTypeV9
getHitTest(): WebHitTestType
Obtains the element type of the area being clicked.
......@@ -839,7 +905,7 @@ Obtains the element type of the area being clicked.
| Type | Description |
| ------------------------------------------------------------ | ---------------------- |
| [HitTestTypeV9](#hittesttypev9)| Element type of the area being clicked.|
| [WebHitTestType](#webhittesttype)| Element type of the area being clicked.|
**Error codes**
......@@ -1026,7 +1092,7 @@ Executes a JavaScript script. This API uses a promise to return the script execu
| Type | Description |
| --------------- | --------------------------------------------------- |
| Promise\<string> | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed|
| Promise\<string> | Promise used to return the result. Returns **null** if the JavaScript script fails to be executed|
**Error codes**
......@@ -1512,7 +1578,7 @@ struct WebComponent {
this.ports = this.controller.createWebMessagePorts();
// 2. Register a callback on a message port (for example, port 1) on the application side.
this.ports[1].onMessageEvent((result: web_webview.WebMessage) => {
var msg = 'Got msg from HTML:';
let msg = 'Got msg from HTML:';
if (typeof(result) == "string") {
console.log("received string message from html5, string is:" + result);
msg = msg + result;
......@@ -1540,7 +1606,7 @@ struct WebComponent {
.onClick(() => {
try {
if (this.ports && this.ports[1]) {
this.ports[1].postMessageEvent("post message from ets to HTML");
this.ports[1].postMessageEvent("this.sendFromEts");
} else {
console.error(`ports is null, Please initialize first`);
}
......@@ -3579,7 +3645,7 @@ Deletes all data in the specified origin.
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------ |
| origin | string | Yes | Index of the origin.|
| origin | string | Yes | Index of the origin, which is obtained through [getOrigins](#getorigins).|
**Error codes**
......@@ -4140,7 +4206,7 @@ Checks whether any saved HTTP authentication credentials exist. This API returns
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.|
| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise. |
**Example**
......@@ -4204,133 +4270,6 @@ struct WebComponent {
}
```
## WebAsyncController
Implements a **WebAsyncController** object, which can be used to control the behavior of a **\<Web>** component with asynchronous callbacks. A **WebAsyncController **object controls one **\<Web>** component.
### Creating an Object
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
webAsyncController: web_webview.WebAsyncController = new web_webview.WebAsyncController(this.controller)
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### constructor<sup>9+</sup>
constructor(controller: WebController)
Implements a **WebAsyncController** by binding it with a [WebController](../arkui-ts/ts-basic-components-web.md#webcontroller) object.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ---- | ---- | --- |
| controller | [WebController](../arkui-ts/ts-basic-components-web.md#webcontroller) | Yes| **WebviewController** to bind.|
### storeWebArchive<sup>9+</sup>
storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void
Stores this web page. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null. |
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. |
| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Button('saveWebArchive')
.onClick(() => {
let webAsyncController = new web_webview.WebAsyncController(this.controller)
webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => {
if (filename != null) {
console.info(`save web archive success: ${filename}`)
}
})
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### storeWebArchive<sup>9+</sup>
storeWebArchive(baseName: string, autoName: boolean): Promise\<string>
Stores this web page. This API uses a promise to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null. |
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. |
**Return value**
| Type | Description |
| ---------------- | ------------------------------------------------------------ |
| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('saveWebArchive')
.onClick(() => {
let webAsyncController = new web_webview.WebAsyncController(this.controller);
webAsyncController.storeWebArchive("/data/storage/el2/base/", true)
.then(filename => {
if (filename != null) {
console.info(`save web archive success: ${filename}`)
}
})
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## GeolocationPermissions
Implements a **GeolocationPermissions** object.
......@@ -4686,7 +4625,7 @@ struct WebComponent {
}
}
```
## HeaderV9
## WebHeader
Describes the request/response header returned by the **\<Web>** component.
**System capability**: SystemCapability.Web.Webview.Core
......@@ -4696,7 +4635,7 @@ Describes the request/response header returned by the **\<Web>** component.
| headerKey | string | Yes| Yes| Key of the request/response header. |
| headerValue | string | Yes| Yes| Value of the request/response header.|
## HitTestTypeV9
## WebHitTestType
**System capability**: SystemCapability.Web.Webview.Core
......@@ -4719,7 +4658,7 @@ Provides the element information of the area being clicked. For details about th
| Name| Type| Readable| Writable| Description|
| ---- | ---- | ---- | ---- |---- |
| type | [HitTestTypeV9](#hittesttypev9) | Yes| No| Element type of the area being clicked.|
| type | [WebHitTestType](#webhittesttype) | Yes| No| Element type of the area being clicked.|
| extra | string | Yes| No|Extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.|
## WebMessage
......@@ -4788,7 +4727,7 @@ import image from "@ohos.multimedia.image"
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State icon: image.PixelMap = undefined;
build() {
Column() {
Button('getBackForwardEntries')
......@@ -4796,8 +4735,8 @@ struct WebComponent {
try {
let list = this.controller.getBackForwardEntries();
let historyItem = list.getItemAtIndex(list.currentIndex);
console.log("HistoryItem: " + JSON.stringify(historyItem));
this.icon = historyItem.icon;
console.log("HistoryItem: " + JSON.stringify(historyItem));
this.icon = historyItem.icon;
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
......
......@@ -51,7 +51,7 @@ This component can contain only one child component.
| Normal | Normal button (without rounded corners by default). |
> **NOTE**
> - The rounded corner of a button is set by using [borderRadius](ts-universal-attributes-border.md), rather than by using the **border** API.
> - The rounded corner of a button is set by using [borderRadius](ts-universal-attributes-border.md), rather than by using the **border** API. Only a button-wide rounded corner setting is supported.
> - For a button of the **Capsule** type, the **borderRadius** settings do not take effect, and its rounded corner is always half of the button height.
> - For a button of the **Circle** type, its radius is the value of **borderRadius** (if set) or the width or height (whichever is smaller).
> - The button text is set using the [text style attributes](ts-universal-attributes-text-style.md).
......
......@@ -37,7 +37,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the
| viewPort | {<br>x?: number \| string,<br>y?: number \| string,<br>width?: number \| string,<br>height?: number \| string<br>} | { x:0, y:0, width:0, height:0 } | View port of the shape.|
| fill | [ResourceColor](ts-types.md) | Color.Black | Color of the fill area.|
| fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | Opacity of the fill area.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, no stroke is displayed.|
| stroke | [ResourceColor](ts-types.md) | - | Stroke color. If this attribute is not set, the component does not have any stroke.|
| strokeDashArray | Array&lt;Length&gt; | [] | Stroke dashes.|
| strokeDashOffset | number \| string | 0 | Offset of the start point for drawing the stroke.|
| strokeLineCap | [LineCapStyle](ts-appendix-enums.md#linecapstyle) | LineCapStyle.Butt | Cap style of the stroke.|
......@@ -145,91 +145,3 @@ struct ShapeExample {
```
![en-us_image_0000001184628104](figures/en-us_image_0000001184628104.png)
### Example 2
```ts
// xxx.ets
@Entry
@Component
struct ShapeMeshExample {
@State columnVal: number = 0
@State rowVal: number = 0
@State count: number = 0
@State verts: Array<number> = []
@State shapeWidth: number = 600
@State shapeHeight: number = 600
build() {
Column() {
Shape() {
Rect()
.width('250px')
.height('250px')
.radiusWidth('10px')
.radiusHeight('10px')
.stroke('10px')
.margin({ left: '10px', top: '10px' })
.strokeWidth('10px')
.fill(Color.Blue)
Rect()
.width('250px')
.height('250px')
.radiusWidth('10px')
.radiusHeight('10px')
.stroke('10px')
.margin({ left: '270px', top: '10px' })
.strokeWidth('10px')
.fill(Color.Red)
}
.mesh(this.verts, this.columnVal, this.rowVal)
.width(this.shapeWidth + 'px')
.height(this.shapeHeight + 'px')
// The mesh distortion effect is displayed when the component is touched.
.onTouch((event: TouchEvent) => {
var touchX = event.touches[0].x * 2
var touchY = event.touches[0].y * 2
this.columnVal = 20
this.rowVal = 20
this.count = (this.columnVal + 1) * (this.rowVal + 1)
var orig = [this.count * 2]
var index = 0
for (var i = 0; i <= this.rowVal; i++) {
var fy = this.shapeWidth * i / this.rowVal
for (var j = 0; j <= this.columnVal; j++) {
var fx = this.shapeWidth * j / this.columnVal
orig[index * 2 + 0] = this.verts[index * 2 + 0] = fx
orig[index * 2 + 1] = this.verts[index * 2 + 1] = fy
index++;
}
}
for (var k = 0; k < this.count * 2; k += 2) {
var dx = touchX - orig[k + 0]
var dy = touchY - orig[k + 1]
var dd = dx * dx + dy * dy
var d = Math.sqrt(dd)
var pull = 80000 / (dd * d)
if (pull >= 1) {
this.verts[k + 0] = touchX
this.verts[k + 1] = touchY
} else {
this.verts[k + 0] = orig[k + 0] + dx * pull
this.verts[k + 1] = orig[k + 1] + dy * pull
}
}
})
}
.width('600px')
.height('600px')
.border({ width: 3, color: Color.Black })
}
}
```
Below is how the component is displayed when not being touched.
![en-us_image1_0000001184628104](figures/en-us_image1_0000001184628104.png)
The mesh distortion effect is displayed when the component is touched, as shown below.
![en-us_image2_0000001184628104](figures/en-us_image2_0000001184628104.png)
......@@ -4,10 +4,10 @@
The [Ability Privilege Level (APL)](accesstoken-overview.md#app-apls) of an application can be **normal**, **system_basic**, or **system_core**. The default APL is **normal**. The [permission types](accesstoken-overview.md#permission-types) include **system_grant** and **user_grant**. For details about the permissions for applications, see the [Application Permission List](permission-list.md).
This document describes:
This document describes the following operations:
- [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file)
- [Declaring Permissions in the ACL](#declaring-permissions-in-the-acl)
- [Declaring the ACL](#declaring-the-acl)
- [Requesting User Authorization](#requesting-user-authorization)
- [Pre-Authorizing user_grant Permissions](#pre-authorizing-user_grant-permissions)
......@@ -15,22 +15,22 @@ This document describes:
During the development, you need to declare the permissions required by your application one by one in the project configuration file. The application cannot obtain the permissions that are not declared in the configuration file. OpenHarmony provides two application models: FA model and stage model. For more information, see [Application Models](../application-models/application-model-description.md). The application bundle and configuration file vary with the application model.
> **NOTE**<br>The default APL of an application is **normal**. When an application needs the **system_basic** or **system_core** APL, you must declare the permission in the configuration file and the [Access Control List (ACL)](#declaring-permissions-in-the-acl).
> **NOTE**<br>The default APL of an application is **normal**. When an application of the **normal** APL needs a permission of the **system_basic** or **system_core** level, you must declare the permission in the configuration file and the [Access Control List (ACL)](#declaring-the-acl).
The following table describes the fields in the configuration file.
| Field | Mandatory| Description |
| --------- | -------- | ------------------------------------------------------------ |
| name | Yes | Name of the permission. |
| reason | No | Reason for requesting the permission.<br>This field is mandatory when the requested permission needs user authorization (user_grant).|
| usedScene | No | Application scenario of the permission.<br>This field is mandatory when the requested permission needs user authorization (user_grant).|
| reason | No | Reason for requesting the permission.<br>This field is mandatory when a user_grant permission is required.|
| usedScene | No | Application scenario of the permission.<br>This field is mandatory when a user_grant permission is required.|
| abilities | No | Abilities that require the permission. The value is an array.<br>**Applicable model**: stage|
| ability | No | Abilities that require the permission. The value is an array.<br>**Applicable model**: FA|
| when | No | Time when the permission is used. <br>Value:<br>- **inuse**: The permission applies only to a foreground application.<br>- **always**: The permission applies to both the foreground and background applications.|
### Stage Model
If the application is based on the stage model, declare the permissions in [**module.json5**](../quick-start/module-configuration-file.md).
If your application is based on the stage model, declare the required permissions in [**module.json5**](../quick-start/module-configuration-file.md).
```json
{
......@@ -64,7 +64,7 @@ If the application is based on the stage model, declare the permissions in [**mo
### FA Model
If the application is based on the FA model, declare the required permissions in **config.json**.
If your application is based on the FA model, declare the required permissions in **config.json**.
```json
{
......@@ -96,11 +96,11 @@ If the application is based on the FA model, declare the required permissions in
}
```
## Declaring Permissions in the ACL
## Declaring the ACL
If an application of the **normal** level requires permissions corresponding to the **system_basic** or **system_core** level, you need to declare the required permissions in the ACL.
If an application of the **normal** APL requires permissions of the **system_basic** or **system_core** level, you need to declare the required permissions in the ACL.
For example, if an application needs to access audio files of a user and capture screenshots, it requires the **ohos.permission.WRITE_AUDIO** permission (of the **system_basic** level) and the **ohos.permission.CAPTURE_SCREEN** permission (of the **system_core** level). In this case, you need to add the related permissions to the **acl** field in the [HarmonyAppProvision configuration file](app-provision-structure.md).
For example, if an application needs to access audio files of a user and capture screenshots, it requires the **ohos.permission.WRITE_AUDIO** permission (of the **system_basic** level) and the **ohos.permission.CAPTURE_SCREEN** permission (of the **system_core** level). In this case, you need to add the required permissions to the **acls** field in the [HarmonyAppProvision configuration file](app-provision-structure.md).
```json
{
......@@ -116,11 +116,11 @@ For example, if an application needs to access audio files of a user and capture
## Requesting User Authorization
If an application needs to access user privacy information or use system abilities, for example, accessing location or calendar information or using the camera to take photos or record videos, it must request the permission from users. A permission verification is performed first to determine whether the current invoker has the corresponding permission. If the application has not obtained that permission, a dialog box will be displayed to request user authorization. The following figure shows an example.
If an application needs to access user privacy information or use system abilities, for example, accessing location or calendar information or using the camera to take photos or record videos, it must request the permission from the user. A permission verification is performed first to determine whether the current caller has the corresponding permission. If the application has not obtained that permission, a dialog box will be displayed to request user authorization. The following figure shows an example.
![](figures/permission-read_calendar.png)
> **NOTE**<br>Each time before an API protected by a permission is accessed, [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) will be called to request user authorization. After a permission is dynamically granted, the user may revoke the permission. Therefore, the previously granted authorization status cannot be persistent.
> **NOTE**<br>Each time before an API protected by a user_grant permission is accessed, [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) will be called to request user authorization. After the permission is dynamically granted, the user may revoke the authorization. Therefore, the previously granted authorization status cannot be persistent.
### Stage Model
......@@ -128,7 +128,7 @@ Example: Request the permission for an application to access calendar informatio
1. Apply for the **ohos.permission.READ_CALENDAR** permission. For details, see [Declaring Permissions in the Configuration File](#declaring-permissions-in-the-configuration-file).
2. Call [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) in the **onWindowStageCreate()** callback of the UIAbility to dynamically apply for the permission, or request user authorization on the UI based on service requirements. The return value of [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) indicates whether the application has the target permission. If yes, the target API can be called normally.
2. Call [**requestPermissionsFromUser()**](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) in the **onWindowStageCreate()** callback of the UIAbility to dynamically apply for the permission, or request user authorization on the UI based on service requirements. The return value of [requestPermissionsFromUser()](../reference/apis/js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) indicates whether the application has the permission. If yes, the target API can be called.
Request user authorization in UIAbility.
......@@ -149,11 +149,14 @@ Example: Request the permission for an application to access calendar informatio
atManager.requestPermissionsFromUser(context, permissions).then((data) => {
console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
let grantStatus: Array<number> = data.authResults;
if (grantStatus[0] === -1) {
// The authorization fails.
} else {
// The authorization is successful.
let length: number = grantStatus.length;
for (let i = 0; i < length; i++) {
if (grantStatus[i] !== 0) {
// The authorization fails.
return;
}
}
// The authorization is successful.
}).catch((err) => {
console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
})
......@@ -179,11 +182,14 @@ Example: Request the permission for an application to access calendar informatio
atManager.requestPermissionsFromUser(context, permissions).then((data) => {
console.info(`[requestPermissions] data: ${JSON.stringify(data)}`);
let grantStatus: Array<number> = data.authResults;
if (grantStatus[0] === -1) {
// The authorization fails.
} else {
// The authorization is successful.
let length: number = grantStatus.length;
for (let i = 0; i < length; i++) {
if (grantStatus[i] !== 0) {
// The authorization fails.
return;
}
}
// The authorization is successful.
}).catch((err) => {
console.error(`[requestPermissions] Failed to start request permissions. Error: ${JSON.stringify(err)}`);
})
......@@ -217,7 +223,7 @@ reqPermissions() {
}
```
## Pre-Authorizing user_grant Permissions
By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, for pre-installed applications, you can pre-authorize the permissions, for example, the **ohos.permission.MICROPHONE** permission for camera applications, in the [**install_list_permission.json**] file to prevent the user authorization dialog box from being displayed. The [**install_list_permissions.json** file](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) is in the **/system/etc/app/** directory on a device. When the device is started, the **install_list_permissions.json** file is loaded. When the application is installed, the **user_grant** permissions in the file are granted. The **install_list_permissions.json** file contains the following fields:
By default, the **user_grant** permissions must be dynamically authorized by the user through a dialog box. However, for pre-installed applications, you can pre-authorize the permissions, for example, the **ohos.permission.MICROPHONE** permission for camera applications, in the [**install_list_permission.json**](https://gitee.com/openharmony/vendor_hihope/blob/master/rk3568/preinstall-config/install_list_permissions.json) file to prevent the user authorization dialog box from being displayed. The **install_list_permissions.json** file is in the **/system/etc/app/** directory on a device. When the device is started, the **install_list_permissions.json** file is loaded. When the application is installed, the user_grant permissions in the file are granted. The **install_list_permissions.json** file contains the following fields:
- **bundleName**: bundle name of the application.
- **app_signature**: fingerprint information of the application. For details, see **Configuration in install_list_capability.json** in [Application Privilege Configuration Guide](../../device-dev/subsystems/subsys-app-privilege-config-guide.md).
......
......@@ -8,10 +8,12 @@ Create a **\<Web>** component in the .ets file under **main/ets/entryability/pag
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: 'https://www.example.com', controller: this.controller })
......@@ -26,11 +28,13 @@ When using the **\<Web>** component, you must specify the styles and attributes.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
fileAccess: boolean = true;
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Text('Hello world!')
......@@ -54,13 +58,15 @@ Add the **onProgressChange** event for the **\<Web>** component, which is trigge
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
@State progress: number = 0;
@State hideProgress: boolean = true;
fileAccess: boolean = true;
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Text('Hello world!')
......@@ -93,14 +99,17 @@ Add the **runJavaScript** method to the **onPageEnd** event. The **onPageEnd** e
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
@State progress: number = 0;
@State hideProgress: boolean = true;
@State webResult: string = ''
fileAccess: boolean = true;
// Define the controller for the \<Web> component.
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Text('Hello world!')
......@@ -124,8 +133,23 @@ struct WebComponent {
})
.onPageEnd(e => {
// test() is defined in index.html.
this.controller.runJavaScript({ script: 'test()' });
console.info('url: ', e.url);
try {
this.controller.runJavaScript(
'test()',
(error, result) => {
if (error) {
console.info(`run JavaScript error: ` + JSON.stringify(error))
return;
}
if (result) {
this.webResult = result
console.info(`The test() return value is: ${result}`)
}
});
console.info('url: ', e.url);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Text('End')
.fontSize(20)
......@@ -160,10 +184,12 @@ The configuration procedure is as follows:
1. Set the **webDebuggingAccess** attribute of the **\<Web>** component to **true**.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
......@@ -189,20 +215,30 @@ In this example, you'll implement a **\<Web>** component where videos can be pla
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Row() {
Button('onActive').onClick(() => {
console.info("Web Component onActive");
this.controller.onActive();
try {
this.controller.onActive();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Button('onInactive').onClick(() => {
console.info("Web Component onInactive");
this.controller.onInactive();
try {
this.controller.onInactive();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
}
Web({ src: $rawfile('index.html'), controller: this.controller })
......
......@@ -65,6 +65,7 @@ ohos_shared_library("helloworld") {
# Sanitizer variables
cfi = [boolean]
cfi_cross_dso = [boolean] # CFI: shared library support.
scs = [boolean]
scudo = []
ubsan = []
......@@ -106,6 +107,7 @@ ohos_static_library("helloworld") {
# Sanitizer variables
cfi = [boolean]
cfi_cross_dso = [boolean] # CFI: shared library support.
scs = [boolean]
scudo = []
ubsan = []
......@@ -138,6 +140,7 @@ ohos_executable("helloworld") {
# Sanitizer variables
cfi = [boolean]
cfi_cross_dso = [boolean] # CFI: shared library support.
scs = [boolean]
scudo = []
ubsan = []
......@@ -181,6 +184,7 @@ ohos_source_set("helloworld") {
# Sanitizer variables
cfi = [boolean]
cfi_cross_dso = [boolean] # CFI: shared library support.
scs = [boolean]
scudo = []
ubsan = []
......
......@@ -72,6 +72,7 @@ Sanitizer configuration example:
ohos_shared_library("example") {
sanitize = {
cfi = true
cfi_cross_dso = true # CFI: shared library support.
integer_overflow = true
debug = true # Optional. The debug mode is disabled by default.
blocklist = "./blocklist.txt" # Optional. Enter the path of the blocklist.
......
......@@ -119,7 +119,7 @@ DataShare即数据共享模块,提供了向其他应用共享以及管理其
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('DataShareExtAbility onCreate, executeSql done err:' + JSON.stringify(err));
});
if (callbakc) {
if (callback) {
callback();
}
});
......
......@@ -117,6 +117,7 @@ install(hapFilePaths: Array&lt;string&gt;, installParam: InstallParam, callback:
| 17700016 | Failed to install the HAP because of insufficient system disk space. |
| 17700017 | Failed to install the HAP since the version of the HAP to install is too early. |
| 17700018 | Failed to install because the dependent module does not exist. |
| 17700031 | Failed to install the HAP because the overlay check of the HAP is failed. |
**示例:**
......
......@@ -40,7 +40,7 @@ RichText(content:string)
| \<br/> | 插入一个简单的换行符。 | \<p>这是一个段落\<br/>这是换行段落\</p> |
| \<font/> | 规定文本的字体、字体尺寸、字体颜色。 | \<font size="3" face="arial" color="red">这是一段红色字体。\</font> |
| \<hr/> | 定义HTML页面中的主题变化(比如话题的转移),并显示为一条水平线。 | \<p>这个一个段落\</p>\<hr/>\<p>这是一个段落\</p> |
| \<image>\</image> | 用来定义图片。 | \<image src="file:///data/storage/el1/bundle/entry/resources/rawfile/icon.png">\</image> |
| \<image>\</image> | 用来定义图片。 | \<image src="resource://rawfile/icon.png">\</image> |
| \<div>\</div> | 常用于组合块级元素,以便通过CSS来对这些元素进行格式化。 | \<div style='color:#0000FF'>\<h3>这是一个在div元素中的标题。\</h3>\</div> |
| \<i>\</i> | 定义与文本中其余部分不同的部分,并把这部分文本呈现为斜体文本。 | \<i>这是一个斜体\</i> |
| \<u>\</u> | 定义与常规文本风格不同的文本,像拼写错误的单词或者汉语中的专有名词,应尽量避免使用\<u>为文本加下划线,用户会把它混淆为一个超链接。 | \<p>\<u>这是带有下划线的段落\</u>\</p> |
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册