diff --git a/CODEOWNERS b/CODEOWNERS
index 23303c92c5a24ed1894449ea30b52c7de2685226..fffaf64564e559bbf9ca4ffd5d5a65e228b26e00 100644
--- a/CODEOWNERS
+++ b/CODEOWNERS
@@ -241,7 +241,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @feng-aiwen @ge
zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-udmf.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-cloudData.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
-zh-cn/application-dev/reference/apis/js-apis-data-relationStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
+zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-ValuesBucket.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
diff --git a/en/application-dev/application-models/arkts-ui-widget-configuration.md b/en/application-dev/application-models/arkts-ui-widget-configuration.md
index ea9832f92d32dfe0c2a4160f3ac6f8e904d323fa..d86c3b6991460a25c0ea6a177a8aec8c4607364c 100644
--- a/en/application-dev/application-models/arkts-ui-widget-configuration.md
+++ b/en/application-dev/application-models/arkts-ui-widget-configuration.md
@@ -54,7 +54,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and
| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)|
| metadata | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)|
| dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.
- **true**: The widget supports the update-through-proxy feature.
- **false**: The widget does not support the update-through-proxy feature.
If this tag is set to **true**, the settings for the scheduled update time will still take effect, but the settings for the update interval and next update time will not.| Boolean| Yes (initial value: **false**)|
- | isDynamic | Whether the widget is a dynamic widget. This tag only applies to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)|
+ | isDynamic | Whether the widget is a dynamic widget. This tag applies only to ArkTS widgets.
- **true**: The widget is a dynamic widget.
- **false**: The widget is a static widget. In this case, the widget is displayed as a static image after being added.| Boolean| Yes (initial value: **true**)|
**Table 2** Internal structure of the window object
diff --git a/en/application-dev/application-models/component-startup-rules.md b/en/application-dev/application-models/component-startup-rules.md
index bddf63dbc69ea243733e6f60f67f92a854833bf7..2db47d35f24df7d3eb155bb4ab2540f4a1af7ce0 100644
--- a/en/application-dev/application-models/component-startup-rules.md
+++ b/en/application-dev/application-models/component-startup-rules.md
@@ -26,7 +26,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
- If the **exported** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details, see [Component exported Configuration](../quick-start/module-configuration-file.md#abilities).
-- **Before starting a component of a background application, verify the BACKGROUND permission.**
+- **Before starting a UIAbility component of a background application, verify the BACKGROUND permission.**
- An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground.
- Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
@@ -45,7 +45,9 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
The rules for starting components on the same device vary in the following scenarios:
-- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components
+- Starting the UIAbility component
+
+- Starting the ServiceExtensionAbility and DataShareExtensionAbility components
- Using **startAbilityByCall()** to start the UIAbility component
@@ -56,9 +58,10 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
The rules for starting components on a different device vary in the following scenarios:
-- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components
+- Starting the UIAbility component
+
+- Starting the ServiceExtensionAbility and DataShareExtensionAbility components
- Using **startAbilityByCall()** to start the UIAbility component

-
diff --git a/en/application-dev/application-models/figures/component-startup-inner-stage.png b/en/application-dev/application-models/figures/component-startup-inner-stage.png
index 00514276f4ac3eb8ead650e5858cebb0a344d2c6..9761b9879e513f0e1ad942b5fe18997f1331c9e5 100644
Binary files a/en/application-dev/application-models/figures/component-startup-inner-stage.png and b/en/application-dev/application-models/figures/component-startup-inner-stage.png differ
diff --git a/en/application-dev/application-models/figures/component-startup-inter-stage.png b/en/application-dev/application-models/figures/component-startup-inter-stage.png
index a6f79e6803edc160e5570729456569f46cc80967..517407f6b557648db78a0de89431d8b18f8e2b59 100644
Binary files a/en/application-dev/application-models/figures/component-startup-inter-stage.png and b/en/application-dev/application-models/figures/component-startup-inter-stage.png differ
diff --git a/en/application-dev/application-models/start-pageability-from-stage.md b/en/application-dev/application-models/start-pageability-from-stage.md
index bd6a11187fdfbc81c63bcc6601f8a8e82b0dbe4c..123e15c45614f83ece1c11db87827535b2ac4937 100644
--- a/en/application-dev/application-models/start-pageability-from-stage.md
+++ b/en/application-dev/application-models/start-pageability-from-stage.md
@@ -8,6 +8,10 @@ This topic describes how the two application components of the stage model start
A UIAbility starts a PageAbility in the same way as it starts another UIAbility.
+> **NOTE**
+>
+> In the FA model, **abilityName** consists of **bundleName** and **AbilityName**. For details, see the code snippet below.
+
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
@@ -25,7 +29,7 @@ export default class EntryAbility extends UIAbility {
});
let want = {
bundleName: "com.ohos.fa",
- abilityName: "EntryAbility",
+ abilityName: "com.ohos.fa.EntryAbility",
};
this.context.startAbility(want).then(() => {
console.info('Start Ability successfully.');
diff --git a/en/application-dev/application-models/start-uiability-from-fa.md b/en/application-dev/application-models/start-uiability-from-fa.md
index 42d8e034cd6519643423bb289217d1aa140a18d4..8520cf94be0d0d21999af3175848a37edac85c52 100644
--- a/en/application-dev/application-models/start-uiability-from-fa.md
+++ b/en/application-dev/application-models/start-uiability-from-fa.md
@@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility';
let parameter = {
"want": {
bundleName: "com.ohos.stage",
- abilityName: "com.ohos.stage.EntryAbility"
+ abilityName: "EntryAbility"
}
};
featureAbility.startAbility(parameter).then((code) => {
diff --git a/en/application-dev/application-models/want-overview.md b/en/application-dev/application-models/want-overview.md
index cf5cac43999a5efbe59659252b6b3db325cacd8a..9260c71666f3c47181756ba205c265391d989b05 100644
--- a/en/application-dev/application-models/want-overview.md
+++ b/en/application-dev/application-models/want-overview.md
@@ -12,7 +12,7 @@
## Types of Want
-- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an an application component, explicit Want is used.
+- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an application component, explicit Want is used.
Explicit Want is usually used to start a known target application component in the same application. The target application component is started by specifying **bundleName** of the application where the target application component is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target application component.
@@ -24,7 +24,7 @@
}
```
-- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting the an application component, implicit Want is used.
+- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting an application component, implicit Want is used.
Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select.
@@ -47,6 +47,7 @@
> - An application component that meets the conditions is matched. That application component is started.
> - Multiple application components that meet the conditions are matched. A dialog box is displayed for users to select one of them.
>
- > - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want.
+ > - In the scenario for starting the ServiceExtensionAbility component:
+ > - If the **want** parameter passed in contains **abilityName**, the ServiceExtensionAbility component cannot be started through implicit Want.
>
- > - If the **want** parameter passed contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start ServiceExtensionAbility. By default, ServiceExtensionAbility with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility is returned.
+ > - If the **want** parameter passed in contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start the ServiceExtensionAbility component. By default, the ServiceExtensionAbility component with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility component is returned.
diff --git a/en/application-dev/connectivity/http-request.md b/en/application-dev/connectivity/http-request.md
index 1bb784cf96fb1d74dcbafed54498435f505814b6..a0fa4102864ba2403e7a6826f3ca3b872b5a80dd 100644
--- a/en/application-dev/connectivity/http-request.md
+++ b/en/application-dev/connectivity/http-request.md
@@ -1,6 +1,6 @@
# HTTP Data Request
-## When to Use
+## Overview
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
@@ -18,7 +18,7 @@ The following table provides only a simple description of the related APIs. For
| ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. |
-| request2()10+ | Initiates an HTTP network request based on the URL and returns a streaming response.|
+| requestInStream()10+ | Initiates an HTTP network request to a given URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
@@ -27,8 +27,8 @@ The following table provides only a simple description of the related APIs. For
| off\('dataReceive'\)10+ | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)10+ | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)10+ | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
-| on\('dataProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
-| off\('dataProgress'\)10+ | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
+| on\('dataReceiveProgress'\)10+ | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
+| off\('dataReceiveProgress'\)10+ | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop request APIs
@@ -53,6 +53,7 @@ httpRequest.on('headersReceive', (header) => {
});
httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
+ "EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
@@ -81,7 +82,7 @@ httpRequest.request(
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
} else {
- console.info('error:' + JSON.stringify(err));
+ console.error('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
@@ -91,12 +92,12 @@ httpRequest.request(
);
```
-## How to Develop request2 APIs
+## How to Develop requestInStream APIs
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Depending on your need, call **on()** of the **HttpRequest** object to subscribe to HTTP response header events as well as events indicating receiving of HTTP streaming responses, progress of receiving HTTP streaming responses, and completion of receiving HTTP streaming responses.
-4. Call **request2()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
+4. Call **requestInStream()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned response code as needed.
6. Call **off()** of the **HttpRequest** object to unsubscribe from the related events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
@@ -122,11 +123,11 @@ httpRequest.on('dataEnd', () => {
console.info('No more data in response, data receive end');
});
// Subscribe to events indicating progress of receiving HTTP streaming responses.
-httpRequest.on('dataProgress', (data) => {
- console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
+httpRequest.on('dataReceiveProgress', (data) => {
+ console.log("dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
});
-httpRequest.request2(
+httpRequest.requestInStream(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
@@ -146,14 +147,14 @@ httpRequest.request2(
readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => {
- console.info('error:' + JSON.stringify(err));
+ console.error('error:' + JSON.stringify(err));
console.info('ResponseCode :' + JSON.stringify(data));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Unregister the observer for events indicating receiving of HTTP streaming responses.
httpRequest.off('dataReceive');
// Unregister the observer for events indicating progress of receiving HTTP streaming responses.
- httpRequest.off('dataProgress');
+ httpRequest.off('dataReceiveProgress');
// Unregister the observer for events indicating completion of receiving HTTP streaming responses.
httpRequest.off('dataEnd');
// Call the destroy() method to release resources after HttpRequest is complete.
@@ -161,10 +162,3 @@ httpRequest.request2(
}
);
```
-
-## Samples
-
-The following sample is provided to help you better understand how to develop the HTTP data request feature:
-
-- [`Http`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
-- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md
index b9bbb0608dfb83ba6d2198b063e68c4b324bbd88..14016ef5da297361bd4a17a3d278357060590784 100644
--- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md
+++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md
@@ -1,6 +1,6 @@
# IPC & RPC Development Guidelines
-## When to Use
+## Overview
IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices.
diff --git a/en/application-dev/connectivity/net-connection-manager.md b/en/application-dev/connectivity/net-connection-manager.md
index fba108e73cd8e5e3dd81a43880cf25a54aee6ee5..f3b945ab0970786000ab8b04adfe90592a11e0d1 100644
--- a/en/application-dev/connectivity/net-connection-manager.md
+++ b/en/application-dev/connectivity/net-connection-manager.md
@@ -1,10 +1,11 @@
# Network Connection Management
-## Introduction
+## Overview
The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
> **NOTE**
+>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md).
## Basic Concepts
diff --git a/en/application-dev/connectivity/net-ethernet.md b/en/application-dev/connectivity/net-ethernet.md
index 18f20a7fd7e1a4c9516386c543c9521522df5f66..76ae1ee28078520b9d70796f71fd2b9236f47959 100644
--- a/en/application-dev/connectivity/net-ethernet.md
+++ b/en/application-dev/connectivity/net-ethernet.md
@@ -1,10 +1,11 @@
# Ethernet Connection
-## Introduction
+## Overview
The Ethernet Connection module allows a device to access the Internet through a network cable. After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode.
> **NOTE**
+>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md).
## **Constraints**
diff --git a/en/application-dev/connectivity/net-mdns.md b/en/application-dev/connectivity/net-mdns.md
index de7982a5c03908a70e4005bdc5fbea3584c435f5..75da959da8c4b1fc55aa0afca1cf0dcd945b86bb 100644
--- a/en/application-dev/connectivity/net-mdns.md
+++ b/en/application-dev/connectivity/net-mdns.md
@@ -1,6 +1,6 @@
# MDNS Management
-## Introduction
+## Overview
Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN.
- Local service: a service provider on a LAN, for example, a printer or scanner.
diff --git a/en/application-dev/connectivity/net-sharing.md b/en/application-dev/connectivity/net-sharing.md
index 4072217d9ced5d99b2052b5db8ccb8333fcb7023..f2b2e6ac21362691ede111db8b16316fa9fd32cb 100644
--- a/en/application-dev/connectivity/net-sharing.md
+++ b/en/application-dev/connectivity/net-sharing.md
@@ -1,10 +1,11 @@
# Network Sharing
-## Introduction
+## Overview
The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**
+>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md).
## Basic Concepts
diff --git a/en/application-dev/connectivity/net-statistics.md b/en/application-dev/connectivity/net-statistics.md
index 47ec62ff156448b3214885176c30b2f76d77b76c..6df8800dd479b48c32619514b8e6b90d5c776330 100644
--- a/en/application-dev/connectivity/net-statistics.md
+++ b/en/application-dev/connectivity/net-statistics.md
@@ -1,6 +1,6 @@
# Traffic Management
-## Introduction
+## Overview
The traffic management module allows you to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID).
@@ -11,6 +11,7 @@ Its functions include:
- Subscribing to traffic change events by NIC or UID
> **NOTE**
+>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-statistics.md).
The following describes the development procedure specific to each application scenario.
diff --git a/en/application-dev/connectivity/net-vpn.md b/en/application-dev/connectivity/net-vpn.md
index adf38f9676f29937532579e0bbdb4a94467095f3..a93b00b932bdec33de7cb45764474c163ed456ce 100644
--- a/en/application-dev/connectivity/net-vpn.md
+++ b/en/application-dev/connectivity/net-vpn.md
@@ -5,6 +5,7 @@
A virtual private network (VPN) is a dedicated network established on a public network. On a VPN, the connection between any two nodes does not have an end-to-end physical link required by the traditional private network. Instead, user data is transmitted over a logical link because a VPN is a logical network deployed over the network platform (such as the Internet) provided by the public network service provider.
> **NOTE**
+>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-vpn.md).
The following describes the development procedure specific to each application scenario.
diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md
index 9dda8b4e4c0ac6931ea75ad706fef76c9fb3c0a3..fe8ab1f141e3525de46985ba113eee364adac723 100644
--- a/en/application-dev/connectivity/socket-connection.md
+++ b/en/application-dev/connectivity/socket-connection.md
@@ -1,6 +1,6 @@
# Socket Connection
-## Introduction
+## Overview
The Socket Connection module allows an application to transmit data over a socket connection through the TCP, UDP, or TLS protocol.
diff --git a/en/application-dev/connectivity/subscribe-remote-state.md b/en/application-dev/connectivity/subscribe-remote-state.md
index 5b21750ba8b56fefcb10a5fff653d7512765c279..d23385e44752cb0945217eddc74117202ca38c5f 100755
--- a/en/application-dev/connectivity/subscribe-remote-state.md
+++ b/en/application-dev/connectivity/subscribe-remote-state.md
@@ -1,5 +1,7 @@
# Subscribing to State Changes of a Remote Object
+## Overview
+
IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
## When to Use
diff --git a/en/application-dev/connectivity/websocket-connection.md b/en/application-dev/connectivity/websocket-connection.md
index 4c373011c45be18183e4c622c3e7e35b97198a24..1b162256db5cad28aa50ca6989625f9191fb2257 100644
--- a/en/application-dev/connectivity/websocket-connection.md
+++ b/en/application-dev/connectivity/websocket-connection.md
@@ -1,6 +1,6 @@
# WebSocket Connection
-## When to Use
+## Overview
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
diff --git a/en/application-dev/dfx/Readme-EN.md b/en/application-dev/dfx/Readme-EN.md
index 5a1b6326bae1ecb94ef7fe8d9e4cfe2cdf2c6c56..c40f752d8f85e8894eb725965f50a7614dddef36 100644
--- a/en/application-dev/dfx/Readme-EN.md
+++ b/en/application-dev/dfx/Readme-EN.md
@@ -1,7 +1,6 @@
# DFX
- [Development of Application Event Logging](hiappevent-guidelines.md)
-- [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- [HiLog Development (Native)](hilog-guidelines.md)
- Performance Tracing
diff --git a/en/application-dev/dfx/appfreeze-guidelines.md b/en/application-dev/dfx/appfreeze-guidelines.md
index 05b52c4d8070386ec350701cefb2c6b63ef67d55..4984c95e215fe832f59abc3306bf777c6c313818 100644
--- a/en/application-dev/dfx/appfreeze-guidelines.md
+++ b/en/application-dev/dfx/appfreeze-guidelines.md
@@ -1,6 +1,6 @@
# Application Freeze (appfreeze) Log Analysis
-## Introduction
+## Overview
Application freeze (appfreeze) means that an application does not respond to user operations (for example, clicking) within a given period of time. OpenHarmony provides a mechanism for detecting appfreeze faults and generates appfreeze logs for fault analysis.
diff --git a/en/application-dev/dfx/apprecovery-guidelines.md b/en/application-dev/dfx/apprecovery-guidelines.md
index 284de5ca6d5f6027f2cce975a29b3259b2778021..9548404b3b359ad3f6fbe6778e0ddaeb374cc2ec 100644
--- a/en/application-dev/dfx/apprecovery-guidelines.md
+++ b/en/application-dev/dfx/apprecovery-guidelines.md
@@ -1,6 +1,6 @@
# Application Recovery Development
-## When to Use
+## Overview
During application running, some unexpected behaviors are inevitable. For example, unprocessed exceptions and errors are thrown, and the call or running constraints of the recovery framework are violated.
@@ -99,9 +99,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
- Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback. For details about its usage, see [errorManager](../reference/apis/js-apis-app-ability-errorManager.md).
```ts
- var registerId = -1;
- var callback = {
- onUnhandledException(errMsg) {
+ export let abilityWant : Want // file1
+
+ import * as G form "../file1"
+ let registerId = -1;
+ let callback: Callback = {
+ onUnhandledException(errMsg: string): void {
console.log(errMsg);
appRecovery.saveAppState();
appRecovery.restartApp();
@@ -112,7 +115,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate")
- globalThis.registerObserver = (() => {
+ G.registerObserver = (() => {
registerId = errorManager.on('error', callback);
})
@@ -138,13 +141,16 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state,
After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onCreate(want, launchParam)** of **MainAbility** is called, and the saved data is in **parameters** of **want**.
```ts
+export let abilityWant : Want // file1
+
+import * as GlobalWant form "../file1"
storage: LocalStorage
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
- globalThis.abilityWant = want;
+ GlobalWant.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage();
- let recoveryData = want.parameters["myData"];
+ let recoveryData: string = want.parameters["myData"];
this.storage.setOrCreate("myData", recoveryData);
this.context.restoreWindowStage(this.storage);
}
@@ -154,12 +160,15 @@ onCreate(want, launchParam) {
- Unregister the **ErrorObserver** callback.
```ts
+export let abilityWant : Want // file1
+
+import * as G form "../file1"
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy")
- globalThis.unRegisterObserver = (() => {
- errorManager.off('error', registerId, (err) => {
+ G.unRegisterObserver = (() => {
+ errorManager.off(type: 'error', registerId: number, (err:Error) => {
console.error("[Demo] err:", err);
});
})
@@ -171,20 +180,22 @@ onWindowStageDestroy() {
This is triggered by the recovery framework. You do not need to register an **ErrorObserver** callback. You only need to implement **onSaveState** for application state saving and **onCreate** for data restore.
```ts
+export let abilityWant : Want // file1
+
+import * as GlobalWant form "../file1"
export default class MainAbility extends Ability {
- storage: LocalStorage
- onCreate(want, launchParam) {
+ onCreate(want: Want, launchParam:AbilityConstant.LaunchParam):void {
console.log("[Demo] MainAbility onCreate")
- globalThis.abilityWant = want;
+ GlobalWant.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage();
- let recoveryData = want.parameters["myData"];
- this.storage.setOrCreate("myData", recoveryData);
+ let recoveryData: string = want.parameters["myData"];
+ this.storage.setOrCreate("myData", recoveryData);
this.context.restoreWindowStage(this.storage);
}
}
- onSaveState(state, wantParams) {
+ onSaveState(state: AbilityConstant.StateType, wantParams: { [key: string]: Object }) : AbilityConstant.OnSaveResult{
// Ability has called to save app data
console.log("[Demo] MainAbility onSaveState")
wantParams["myData"] = "my1234567";
diff --git a/en/application-dev/dfx/cppcrash-guidelines.md b/en/application-dev/dfx/cppcrash-guidelines.md
index c3ca07a4dc3a069272d89986329c2cbe103a45cb..15136518788324e23ac46c8c8b5bba327c03ea7a 100644
--- a/en/application-dev/dfx/cppcrash-guidelines.md
+++ b/en/application-dev/dfx/cppcrash-guidelines.md
@@ -1,6 +1,6 @@
# Process Crash (cppcrash) Log Analysis
-## Introduction
+## Overview
A process crash refers to a C/C++ runtime crash. The FaultLogger module of OpenHarmony provides capabilities such as process crash detection, log collection, log storage, and log reporting, helping you to locate faults more effectively.
diff --git a/en/application-dev/dfx/errormanager-guidelines.md b/en/application-dev/dfx/errormanager-guidelines.md
index 4679cfcfc78893590fe73eab770e49fc68a1a828..14d7735d731d0fb2eb3fc41f61de58f5de7f4e02 100644
--- a/en/application-dev/dfx/errormanager-guidelines.md
+++ b/en/application-dev/dfx/errormanager-guidelines.md
@@ -1,6 +1,6 @@
# Development of Error Manager
-## When to Use
+## Overview
If coding specification issues or errors exist in the code of an application, the application may encounter unexpected errors, for example, uncaught exceptions or application lifecycle timeouts, while it is running. In such a case, the application may exit unexpectedly. Error logs, however, are usually stored on users' local storage, making it inconvenient to locate faults. With the APIs provided by the **errorManager** module, your application will be able to report related errors and logs to your service platform for fault locating before it exits.
diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md
index d21d4e3fa9e0fa0b795c82e7157cd6215eab5e0c..6b0f4dd1cb8ec36288514e3f8767770f4e30105b 100644
--- a/en/application-dev/dfx/hiappevent-guidelines.md
+++ b/en/application-dev/dfx/hiappevent-guidelines.md
@@ -1,6 +1,6 @@
# Development of Application Event Logging
-## Introduction
+## Overview
A traditional log system aggregates log information generated by all applications running on the entire device, making it difficult to identify key information in the log. Therefore, an effective logging mechanism is needed to evaluate mission-critical information, for example, number of visits, number of daily active users, user operation habits, and key factors that affect application usage.
diff --git a/en/application-dev/dfx/hilog-guidelines.md b/en/application-dev/dfx/hilog-guidelines.md
index 25b4a7f9cc5c92d9f20ed6582299d5dd65b937d0..45d46c01fb4c601241120ce9cf5d249bd0bc893f 100644
--- a/en/application-dev/dfx/hilog-guidelines.md
+++ b/en/application-dev/dfx/hilog-guidelines.md
@@ -1,6 +1,6 @@
# HiLog Development (Native)
-## 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.
diff --git a/en/application-dev/dfx/hitracechain-guidelines.md b/en/application-dev/dfx/hitracechain-guidelines.md
index affd260b0503f3c4f4c4b748d5911d94f7fef9e3..44e2da92dfbf985f27a275ac6e02e61a934d199e 100644
--- a/en/application-dev/dfx/hitracechain-guidelines.md
+++ b/en/application-dev/dfx/hitracechain-guidelines.md
@@ -1,6 +1,6 @@
# Development of Distributed Call Chain Tracing
-## Introduction
+## Overview
The hiTraceChain module provides APIs to implement call chain tracing throughout a service process. This can help you quickly obtain the run log for the call chain of a specified service process and locate faults in inter-device, inter-process, or inter-thread communications.
diff --git a/en/application-dev/dfx/hitracemeter-guidelines.md b/en/application-dev/dfx/hitracemeter-guidelines.md
index ed99e4e89d5b6fce3d5bd50ef8dedcfc32b04fb1..195aae4b2d98dd1ab950613c6c97ed07cfcfe98e 100644
--- a/en/application-dev/dfx/hitracemeter-guidelines.md
+++ b/en/application-dev/dfx/hitracemeter-guidelines.md
@@ -1,6 +1,6 @@
# Development of Performance Tracing (ArkTS)
-## Introduction
+## Overview
hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
@@ -21,7 +21,7 @@ hiTraceMeter provides APIs for system performance tracing. You can call the APIs
## Available APIs
-The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md).
+The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference]( ../reference/apis/js-apis-hitracemeter.md).
**APIs for performance tracing**
@@ -35,60 +35,16 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de
In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed.
-1. Create a JS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **js** > **default** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. The sample code is as follows:
-
- ```js
- import hiTraceMeter from '@ohos.hiTraceMeter'
-
- export default {
- data: {
- title: ""
- },
- onInit() {
- this.title = this.$t('strings.world');
-
- // Start trace tasks with the same name concurrently.
- hiTraceMeter.startTrace("business", 1);
- // Keep the service process running.
- console.log(`business running`);
- hiTraceMeter.startTrace("business", 2); // Start the second trace task with the same name while the first task is still running. The tasks are running concurrently and therefore their taskId must be different.
- // Keep the service process running.
- console.log(`business running`);
- hiTraceMeter.finishTrace("business", 1);
- // Keep the service process running.
- console.log(`business running`);
- hiTraceMeter.finishTrace("business", 2);
-
- // Start trace tasks with the same name in serial mode.
- hiTraceMeter.startTrace("business", 1);
- // Keep the service process running.
- console.log(`business running`);
- hiTraceMeter.finishTrace("business", 1); // End the first trace task.
- // Keep the service process running.
- console.log(`business running`);
- hiTraceMeter.startTrace("business", 1); // Start the second trace task with the same name in serial mode.
- // Keep the service process running.
- console.log(`business running`);
-
- let traceCount = 3;
- hiTraceMeter.traceByValue("myTestCount", traceCount);
- traceCount = 4;
- hiTraceMeter.traceByValue("myTestCount", traceCount);
- hiTraceMeter.finishTrace("business", 1);
- }
- }
- ```
-
-2. Create an ArkTs application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows:
-
+1. Create an ArkTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows:
+
```ts
import hitrace from '@ohos.hiTraceMeter';
-
+
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
-
+
build() {
Row() {
Column() {
@@ -97,7 +53,7 @@ In this example, distributed call chain tracing begins when the application star
.fontWeight(FontWeight.Bold)
.onClick(() => {
this.message = 'Hello ArkUI';
-
+
// Start trace tasks with the same name concurrently.
hitrace.startTrace("HITRACE_TAG_APP", 1001);
// Keep the service process running.
@@ -107,7 +63,7 @@ In this example, distributed call chain tracing begins when the application star
hitrace.startTrace("HITRACE_TAG_APP", 1002);
// Keep the service process running.
console.log(`HITRACE_TAG_APP running`);
-
+
hitrace.finishTrace("HITRACE_TAG_APP", 1001);
hitrace.finishTrace("HITRACE_TAG_APP", 1002);
@@ -143,7 +99,7 @@ In this example, distributed call chain tracing begins when the application star
```
3. Click the run button on the application page. Then, run the following commands in sequence in shell:
-
+
```shell
hdc shell
hitrace --trace_begin app
diff --git a/en/application-dev/dfx/hitracemeter-native-guidelines.md b/en/application-dev/dfx/hitracemeter-native-guidelines.md
index bb0274f7c4077b016061430250e7a949cf826864..912ec1c5f87b6ebfdd6f14cb4da568e251501af2 100644
--- a/en/application-dev/dfx/hitracemeter-native-guidelines.md
+++ b/en/application-dev/dfx/hitracemeter-native-guidelines.md
@@ -1,6 +1,6 @@
# Development of Performance Tracing (Native)
-## Introduction
+## Overview
hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
> **NOTE**
diff --git a/en/application-dev/faqs/faqs-graphics.md b/en/application-dev/faqs/faqs-graphics.md
index 345cbf83c5b2976c810e78237cb2587eaa4b1404..4cc8b196d5b8210e2360a598c1b24fdc0edb891b 100644
--- a/en/application-dev/faqs/faqs-graphics.md
+++ b/en/application-dev/faqs/faqs-graphics.md
@@ -21,42 +21,6 @@ try {
}
```
-## How do I hide the status bar to get the immersive effect?
-
-Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
-
-**Solution**
-
-1. Use **onWindowStageCreate** to obtain a **windowClass** object.
-
- ```
- onWindowStageCreate(windowStage) {
- // When the main window is created, set the main page for this ability.
- console.log("[Demo] MainAbility onWindowStageCreate")
- windowStage.getMainWindow((err, data) => {
- if (err.code) {
- console.error('Failed to obtain the main window.')
- return;
- }
- // Obtain a windowClass object.
- globalThis.windowClass = data;
- })
- }
- ```
-
-2. Enable the full-screen mode for the window and hide the status bar.
-
- ```
- globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => {
- if (err.code) {
- console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err));
- return;
- }
- console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
- });
- ```
-
-
## How do I obtain the window width and height?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model)
diff --git a/en/application-dev/media/using-avrecorder-for-recording.md b/en/application-dev/media/using-avrecorder-for-recording.md
index 71ab8557df470671088adfaa0473a6448d935881..aa204062795339cf425cb95d9726001f56b66d9a 100644
--- a/en/application-dev/media/using-avrecorder-for-recording.md
+++ b/en/application-dev/media/using-avrecorder-for-recording.md
@@ -20,11 +20,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
import media from '@ohos.multimedia.media';
- let avRecorder = undefined;
- media.createAVRecorder().then((recorder) => {
+ let avRecorder: media.AVRecorder;
+ media.createAVRecorder().then((recorder: media.AVRecorder) => {
avRecorder = recorder;
- }, (err) => {
- console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`);
+ }, (error: Error) => {
+ console.error(`createAVRecorder failed`);
})
```
@@ -37,13 +37,13 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
// Callback function for state changes.
- avRecorder.on('stateChange', (state, reason) => {
+ avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.log(`current state is ${state}`);
// You can add the action to be performed after the state is switched.
})
// Callback function for errors.
- avRecorder.on('error', (err) => {
+ avRecorder.on('error', (err: BusinessError) => {
console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`);
})
```
@@ -62,21 +62,21 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
- let avProfile = {
+ let avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // Audio bit rate.
audioChannels: 2, // Number of audio channels.
audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported.
audioSampleRate: 48000, // Audio sampling rate.
fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported.
}
- let avConfig = {
+ let avConfig: media.AVRecorderConfig = {
audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used.
profile: avProfile,
url: 'fd://35', // Obtain the file descriptor of the created audio file by referring to the sample code in Application File Access and Management.
}
avRecorder.prepare(avConfig).then(() => {
console.log('Invoke prepare succeeded.');
- }, (err) => {
+ }, (err: BusinessError) => {
console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`);
})
```
@@ -100,17 +100,17 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
import media from '@ohos.multimedia.media';
-
+import { BusinessError } from '@ohos.base';
export class AudioRecorderDemo {
- private avRecorder;
- private avProfile = {
+ private avRecorder: media.AVRecorder;
+ private avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // Audio bit rate.
audioChannels: 2, // Number of audio channels.
audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported.
audioSampleRate: 48000, // Audio sampling rate.
fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported.
};
- private avConfig = {
+ private avConfig: media.AVRecorderConfig = {
audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used.
profile: this.avProfile,
url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
@@ -119,11 +119,11 @@ export class AudioRecorderDemo {
// Set AVRecorder callback functions.
setAudioRecorderCallback() {
// Callback function for state changes.
- this.avRecorder.on('stateChange', (state, reason) => {
+ this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.log(`AudioRecorder current state is ${state}`);
})
// Callback function for errors.
- this.avRecorder.on('error', (err) => {
+ this.avRecorder.on('error', (err: BusinessError) => {
console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`);
})
}
diff --git a/en/application-dev/media/video-recording.md b/en/application-dev/media/video-recording.md
index 8eabb4e1aad61f954135832ff2e5439912acdb34..d2f5affc31bca6badec8329a918a2aed2e498779 100644
--- a/en/application-dev/media/video-recording.md
+++ b/en/application-dev/media/video-recording.md
@@ -24,10 +24,10 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
import media from '@ohos.multimedia.media'
- let avRecorder
- media.createAVRecorder().then((recorder) => {
+ let avRecorder: media.AVRecorder;
+ media.createAVRecorder().then((recorder: media.AVRecorder) => {
avRecorder = recorder
- }, (error) => {
+ }, (error: Error) => {
console.error('createAVRecorder failed')
})
```
@@ -40,11 +40,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
// Callback function for state changes.
- avRecorder.on('stateChange', (state, reason) => {
+ avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.info('current state is: ' + state);
})
// Callback function for errors.
- avRecorder.on('error', (err) => {
+ avRecorder.on('error', (err: BusinessError) => {
console.error('error happened, error message is ' + err);
})
```
@@ -62,7 +62,7 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
> - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../file-management/app-file-access.md).
```ts
- let avProfile = {
+ let avProfile: media.AVRecorderProfile = {
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
videoBitrate: 200000, // Video bit rate.
videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported.
@@ -70,15 +70,15 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
videoFrameHeight: 480, // Video frame height.
videoFrameRate: 30 // Video frame rate.
}
- let avConfig = {
+ let avConfig: media.AVRecorderConfig = {
videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
- profile : this.avProfile,
+ profile : avProfile,
url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
rotation: 0, // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270.
}
avRecorder.prepare(avConfig).then(() => {
console.info('avRecorder prepare success')
- }, (error) => {
+ }, (error: Error) => {
console.error('avRecorder prepare failed')
})
```
@@ -90,9 +90,9 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
The video data collection module obtains the surface based on the surface ID and transmits video data to the AVRecorder through the surface. Then the AVRecorder processes the video data.
```ts
- avRecorder.getInputSurface().then((surfaceId) => {
+ avRecorder.getInputSurface().then((surfaceId: string) => {
console.info('avRecorder getInputSurface success')
- }, (error) => {
+ }, (error: Error) => {
console.error('avRecorder getInputSurface failed')
})
```
@@ -123,19 +123,20 @@ Refer to the sample code below to complete the process of starting, pausing, res
```ts
import media from '@ohos.multimedia.media'
+import { BusinessError } from '@ohos.base';
const TAG = 'VideoRecorderDemo:'
export class VideoRecorderDemo {
- private avRecorder;
- private videoOutSurfaceId;
- private avProfile = {
+ private avRecorder: media.AVRecorder;
+ private videoOutSurfaceId: string;
+ private avProfile: media.AVRecorderProfile = {
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
- videoBitrate : 100000, // Video bit rate.
+ videoBitrate: 100000, // Video bit rate.
videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported.
videoFrameWidth: 640, // Video frame width.
videoFrameHeight: 480, // Video frame height.
videoFrameRate: 30 // Video frame rate.
}
- private avConfig = {
+ private avConfig: media.AVRecorderConfig = {
videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
profile : this.avProfile,
url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
@@ -145,11 +146,11 @@ export class VideoRecorderDemo {
// Set AVRecorder callback functions.
setAvRecorderCallback() {
// Callback function for state changes.
- this.avRecorder.on('stateChange', (state, reason) => {
+ this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.info(TAG + 'current state is: ' + state);
})
// Callback function for errors.
- this.avRecorder.on('error', (err) => {
+ this.avRecorder.on('error', (err: BusinessError) => {
console.error(TAG + 'error ocConstantSourceNode, error message is ' + err);
})
}
@@ -188,7 +189,7 @@ export class VideoRecorderDemo {
// 5. Start the camera stream output.
await this.startCameraOutput();
// 6. Start recording.
- await this.videoRecorder.start();
+ await this.avRecorder.start();
}
// Process of pausing recording.
diff --git a/en/application-dev/napi/neural-network-runtime-guidelines.md b/en/application-dev/napi/neural-network-runtime-guidelines.md
index 344ae4f1d623f67fcd3b093e8dec6653b806c4f2..974ccc5bafbfe7169034924ba27d0eb3c91606a8 100644
--- a/en/application-dev/napi/neural-network-runtime-guidelines.md
+++ b/en/application-dev/napi/neural-network-runtime-guidelines.md
@@ -1,4 +1,4 @@
-# Connecting the Neural Network Runtime to an AI Inference Framework
+# Development Guide for Connecting the Neural Network Runtime to an AI Inference Framework
## When to Use
@@ -19,8 +19,7 @@ The environment requirements for the Neural Network Runtime are as follows:
- Development environment: Ubuntu 18.04 or later.
- Access device: a standard device running OpenHarmony. The built-in hardware accelerator driver has been connected to the Neural Network Runtime through an HDI API.
-The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications.
-
+The Neural Network Runtime is opened to external systems through OpenHarmony Native APIs. Therefore, you need to use the Native development suite of the OpenHarmony to compile Neural Network Runtime applications.
### Environment Setup
@@ -33,7 +32,6 @@ unzip native-linux-{version number}.zip
```
The directory structure after decompression is as follows. The content in the directory may vary depending on version iteration. Use the Native APIs of the latest version.
-
```text
native/
─ ─ build // Cross-compilation toolchain
@@ -488,4 +486,4 @@ The development process of the Neural Network Runtime consists of three phases:
```shell
rm /data/local/tmp/*nncache
- ```
\ No newline at end of file
+ ```
diff --git a/en/application-dev/quick-start/arkts-appstorage.md b/en/application-dev/quick-start/arkts-appstorage.md
index 50cbcf6aa0854fc901eb6bbf80b41da7c990eaa1..c1ebb9c91252d5b75a96b837e6f07bd2f1053a56 100644
--- a/en/application-dev/quick-start/arkts-appstorage.md
+++ b/en/application-dev/quick-start/arkts-appstorage.md
@@ -23,8 +23,7 @@ Selected state attributes of AppStorage can be synced with different data source
As mentioned above, if you want to establish a binding between AppStorage and a custom component, you'll need the \@StorageProp and \@StorageLink decorators. Use \@StorageProp(key) or \@StorageLink(key) to decorate variables in the component, where **key** identifies the attribute in AppStorage.
-When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Local initialization is mandatory. If an attribute with the given key is missing from AppStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in AppStorage depends on the application logic.)
-
+When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Whether the attribute with the given key exists in AppStorage depends on the application logic. This means that the attribute with the given key may be missing from AppStorage. In light of this, local initialization is mandatory for the \@StorageProp(key)/\@StorageLink(key) decorated variable.
By decorating a variable with \@StorageProp(key), a one-way data synchronization is established with the attribute with the given key in AppStorage. A local change can be made, but it will not be synchronized to AppStorage. An update to the attribute with the given key in AppStorage will overwrite local changes.
@@ -193,9 +192,85 @@ struct CompA {
}
```
-### Persistent Subscription and Callback
+### Unrecommended: Using @StorageLink to Implement Event Notification
+
+Compared with the common mechanism for event notification, the two-way synchronization mechanism of @StorageLink and AppStorage is far less cost efficient and therefore not recommended. This is because AppStorage stores UI-related data, and its changes will cause costly UI refresh.
+
+In the following example, any tap event in the **TapImage** component will trigger a change of the **tapIndex** attribute. As @StorageLink establishes a two-way data synchronization with AppStorage, the local change is synchronized to AppStorage. As a result, all visible custom components owning the **tapIndex** attribute bound to AppStorage are notified to refresh the UI.
+
+
+```ts
+// xxx.ets
+class ViewData {
+ title: string;
+ uri: Resource;
+ color: Color = Color.Black;
+
+ constructor(title: string, uri: Resource) {
+ this.title = title;
+ this.uri = uri
+ }
+}
+
+@Entry
+@Component
+struct Gallery2 {
+ dataList: Array = [new ViewData('flower', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon')), new ViewData('OMG', $r('app.media.icon'))]
+ scroller: Scroller = new Scroller()
+
+ build() {
+ Column() {
+ Grid(this.scroller) {
+ ForEach(this.dataList, (item: ViewData, index?: number) => {
+ GridItem() {
+ TapImage({
+ uri: item.uri,
+ index: index
+ })
+ }.aspectRatio(1)
+
+ }, (item: ViewData, index?: number) => {
+ return JSON.stringify(item) + index;
+ })
+ }.columnsTemplate('1fr 1fr')
+ }
+
+ }
+}
+
+@Component
+export struct TapImage {
+ @StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1;
+ @State tapColor: Color = Color.Black;
+ private index: number;
+ private uri: Resource;
+
+ // Check whether the component is selected.
+ onTapIndexChange() {
+ if (this.tapIndex >= 0 && this.index === this.tapIndex) {
+ console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, red`)
+ this.tapColor = Color.Red;
+ } else {
+ console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, black`)
+ this.tapColor = Color.Black;
+ }
+ }
-The persistent subscription and callback can help reduce overhead and enhance code readability.
+ build() {
+ Column() {
+ Image(this.uri)
+ .objectFit(ImageFit.Cover)
+ .onClick(() => {
+ this.tapIndex = this.index;
+ })
+ .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor })
+ }
+
+ }
+}
+```
+
+To implement event notification with less overhead and higher code readability, use **emit** instead, with which you can subscribe to an event and receive event callback.
```ts
@@ -294,10 +369,9 @@ export struct TapImage {
}
```
-The following example uses the message mechanism to subscribe to events. Because this mechanism can result in a large number of nodes to listen for and a long implementation time, it is not recommended.
-
+The preceding notification logic is simple. It can be simplified into a ternary expression as follows:
-```ts
+```
// xxx.ets
class ViewData {
title: string;
@@ -338,22 +412,11 @@ struct Gallery2 {
@Component
export struct TapImage {
- @StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1;
+ @StorageLink('tapIndex') tapIndex: number = -1;
@State tapColor: Color = Color.Black;
private index: number;
private uri: Resource;
- // Check whether the component is selected.
- onTapIndexChange() {
- if (this.tapIndex >= 0 && this.index === this.tapIndex) {
- console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, red`)
- this.tapColor = Color.Red;
- } else {
- console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, black`)
- this.tapColor = Color.Black;
- }
- }
-
build() {
Column() {
Image(this.uri)
@@ -361,14 +424,18 @@ export struct TapImage {
.onClick(() => {
this.tapIndex = this.index;
})
- .border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor })
+ .border({
+ width: 5,
+ style: BorderStyle.Dotted,
+ color: (this.tapIndex >= 0 && this.index === this.tapIndex) ? Color.Red : Color.Black
+ })
}
-
}
}
```
+
## Restrictions
When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) and [Environment](arkts-environment.md), pay attention to the following:
@@ -377,5 +444,5 @@ When using AppStorage together with [PersistentStorage](arkts-persiststorage.md)
- A call to **Environment.EnvProp()** after creating the attribute in AppStorage will fail. This is because AppStorage already has an attribute with the same name, and the environment variable will not be written into AppStorage. Therefore, you are advised not to use the preset environment variable name in AppStorage.
-- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Persistent Subscription and Callback](#persistent-subscription-and-callback).
+- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Unrecommended: Using @StorageLink to Implement Event Notification](#unrecommended-using-storagelink-to-implement-event-notification).
diff --git a/en/application-dev/quick-start/arkts-builder.md b/en/application-dev/quick-start/arkts-builder.md
index 80a262fcd97a0dcf6808bf8cdb84bf78849cb0e1..ab1c53b103db98c49fa42a21f69adff6ea32b86b 100644
--- a/en/application-dev/quick-start/arkts-builder.md
+++ b/en/application-dev/quick-start/arkts-builder.md
@@ -21,14 +21,14 @@ Syntax:
```ts
-@Builder myBuilderFunction({ ... })
+@Builder MyBuilderFunction({ ... })
```
Usage:
```ts
-this.myBuilderFunction({ ... })
+this.MyBuilderFunction({ ... })
```
- Defining one or more custom builder (\@Builder decorated) functions inside a custom component is allowed. Such a custom builder function can be considered as a private, special type of member functions of that component.
@@ -66,7 +66,7 @@ There are two types of parameter passing for custom builder functions: [by-value
- The parameter type must be the same as the declared parameter type. The **undefined** or **null** constants as well as expressions evaluating to these values are not allowed.
-- All parameters are immutable inside the custom builder function. If mutability and synchronization of the mutation is required, the custom builder should be replaced by a custom component with a [@Link](arkts-link.md) decorated variable.
+- All parameters are immutable inside the@Builder decorated function.
- The \@Builder function body follows the same [syntax rules](arkts-create-custom-components.md#build-function) as the **build** function.
diff --git a/en/application-dev/quick-start/arkts-environment.md b/en/application-dev/quick-start/arkts-environment.md
index 2f0718290460508c4510acc298fa85c855bbec26..ac80bd54590b0dffdfa6b3bf82351d27f09917a1 100644
--- a/en/application-dev/quick-start/arkts-environment.md
+++ b/en/application-dev/quick-start/arkts-environment.md
@@ -15,12 +15,11 @@ Environment is a singleton object created by the ArkUI framework at application
- Use **Environment.EnvProp** to save the environment variables of the device to AppStorage.
```ts
- // Save the language code of the device to AppStorage. The default value is en.
- // Whenever its value changes in the device environment, it will update its value in AppStorage.
+ // Save languageCode to AppStorage. The default value is en.
Environment.EnvProp('languageCode', 'en');
```
-- To keep a component variable updated with changes in the device environment, this variable should be decorated with \@StorageProp.
+- Decorate the variables with \@StorageProp to link them with components.
```ts
@StorageProp('languageCode') lang : string = 'en';
@@ -29,6 +28,7 @@ Environment is a singleton object created by the ArkUI framework at application
The chain of updates is as follows: Environment > AppStorage > Component.
> **NOTE**
+>
> An \@StorageProp decorated variable can be locally modified, but the change will not be updated to AppStorage. This is because the environment variable parameters are read-only to the application.
@@ -69,3 +69,29 @@ if (lang.get() === 'en') {
console.info('Hello!');
}
```
+
+
+## Restrictions
+
+
+Environment can be called only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified. If Environment is called otherwise, no device environment data can be obtained.
+
+
+```ts
+// EntryAbility.ts
+import UIAbility from '@ohos.app.ability.UIAbility';
+import window from '@ohos.window';
+
+export default class EntryAbility extends UIAbility {
+ onWindowStageCreate(windowStage: window.WindowStage) {
+ windowStage.loadContent('pages/Index');
+ let window = windowStage.getMainWindow()
+ window.then(window => {
+ let uicontext = window.getUIContext()
+ uicontext.runScopedTask(() => {
+ Environment.EnvProp('languageCode', 'en');
+ })
+ })
+ }
+}
+```
diff --git a/en/application-dev/quick-start/arkts-observed-and-objectlink.md b/en/application-dev/quick-start/arkts-observed-and-objectlink.md
index 61f1bd8ae476f5984405eed97fb127161bb131e2..a7e47fb63e57896158a6a03aaa6896bea7ac644f 100644
--- a/en/application-dev/quick-start/arkts-observed-and-objectlink.md
+++ b/en/application-dev/quick-start/arkts-observed-and-objectlink.md
@@ -162,6 +162,26 @@ class ClassB {
this.a = a;
}
}
+
+@Observed
+class ClassD {
+ public c: ClassC;
+
+ constructor(c: ClassC) {
+ this.c = c;
+ }
+}
+
+@Observed
+class ClassC extends ClassA {
+ public k: number;
+
+ constructor(k: number) {
+ // Invoke the parent class method to process k.
+ super(k);
+ this.k = k;
+ }
+}
```
@@ -169,60 +189,64 @@ class ClassB {
```ts
@Component
-struct ViewA {
- label: string = 'ViewA1';
- @ObjectLink a: ClassA;
+struct ViewC {
+ label: string = 'ViewC1';
+ @ObjectLink c: ClassC;
build() {
Row() {
- Button(`ViewA [${this.label}] this.a.c=${this.a.c} +1`)
- .onClick(() => {
- this.a.c += 1;
- })
- }
+ Column() {
+ Text(`ViewC [${this.label}] this.a.c = ${this.c.c}`)
+ .fontColor('#ffffffff')
+ .backgroundColor('#ff3fc4c4')
+ .height(50)
+ .borderRadius(25)
+ Button(`ViewC: this.c.c add 1`)
+ .backgroundColor('#ff7fcf58')
+ .onClick(() => {
+ this.c.c += 1;
+ console.log('this.c.c:' + this.c.c)
+ })
+ }
+ .width(300)
}
}
+}
@Entry
@Component
struct ViewB {
@State b: ClassB = new ClassB(new ClassA(0));
-
+ @State child : ClassD = new ClassD(new ClassC(0));
build() {
Column() {
- ViewA({ label: 'ViewA #1', a: this.b.a })
- ViewA({ label: 'ViewA #2', a: this.b.a })
-
- Button(`ViewB: this.b.a.c+= 1`)
- .onClick(() => {
- this.b.a.c += 1;
- })
- Button(`ViewB: this.b.a = new ClassA(0)`)
+ ViewC({ label: 'ViewC #3', c: this.child.c})
+ Button(`ViewC: this.child.c.c add 10`)
+ .backgroundColor('#ff7fcf58')
.onClick(() => {
- this.b.a = new ClassA(0);
- })
- Button(`ViewB: this.b = new ClassB(ClassA(0))`)
- .onClick(() => {
- this.b = new ClassB(new ClassA(0));
+ this.child.c.c += 10
+ console.log('this.child.c.c:' + this.child.c.c)
})
}
}
}
```
+The @Observed decorated **ClassC** class can observe changes in attributes inherited from the base class.
+
Event handlers in **ViewB**:
-- this.b.a = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes.
+- this.child.c = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes.
-- this.b.a.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink.
+- this.child.c.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink.
-Event handlers in **ViewA**:
+Event handle in **ViewC**:
-- this.a.c += 1: Changes to the \@ObjectLink decorated variable cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source.
+- this.c.c += 1: Changes to the \@ObjectLink decorated variable **a** cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source.
- The \@ObjectLink decorated variable is read-only. Assigning **this.a = new ClassA(...)** is not allowed. Once value assignment occurs, the reference to the data source is reset and the synchronization is interrupted.
@@ -297,7 +321,7 @@ struct ViewB {
2. ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] }): The preceding update changes the first element in the array. Therefore, the **ViewA** component instance bound to **this.arrA[0]** is updated.
- this.arrA.push(new ClassA(0)): The change of this state variable triggers two updates with different effects.
- 1. ForEach: The newly added Class A object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **View A** component instance.
+ 1. ForEach: The newly added **ClassA** object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **ViewA** component instance.
2. ViewA({ label: ViewA this.arrA[last], a: this.arrA[this.arrA.length-1] }): The last item of the array is changed. As a result, the second **View A** component instance is changed. For **ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] })**, a change to the array does not trigger a change to the array item, so the first **View A** component instance is not refreshed.
- this.arrA[Math.floor (this.arrA.length/2)].c: [@State](arkts-state.md#observed-changes) cannot observe changes at the second layer. However, as **ClassA** is decorated by \@Observed, the change of its attributes will be observed by \@ObjectLink.
diff --git a/en/application-dev/quick-start/arkts-persiststorage.md b/en/application-dev/quick-start/arkts-persiststorage.md
index fdbacd4235dcd50ea2777e8e3695227ff02be70c..21c854c26557e5fcd5027623b0429b625d6c9c91 100644
--- a/en/application-dev/quick-start/arkts-persiststorage.md
+++ b/en/application-dev/quick-start/arkts-persiststorage.md
@@ -24,7 +24,7 @@ Persistence of data is a relatively slow operation. Applications should avoid th
The preceding situations may overload the change process of persisted data. As a result, the PersistentStorage implementation may limit the change frequency of persisted attributes.
-PersistentStorage is associated with UIContext and can be called to persist data only when [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext) is specified. The context can be identified in [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask).
+PersistentStorage can be called to persist data only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified.
## Application Scenarios
diff --git a/en/application-dev/quick-start/arkts-rendering-control-foreach.md b/en/application-dev/quick-start/arkts-rendering-control-foreach.md
index 4c916bec86f9c9d22b9bdb60ca476f9cbdcd4846..dc6ae173f51df82fbc48f26df56368450fa6fa79 100644
--- a/en/application-dev/quick-start/arkts-rendering-control-foreach.md
+++ b/en/application-dev/quick-start/arkts-rendering-control-foreach.md
@@ -3,6 +3,9 @@
**ForEach** enables repeated content based on array-type data.
+> **NOTE**
+>
+> Since API version 9, this API is supported in ArkTS widgets.
## API Description
@@ -19,15 +22,15 @@ ForEach(
| Name | Type | Mandatory | Description |
| ------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| arr | Array | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.|
-| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. Each component and its child component list must be contained in parentheses.
**NOTE**
- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\** child component is allowed only when the parent container component of **ForEach** is **\**.
- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.
- The optional **index** parameter should only be specified in the function signature if used in its body.|
-| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.
**NOTE**
- Two items inside the same array must never work out the same ID.
- If **index** is not used, an item's ID must not change when the item's position within the array changes. However, if **index** is used, then the ID must change when the item is moved within the array.
- When an item is replaced by a new one (with a different value), the ID of the replaced and the ID of the new item must be different.
- When **index** is used in the build function, it should also be used in the ID generation function.
- The ID generation function is not allowed to mutate any component state.|
+| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. Each component and its child component list must be contained in parentheses.
**NOTE**
- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\** child component is allowed only when the parent container component of **ForEach** is **\**.
- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.
- The optional **index** parameter should only be specified in the function signature if used in its body.|
+| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.
**NOTE**
- Two items inside the same array must never work out the same ID.
- If **index** is not used, an item's ID must not change when the item's position within the array changes. However, if **index** is used, then the ID must change when the item is moved within the array.
- When an item is replaced by a new one (with a different value), the ID of the replaced and the ID of the new item must be different.
- When **index** is used in the build function, it should also be used in the ID generation function.
- The ID generation function is not allowed to mutate any component state.|
## Restrictions
- **ForEach** must be used in container components.
-- The type of the child component must be the one allowed inside the parent container component of **ForEach**.
+- The type of the child component must be the one allowed inside the parent container component of **ForEach**.
- The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**.
diff --git a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md
index b717abf0ad082e4ea7586cc8713596a08e7b3740..de2f146c7226f3a1ef3d61dad588c84b6cc2a1ab 100644
--- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md
+++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md
@@ -1,15 +1,13 @@
# @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)
-The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling.
-
-When developing an application, you can override the APIs of this module and add your own task logic to the APIs.
+The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling. You can override the APIs provided by this module. When a deferred task is triggered, the system calls back the application through the APIs and processes the task logic in the callback.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+>
> - The APIs of this module can be used only in the stage model.
-
## Modules to Import
```ts
@@ -36,7 +34,7 @@ Called when the system starts scheduling the deferred task.
| Name | Type | Mandatory | Description |
| ---- | ---------------------------------------- | ---- | -------------- |
-| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Target task.|
+| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Deferred task that starts.|
**Example**
@@ -60,7 +58,7 @@ Called when the system stops scheduling the deferred task.
| Name | Type | Mandatory | Description |
| ---- | ---------------------------------------- | ---- | -------------- |
-| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Target task.|
+| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Deferred task that stops.|
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md
index 5a4af7f39f321fc486a4e359b567666dc359135a..ff3fb9a3d6af1c9ab3250d892ad729dabb5220ad 100644
--- a/en/application-dev/reference/apis/js-apis-commonEvent.md
+++ b/en/application-dev/reference/apis/js-apis-commonEvent.md
@@ -12,6 +12,8 @@ The **CommonEvent** module provides common event capabilities, including the cap
```ts
import CommonEvent from '@ohos.commonEvent';
+import CommonEventManager from '@ohos.commonEventManager';
+import Base from '@ohos.base';
```
## Support
@@ -43,7 +45,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r
```ts
// Callback for common event publication
-function publishCB(err) {
+function publishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`publish failed, code is ${err.code}`);
} else {
@@ -80,14 +82,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca
```ts
// Attributes of a common event.
-let options = {
+let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event.
- data: "initial data";// Result data of the common event.
+ data: "initial data",// Result data of the common event.
isOrdered: true // The common event is an ordered one.
}
// Callback for common event publication
-function publishCB(err) {
+function publishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`publish failed, code is ${err.code}`);
} else {
@@ -125,7 +127,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb
```ts
// Callback for common event publication
-function publishCB(err) {
+function publishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`publishAsUser failed, code is ${err.code}`);
} else {
@@ -168,13 +170,13 @@ Publishes a common event with given attributes to a specific user. This API uses
```ts
// Attributes of a common event.
-let options = {
+let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event.
data: "initial data",// Result data of the common event.
}
// Callback for common event publication
-function publishCB(err) {
+function publishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`publishAsUser failed, code is ${err.code}`);
} else {
@@ -212,15 +214,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul
```ts
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
- events: ["event"]
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
+ events: ["event"]
};
// Callback for subscriber creation.
-function createCB(err, commonEventSubscriber) {
+function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
@@ -259,18 +261,18 @@ Creates a subscriber. This API uses a promise to return the result.
**Example**
```ts
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Create a subscriber.
-CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => {
+CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => {
console.info("createSubscriber");
subscriber = commonEventSubscriber;
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`createSubscriber failed, code is ${err.code}`);
});
```
@@ -297,15 +299,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th
**Example**
```ts
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for common event subscription.
-function subscribeCB(err, data) {
+function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err.code) {
console.error(`subscribe failed, code is ${err.code}`);
} else {
@@ -314,7 +316,7 @@ function subscribeCB(err, data) {
}
// Callback for subscriber creation.
-function createCB(err, commonEventSubscriber) {
+function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
@@ -351,15 +353,15 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur
**Example**
```ts
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for common event subscription.
-function subscribeCB(err, data) {
+function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err.code) {
console.error(`subscribe failed, code is ${err.code}`);
} else {
@@ -368,7 +370,7 @@ function subscribeCB(err, data) {
}
// Callback for subscriber creation.
-function createCB(err, commonEventSubscriber) {
+function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
@@ -380,7 +382,7 @@ function createCB(err, commonEventSubscriber) {
}
// Callback for common event unsubscription.
-function unsubscribeCB(err) {
+function unsubscribeCB(err:Base.BusinessError) {
if (err.code) {
console.error(`unsubscribe failed, code is ${err.code}`);
} else {
diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md
index 61d22613c35ceb0556ab66748f635c3e92c7b412..070fee6a9381edfea0ceaf7758b01f41a137b861 100644
--- a/en/application-dev/reference/apis/js-apis-commonEventManager.md
+++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md
@@ -10,6 +10,7 @@ The **CommonEventManager** module provides common event capabilities, including
```ts
import CommonEventManager from '@ohos.commonEventManager';
+import Base from '@ohos.base';
```
## Support
@@ -48,7 +49,7 @@ Publishes a common event and executes an asynchronous callback after the event i
```ts
// Callback for common event publication
-function publishCB(err) {
+function publishCB(err:Base.BusinessError) {
if (err) {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -95,14 +96,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca
```ts
// Attributes of a common event.
-let options = {
+let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event.
data: "initial data",// Result data of the common event.
isOrdered: true // The common event is an ordered one.
}
// Callback for common event publication
-function publishCB(err) {
+function publishCB(err:Base.BusinessError) {
if (err) {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -151,7 +152,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb
```ts
// Callback for common event publication
-function publishCB(err) {
+function publishCB(err:Base.BusinessError) {
if (err) {
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -205,13 +206,13 @@ Publishes a common event with given attributes to a specific user. This API uses
```ts
// Attributes of a common event.
-let options = {
+let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event.
data: "initial data",// Result data of the common event.
}
// Callback for common event publication.
-function publishCB(err) {
+function publishCB(err:Base.BusinessError) {
if (err) {
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -248,15 +249,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul
**Example**
```ts
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for subscriber creation.
-function createCB(err, commonEventSubscriber) {
+function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if(!err) {
console.info("createSubscriber");
subscriber = commonEventSubscriber;
@@ -295,18 +296,18 @@ Creates a subscriber. This API uses a promise to return the result.
**Example**
```ts
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Create a subscriber.
-CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => {
+CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => {
console.info("createSubscriber");
subscriber = commonEventSubscriber;
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
});
@@ -341,15 +342,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th
```ts
// Subscriber information.
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for common event subscription.
-function SubscribeCB(err, data) {
+function SubscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err) {
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -358,7 +359,7 @@ function SubscribeCB(err, data) {
}
// Callback for subscriber creation.
-function createCB(err, commonEventSubscriber) {
+function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if(!err) {
console.info("createSubscriber");
subscriber = commonEventSubscriber;
@@ -409,13 +410,13 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur
**Example**
```ts
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for common event subscription.
-function subscribeCB(err, data) {
+function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err) {
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -423,7 +424,7 @@ function subscribeCB(err, data) {
}
}
// Callback for subscriber creation.
-function createCB(err, commonEventSubscriber) {
+function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err) {
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -438,7 +439,7 @@ function createCB(err, commonEventSubscriber) {
}
}
// Callback for common event unsubscription.
-function unsubscribeCB(err) {
+function unsubscribeCB(err:Base.BusinessError) {
if (err) {
console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -493,7 +494,7 @@ Removes a sticky common event. This API uses an asynchronous callback to return
```ts
-CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => {
+CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => {
if (err) {
console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
return;
@@ -542,7 +543,7 @@ Removes a sticky common event. This API uses a promise to return the result.
```ts
CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => {
console.info(`Remove sticky event AsyncCallback success`);
-}).catch ((err) => {
+}).catch ((err:Base.BusinessError) => {
console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
});
```
@@ -577,7 +578,7 @@ Enables or disables static subscription for the current application. This API us
```ts
-CommonEventManager.setStaticSubscriberState(true, (err) => {
+CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => {
if (!err) {
console.info(`Set static subscriber state callback failed, err is null.`);
return;
@@ -627,7 +628,7 @@ Enables or disables static subscription for the current application. This API us
```ts
CommonEventManager.setStaticSubscriberState(false).then(() => {
console.info(`Set static subscriber state promise success`);
-}).catch ((err) => {
+}).catch ((err:Base.BusinessError) => {
console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md b/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md
index 737c91f0036c5217469a254aaad8974913eed1d9..bae8a5884f39618b18c4ed00d60ed3c6fa432b9e 100644
--- a/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md
+++ b/en/application-dev/reference/apis/js-apis-devicestatus-cooperate.md
@@ -4,9 +4,9 @@ The **cooperate** module implements screen hopping for two or more networked dev
> **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.
+> - 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.
>
-> - The APIs provided by this module are system APIs.
+> - The APIs provided by this module are system APIs.
## Modules to Import
@@ -26,7 +26,7 @@ Prepares for screen hopping. This API uses an asynchronous callback to return th
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | --------------------------- |
-| callback | AsyncCallback<void> | Yes|Callback used to return the result. |
+| callback | AsyncCallback<void> | Yes|Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
**Example**
@@ -56,7 +56,7 @@ Prepares for screen hopping. This API uses a promise to return the result.
| Parameters | Description |
| ------------------- | ------------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<void> | Promise that returns no value.|
@@ -75,7 +75,6 @@ try {
```
-
## cooperate.unprepare
unprepare(callback: AsyncCallback<void>): void;
@@ -86,7 +85,7 @@ Cancels the preparation for screen hopping. This API uses an asynchronous callba
| Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------ |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
@@ -104,8 +103,6 @@ try {
}
```
-
-
## cooperate.unprepare
unprepare(): Promise<void>;
@@ -118,7 +115,7 @@ Cancels the preparation for screen hopping. This API uses a promise to return th
| Parameters | Description |
| ------------------- | --------------------------------------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<void> | Promise that returns no value.|
```js
try {
@@ -133,7 +130,6 @@ try {
```
-
## cooperate.activate
activate(targetNetworkId: string, inputDeviceId: number, callback: AsyncCallback<void>): void;
@@ -148,7 +144,7 @@ Starts screen hopping. This API uses an asynchronous callback to return the resu
| -------- | ---------------------------- | ---- | ---------------------------- |
| targetNetworkId | string | Yes | Descriptor of the target device for screen hopping. |
| inputDeviceId | number | Yes | Identifier of the input device for screen hopping.|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
@@ -156,7 +152,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. |
+| 20900001 | Operation failed.|
**Example**
@@ -197,7 +193,7 @@ Starts screen hopping. This API uses a promise to return the result.
| Name | Description |
| ---------------------- | ------------------------------- |
-| Promise<void> | Promise used to return the result. |
+| Promise<void> | Promise that returns no value. |
**Error codes**
@@ -205,7 +201,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. |
+| 20900001 | Operation failed. |
**Example**
@@ -235,8 +231,8 @@ Stops screen hopping. This API uses an asynchronous callback to return the resul
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
-| isUnchained | boolean | Yes| Whether to disable the cross-device link.|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+| isUnchained | boolean | Yes| Whether to disable the cross-device link.
The value **true** means to disable the cross-device link, and the value **false** means the opposite.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
@@ -268,7 +264,7 @@ Stops screen hopping. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ----------- | ------- | ---- | ------------------ |
-| isUnchained | boolean | Yes | Whether to disable the cross-device link.|
+| isUnchained | boolean | Yes | Whether to disable the cross-device link.
The value **true** means to disable the cross-device link, and the value **false** means the opposite.|
@@ -276,7 +272,7 @@ Stops screen hopping. This API uses a promise to return the result.
| Name | Description |
| -------- | ---------------------------- |
-| Promise<void> | Promise used to return the result. |
+| Promise<void> | Promise that returns no value. |
@@ -307,7 +303,7 @@ Obtains the screen hopping status of the target device. This API uses an asynchr
| Name | Type | Mandatory | Description |
| -------- | --------- | ---- | ---------------------------- |
| networkId | string | Yes | Descriptor of the target device for screen hopping. |
-| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.|
+| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.|
**Example**
@@ -336,9 +332,9 @@ Obtains the screen hopping status of the target device. This API uses a promise
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------- | ---- | ---------------------------- |
-| networkId | string | Yes | Descriptor of the target device for screen hopping. |
+| Name | Type | Mandatory | Description |
+| -------- | --------- | ---- | ---------------------------- |
+| networkId | string | Yes | Descriptor of the target device for screen hopping. |
@@ -346,7 +342,7 @@ Obtains the screen hopping status of the target device. This API uses a promise
| Parameters | Description |
| ------------------- | ------------------------------- |
-| Promise<boolean> | Promise used to return the result.|
+| Promise<boolean> | Promise used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.|
diff --git a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md
index 93e460019144b0e321b1f39b4c41a37f9c908d37..ddc6fb296b8e88bd3866696cb7a0e409918c7745 100644
--- a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md
+++ b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md
@@ -1,6 +1,6 @@
# @ohos.distributedMissionManager (Distributed Mission Management)
-The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device.
+The **distributedMissionManager** module implements mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device by mission ID or bundle name.
> **NOTE**
>
@@ -14,7 +14,6 @@ The **distributedMissionManager** module implements system mission management ac
import distributedMissionManager from '@ohos.distributedMissionManager'
```
-
## distributedMissionManager.registerMissionListener
registerMissionListener(parameter: MissionDeviceInfo, options: MissionCallback, callback: AsyncCallback<void>): void;
@@ -30,8 +29,8 @@ Registers a mission status listener. This API uses an asynchronous callback to r
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | --------- |
| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for.|
-| options | [MissionCallback](#missioncallback) | Yes | Callback to register. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| options | [MissionCallback](#missioncallback) | Yes | Callback to register.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the listener is registered, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
@@ -80,14 +79,14 @@ Registers a mission status listener. This API uses a promise to return the resul
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- |
-| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. |
+| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. |
| options | MissionCallback | Yes | Callback to register.|
**Return value**
| Type | Description |
| ------------------- | ---------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<void> | Promise that returns no value.|
**Example**
@@ -123,7 +122,6 @@ Registers a mission status listener. This API uses a promise to return the resul
}
```
-
## distributedMissionManager.unRegisterMissionListener
unRegisterMissionListener(parameter: MissionDeviceInfo, callback: AsyncCallback<void>): void;
@@ -138,8 +136,8 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | --------- |
-| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the listener is deregistered, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
@@ -159,7 +157,6 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
}
```
-
## distributedMissionManager.unRegisterMissionListener
unRegisterMissionListener(parameter: MissionDeviceInfo): Promise<void>
@@ -180,7 +177,7 @@ Deregisters a mission status listener. This API uses a promise to return the res
| Type | Description |
| ------------------- | ---------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<void> |Promise that returns no value.|
**Example**
@@ -215,7 +212,7 @@ Starts to synchronize the remote mission list. This API uses an asynchronous cal
| Name | Type | Mandatory | Description |
| --------- | ------------------------------------- | ---- | --------- |
| parameter | [MissionParameter](#missionparameter) | Yes | Parameters required for synchronization. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the synchronization is started, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
@@ -257,7 +254,7 @@ Starts to synchronize the remote mission list. This API uses a promise to return
| Type | Description |
| ------------------- | ---------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<void> | Promise that returns no value.|
**Example**
@@ -294,7 +291,7 @@ Stops synchronizing the remote mission list. This API uses an asynchronous callb
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | --------- |
| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Parameters required for synchronization. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the synchronization is stopped, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
@@ -334,7 +331,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t
| Type | Description |
| ------------------- | ---------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<void> | Promise that returns no value.|
**Example**
@@ -358,7 +355,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t
continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callback: AsyncCallback<void>): void;
-Continues a mission on a remote device. This API uses an asynchronous callback to return the result.
+Continues a mission on a remote device, with the mission ID specified. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC
@@ -370,7 +367,7 @@ Continues a mission on a remote device. This API uses an asynchronous callback t
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.|
| options | [ContinueCallback](js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the mission is continued, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
@@ -416,7 +413,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promise<void>
-Continues a mission on a remote device. This API uses a promise to return the result.
+Continues a mission on a remote device, with the mission ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC
@@ -433,7 +430,7 @@ Continues a mission on a remote device. This API uses a promise to return the re
| Type | Description |
| ------------------- | ---------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<void> |Promise that returns no value.|
**Error codes**
@@ -490,7 +487,7 @@ Continues a mission on a remote device, with the bundle name specified. This API
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueMissionInfo](./js-apis-inner-application-continueMissionInfo.md) | Yes | Parameters required for mission continuation.|
-| callback | AsyncCallback<void> | Yes | Callback invoked when the mission continuation is complete.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the mission is continued, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
@@ -546,7 +543,7 @@ Continues a mission on a remote device, with the bundle name specified. This API
| Type | Description |
| ------------------- | ---------------- |
-| Promise<void> | Promise used to return the result.|
+| Promise<void> | Promise that returns no value.|
**Error codes**
@@ -586,7 +583,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
on(type: 'continueStateChange', callback: Callback<{ state: ContinueState, info: ContinuableInfo }>): void
-Registers a listener for the mission continuation state of the current application.
+Subscribes to continuation state change events of the current mission.
**Required permissions**: ohos.permission.MANAGE_MISSIONS
@@ -596,8 +593,8 @@ Registers a listener for the mission continuation state of the current applicati
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- |
-| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. |
-| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | Yes | Callback used to return the mission continuation state and information. |
+| type | string | Yes | Event type. The value **'continueStateChange'** indicates the continuation state change event of the current mission. |
+| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | Yes | Callback used to return the continuation state and information of the current mission. |
**Example**
@@ -615,7 +612,7 @@ Registers a listener for the mission continuation state of the current applicati
off(type: 'continueStateChange', callback?: Callback<{ state: ContinueState, info: ContinuableInfo }>): void
-Deregisters a listener for the mission continuation state of the current application.
+Unsubscribes from continuation state change events of the current mission.
**Required permissions**: ohos.permission.MANAGE_MISSIONS
@@ -625,8 +622,8 @@ Deregisters a listener for the mission continuation state of the current applica
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- |
-| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. |
-| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | No | Callback used for the listener to be deregistered. |
+| type | string | Yes | Event type. The value **'continueStateChange'** indicates the continuation state change event of the current mission. |
+| callback | Callback<{ state: [ContinueState](#continuestate10), info: [ContinuableInfo](./js-apis-inner-application-continuableInfo.md) }> | No | Callback used to return the continuation state and information of the current mission.
If the callback is unspecified, all subscriptions to the specified event are canceled. |
**Example**
@@ -688,5 +685,5 @@ Enumerates the mission continuation states.
| Name | Value | Description |
| ------------- | --------- | ------------------------------------------------------------ |
-| ACTIVE | 0 | Mission continuation is activated for the current application. |
-| INACTIVE | 1 | Mission continuation is not activated for the current application. |
+| ACTIVE | 0 | Continuation is activated for the current mission. |
+| INACTIVE | 1 | Continuation is not activated for the current mission. |
diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md
index e2ff3f6fa98d46577475cdaa86222b0eb3522b1f..ed0fdfc9c2f1a1d9e58683f19d11f7d2e9194f48 100644
--- a/en/application-dev/reference/apis/js-apis-hiappevent.md
+++ b/en/application-dev/reference/apis/js-apis-hiappevent.md
@@ -4,7 +4,7 @@ The **hiAppEvent** module provides the application event logging functions, such
> **NOTE**
>
-> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
+> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md).
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -20,7 +20,7 @@ Before using application event logging, you need to understand the requirements
**Event Name**
-An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
+An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter or dollar sign ($) and cannot end with an underscore (_).
**Event Type**
@@ -30,8 +30,8 @@ An event type is an enumerated value of [EventType](#eventtype).
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
-- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
-- The parameter value can be of the string, number, boolean, or array type.
+- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter or dollar sign ($) and cannot end with an underscore (_).
+- A parameter value can be of the string, number, boolean, or array type.
- If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded.
- If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated.
- If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
@@ -156,12 +156,12 @@ Provides the configuration items for application event logging.
| Name | Type | Mandatory| Description |
| ---------- | ------- | ---- | ------------------------------------------------------------ |
| disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.|
-| maxStorage | string | No | Maximum size of the event file storage directory. The default value is 10M. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.|
+| maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.|
## EventType
-Enumerates event types.
+Enumerates the event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md
index 03cad26cfecb5295b611d48fbc9f69862895ddb0..41d5566ed0ffaa6a9327f3da04e2c92c6a31465b 100644
--- a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md
+++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md
@@ -122,10 +122,10 @@ Defines parameters for an **AppEventInfo** object.
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
-| domain | string | Yes | Event domain. Event domain name, which is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
-| name | string | Yes | Event name. Event name, which is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
+| domain | string | Yes | Event domain. The value is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
+| name | string | Yes | Event name. The value is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).|
| eventType | [EventType](#eventtype) | Yes | Event type. |
-| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:
- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).
- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
+| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:
- The parameter name is a string of up to 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).
- The parameter value can be a string, number, boolean, or array. If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded. If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated. If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
## hiAppEvent.configure
@@ -436,7 +436,7 @@ hiAppEvent.clearData();
## EventType
-Enumerates event types.
+Enumerates the event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md
index 50069e993211374ce83715a18f42f6bae26d2895..6f8d2c742f12ebd5d32855d72548266abc308160 100644
--- a/en/application-dev/reference/apis/js-apis-http.md
+++ b/en/application-dev/reference/apis/js-apis-http.md
@@ -86,7 +86,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
| Type | Description |
| :---------- | :----------------------------------------------------------- |
-| HttpRequest | An **HttpRequest** object, which contains the **request**, **request2**, **destroy**, **on**, or **off** method.|
+| HttpRequest | An **HttpRequest** object, which contains the **request**, **requestInStream**, **destroy**, **on**, or **off** method.|
**Example**
@@ -364,9 +364,9 @@ Destroys an HTTP request.
httpRequest.destroy();
```
-### request210+
+### requestInStream10+
-request2(url: string, callback: AsyncCallback\): void
+requestInStream(url: string, callback: AsyncCallback\): void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
@@ -424,18 +424,18 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
-httpRequest.request2("EXAMPLE_URL", (err, data) => {
+httpRequest.requestInStream("EXAMPLE_URL", (err, data) => {
if (!err) {
- console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
+ console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else {
- console.info("request2 ERROR : err = " + JSON.stringify(err));
+ console.info("requestInStream ERROR : err = " + JSON.stringify(err));
}
})
```
-### request210+
+### requestInStream10+
-request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void
+requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\): void
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
@@ -494,7 +494,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
-httpRequest.request2("EXAMPLE_URL",
+httpRequest.requestInStream("EXAMPLE_URL",
{
method: http.RequestMethod.GET,
header: {
@@ -504,16 +504,16 @@ httpRequest.request2("EXAMPLE_URL",
connectTimeout: 60000
}, (err, data) => {
if (!err) {
- console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
+ console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else {
- console.info("request2 ERROR : err = " + JSON.stringify(err));
+ console.info("requestInStream ERROR : err = " + JSON.stringify(err));
}
})
```
-### request210+
+### requestInStream10+
-request2(url: string, options? : HttpRequestOptions): Promise\
+requestInStream(url: string, options? : HttpRequestOptions): Promise\
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result, which is a streaming response.
@@ -577,7 +577,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
-let promise = httpRequest.request2("EXAMPLE_URL", {
+let promise = httpRequest.requestInStream("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
@@ -586,9 +586,9 @@ let promise = httpRequest.request2("EXAMPLE_URL", {
}
});
promise.then((data) => {
- console.info("request2 OK!" + JSON.stringify(data));
+ console.info("requestInStream OK!" + JSON.stringify(data));
}).catch((err) => {
- console.info("request2 ERROR : err = " + JSON.stringify(err));
+ console.info("requestInStream ERROR : err = " + JSON.stringify(err));
});
```
@@ -815,9 +815,9 @@ Unregisters the observer for events indicating completion of receiving HTTP stre
httpRequest.off('dataEnd');
```
-### on('dataProgress')10+
+### on('dataReceiveProgress')10+
-on(type: 'dataProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void
+on(type: 'dataReceiveProgress', callback: Callback\<{ receiveSize: number, totalSize: number }\>): void
Registers an observer for events indicating progress of receiving HTTP streaming responses.
@@ -830,20 +830,20 @@ Registers an observer for events indicating progress of receiving HTTP streaming
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | --------------------------------- |
-| type | string | Yes | Event type. The value is **dataProgress**.|
+| type | string | Yes | Event type. The value is **dataReceiveProgress**.|
| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.
- **receiveSize**: number of received bytes.
- **totalSize**: total number of bytes to be received.|
**Example**
```js
-httpRequest.on('dataProgress', (data) => {
- console.info('dataProgress:' + JSON.stringify(data));
+httpRequest.on('dataReceiveProgress', (data) => {
+ console.info('dataReceiveProgress:' + JSON.stringify(data));
});
```
-### off('dataProgress')10+
+### off('dataReceiveProgress')10+
-off(type: 'dataProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void
+off(type: 'dataReceiveProgress', callback?: Callback\<{ receiveSize: number, totalSize: number }\>): void
Unregisters the observer for events indicating progress of receiving HTTP streaming responses.
@@ -856,13 +856,13 @@ Unregisters the observer for events indicating progress of receiving HTTP stream
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | -------------------------------------- |
-| type | string | Yes | Event type. The value is **dataProgress**.|
+| type | string | Yes | Event type. The value is **dataReceiveProgress**.|
| callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. |
**Example**
```js
-httpRequest.off('dataProgress');
+httpRequest.off('dataReceiveProgress');
```
## HttpRequestOptions6+
diff --git a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md
index 02112d5b265e73139c9cd662246a819bc16c0b1f..cc3d507ee9d208bc66571ca56daf1cf518c3d5fe 100644
--- a/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md
+++ b/en/application-dev/reference/apis/js-apis-inner-commonEvent-commonEventSubscriber.md
@@ -10,15 +10,17 @@ Before using the **CommonEventSubscriber** module, you must obtain a **subscribe
```ts
import CommonEvent from '@ohos.commonEvent';
-let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
+import CommonEventManager from '@ohos.commonEventManager';
+import Base from '@ohos.base';
+let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
-let subscribeInfo = {
+let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for subscriber creation.
-function createCB(err, commonEventSubscriber) {
+function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
@@ -49,7 +51,7 @@ Obtains the code of this common event. This API uses an asynchronous callback to
```ts
// Callback for result code obtaining of an ordered common event.
-function getCodeCB(err, code) {
+function getCodeCB(err:Base.BusinessError, code:number) {
if (err.code) {
console.error(`getCode failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -76,9 +78,9 @@ Obtains the code of this common event. This API uses a promise to return the res
**Example**
```ts
-subscriber.getCode().then((code) => {
+subscriber.getCode().then((code:number) => {
console.info("getCode " + JSON.stringify(code));
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`getCode failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -102,7 +104,7 @@ Sets the code for this common event. This API uses an asynchronous callback to r
```ts
// Callback for result code setting of an ordered common event.
-function setCodeCB(err) {
+function setCodeCB(err:Base.BusinessError) {
if (err.code) {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -137,7 +139,7 @@ Sets the code for this common event. This API uses a promise to return the resul
```ts
subscriber.setCode(1).then(() => {
console.info("setCode");
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -160,7 +162,7 @@ Obtains the data of this common event. This API uses an asynchronous callback to
```ts
// Callback for result data obtaining of an ordered common event.
-function getDataCB(err, data) {
+function getDataCB(err:Base.BusinessError, data:string) {
if (err.code) {
console.error(`getData failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -187,9 +189,9 @@ Obtains the data of this common event. This API uses a promise to return the res
**Example**
```ts
-subscriber.getData().then((data) => {
+subscriber.getData().then((data:string) => {
console.info("getData " + JSON.stringify(data));
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`getData failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -213,7 +215,7 @@ Sets the data for this common event. This API uses an asynchronous callback to r
```ts
// Callback for result data setting of an ordered common event
-function setDataCB(err) {
+function setDataCB(err:Base.BusinessError) {
if (err.code) {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -248,7 +250,7 @@ Sets the data for this common event. This API uses a promise to return the resul
```ts
subscriber.setData("publish_data_changed").then(() => {
console.info("setData");
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -273,7 +275,7 @@ Sets the code and data for this common event. This API uses an asynchronous call
```ts
// Callback for code and data setting of an ordered common event.
-function setCodeDataCB(err) {
+function setCodeDataCB(err:Base.BusinessError) {
if (err.code) {
console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -309,7 +311,7 @@ Sets the code and data for this common event. This API uses a promise to return
```ts
subscriber.setCodeAndData(1, "publish_data_changed").then(() => {
console.info("setCodeAndData");
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -332,7 +334,7 @@ Checks whether this common event is an ordered one. This API uses an asynchronou
```ts
// Callback for checking whether the current common event is an ordered one.
-function isOrderedCB(err, isOrdered) {
+function isOrderedCB(err:Base.BusinessError, isOrdered:boolean) {
if (err.code) {
console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -359,9 +361,9 @@ Checks whether this common event is an ordered one. This API uses a promise to r
**Example**
```ts
-subscriber.isOrderedCommonEvent().then((isOrdered) => {
+subscriber.isOrderedCommonEvent().then((isOrdered:boolean) => {
console.info("isOrdered " + JSON.stringify(isOrdered));
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -384,7 +386,7 @@ Checks whether this common event is a sticky one. This API uses an asynchronous
```ts
// Callback for checking whether the current common event is a sticky one.
-function isStickyCB(err, isSticky) {
+function isStickyCB(err:Base.BusinessError, isSticky:boolean) {
if (err.code) {
console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -411,9 +413,9 @@ Checks whether this common event is a sticky one. This API uses a promise to ret
**Example**
```ts
-subscriber.isStickyCommonEvent().then((isSticky) => {
+subscriber.isStickyCommonEvent().then((isSticky:boolean) => {
console.info("isSticky " + JSON.stringify(isSticky));
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -436,7 +438,7 @@ Aborts this common event. After the abort, the common event is not sent to the n
```ts
// Callback for common event aborting.
-function abortCB(err) {
+function abortCB(err:Base.BusinessError) {
if (err.code) {
console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -465,7 +467,7 @@ Aborts this common event. After the abort, the common event is not sent to the n
```ts
subscriber.abortCommonEvent().then(() => {
console.info("abortCommonEvent");
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -488,7 +490,7 @@ Clears the aborted state of this common event. This API takes effect only for or
```ts
// Callback for clearing the aborted state of the current common event.
-function clearAbortCB(err) {
+function clearAbortCB(err:Base.BusinessError) {
if (err.code) {
console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -517,7 +519,7 @@ Clears the aborted state of this common event. This API takes effect only for or
```ts
subscriber.clearAbortCommonEvent().then(() => {
console.info("clearAbortCommonEvent");
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -540,7 +542,7 @@ Checks whether this common event is in the aborted state. This API takes effect
```ts
// Callback for checking whether the current common event is in the aborted state.
-function getAbortCB(err, abortEvent) {
+function getAbortCB(err:Base.BusinessError, abortEvent:boolean) {
if (err.code) {
console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -567,9 +569,9 @@ Checks whether this common event is in the aborted state. This API takes effect
**Example**
```ts
-subscriber.getAbortCommonEvent().then((abortEvent) => {
+subscriber.getAbortCommonEvent().then((abortEvent:boolean) => {
console.info("abortCommonEvent " + JSON.stringify(abortEvent));
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -592,7 +594,7 @@ Obtains the subscriber information. This API uses an asynchronous callback to re
```ts
// Callback for subscriber information obtaining.
-function getCB(err, subscribeInfo) {
+function getCB(err:Base.BusinessError, subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) {
if (err.code) {
console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -619,9 +621,9 @@ Obtains the subscriber information. This API uses a promise to return the result
**Example**
```ts
-subscriber.getSubscribeInfo().then((subscribeInfo) => {
+subscriber.getSubscribeInfo().then((subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) => {
console.info("subscribeInfo " + JSON.stringify(subscribeInfo));
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`);
});
```
@@ -644,7 +646,7 @@ Finishes this common event. This API takes effect only for ordered common events
```ts
// Callback for ordered common event finishing.
-function finishCB(err) {
+function finishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
@@ -674,7 +676,7 @@ Finishes this common event. This API takes effect only for ordered common events
```ts
subscriber.finishCommonEvent().then(() => {
console.info("FinishCommonEvent");
-}).catch((err) => {
+}).catch((err:Base.BusinessError) => {
console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`);
});
```
diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md
index 0bd9b716421a85fdc2e28582d2799ced24b12109..0dc717e3b5f35c05502cad7e898740c383e67077 100644
--- a/en/application-dev/reference/apis/js-apis-net-connection.md
+++ b/en/application-dev/reference/apis/js-apis-net-connection.md
@@ -158,7 +158,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
-| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
+| callback | AsyncCallback\<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
**Error codes**
@@ -192,7 +192,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses a prom
| Type | Description |
| --------------------------------- | ------------------------------------- |
-| Promise\<[HttpProxy](#httpproxy)> | Promise used to return the result.|
+| Promise\<[HttpProxy](#httpproxy10)> | Promise used to return the result.|
**Error codes**
@@ -229,7 +229,7 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
-| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network. |
+| httpProxy | [HttpProxy](#httpproxy10) | Yes | Global HTTP proxy configuration of the network. |
| callback | AsyncCallback\ | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is set successfully, **error** is **undefined**. Otherwise, **error** is an error object.|
**Error codes**
@@ -274,7 +274,7 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
-| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.|
+| httpProxy | [HttpProxy](#httpproxy10) | Yes | Global HTTP proxy configuration of the network.|
**Return value**
@@ -324,7 +324,7 @@ This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
-| callback | AsyncCallback<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
+| callback | AsyncCallback<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
**Error codes**
@@ -347,7 +347,7 @@ connection.getDefaultHttpProxy((error, data) => {
getDefaultHttpProxy(): Promise\;
Obtains the default proxy configuration of the network.
-If the global proxy is set, the global proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
+If the global proxy is set, the global HTTP proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
@@ -356,7 +356,7 @@ This API uses a promise to return the result.
| Type | Description |
| -------------------------------- | ----------------------------------------- |
-| Promise<[HttpProxy](#httpproxy)> | Promise used to return the result.|
+| Promise<[HttpProxy](#httpproxy10)> | Promise used to return the result.|
**Error codes**
diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md
index 21fdb44e402a4a0cb4a6f39d883522ab84513217..e7aae4ef5ef646af82499c8d3fdfd2bfd53cf905 100644
--- a/en/application-dev/reference/apis/js-apis-net-ethernet.md
+++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md
@@ -486,7 +486,7 @@ Defines the network configuration for the Ethernet connection.
| gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
-| httpProxy10+ | [HttpProxy](js-apis-net-connection.md#httpproxy) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.|
+| httpProxy10+ | [HttpProxy](js-apis-net-connection.md#httpproxy10) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.|
## IPSetMode9+
diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md
index 646f07fc4d30ec6ad4585eacd840a99954b34973..5ab31338dad186152b29dab25f05f1175822902a 100644
--- a/en/application-dev/reference/apis/js-apis-notification.md
+++ b/en/application-dev/reference/apis/js-apis-notification.md
@@ -4,7 +4,7 @@ The **Notification** module provides notification management capabilities, cover
> **NOTE**
>
-> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. This module is deprecated since API version 9.
>
> Notification subscription and unsubscription APIs are available only to system applications.
@@ -1460,7 +1460,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal
| --------------- | ----------------------------------| ---- | -------------------- |
| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. |
| notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. |
-| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. |
+| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. |
| callback | AsyncCallback\ | Yes | Callback used to return the result.|
**Example**
@@ -1502,7 +1502,7 @@ Removes a notification for a specified bundle. This API uses a promise to return
| --------------- | --------------- | ---- | ---------- |
| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.|
| notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. |
-| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. |
+| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. |
**Example**
@@ -1536,8 +1536,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | -------------------- |
-| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback. |
-| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. |
+| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback.|
+| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. |
| callback | AsyncCallback\ | Yes | Callback used to return the result.|
**Example**
@@ -1573,7 +1573,7 @@ Removes a notification for a specified bundle. This API uses a promise to return
| Name | Type | Mandatory| Description |
| -------- | ---------- | ---- | ---------- |
| hashCode | string | Yes | Unique notification ID.|
-| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. |
+| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. |
**Example**
@@ -2872,10 +2872,10 @@ Notification.getDeviceRemindType().then((data) => {
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) instead.
-| Name | Type | Read-only| Mandatory| Description |
-| ------ | ------ |---- | --- | ------ |
-| bundle | string | No | Yes | Bundle information of the application.|
-| uid | number | No | No | User ID.|
+| Name | Type | Mandatory| Description |
+| ------ | ------ | --- | ------ |
+| bundle | string | Yes | Bundle information of the application.|
+| uid | number | No | User ID.|
## NotificationKeydeprecated
@@ -3059,7 +3059,7 @@ Describes the notification request.
| classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. |
| groupName8+| string | Yes | Yes | Notification group name. |
| template8+ | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. |
-| isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. |
+| isRemoveAllowed10+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. |
| source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. |
| distributedOption8+ | [DistributedOptions](#distributedoptions8) | Yes | Yes | Distributed notification options. |
| deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. |
@@ -3203,7 +3203,7 @@ Provides the notification user input.
| TYPE_CONTINUOUS | 1 | Continuous notification. |
| TYPE_TIMER | 2 | Timed notification. |
-## RemoveReason9+ deprecated
+## RemoveReason deprecated
**System capability**: SystemCapability.Notification.Notification
@@ -3211,9 +3211,9 @@ Provides the notification user input.
> **NOTE**
>
-> This API is supported since API version 9 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead.
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead.
| Name | Value | Description |
| -------------------- | --- | -------------------- |
-| CLICK_REASON_REMOVE9+ | 1 | The notification is removed after a click on it. |
-| CANCEL_REASON_REMOVE9+ | 2 | The notification is removed by the user. |
+| CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. |
+| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. |
diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md
index 1ca3f7833aadfde7058e24f8231d0e0360d82122..10a7091a75c1e9354921fe46bdbc1ce4bccb1a2e 100644
--- a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md
+++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md
@@ -443,6 +443,90 @@ notificationSubscribe.remove(hashCode, reason).then(() => {
console.info("remove success");
});
```
+## NotificationSubscribe.remove
+
+remove(hashCodes: Array\, reason: RemoveReason, callback: AsyncCallback\): void
+
+Removes specified notifications. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Notification.Notification
+
+**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER
+
+**System API**: This is a system API and cannot be called by third-party applications.
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|-----------|-------------------------------| ---- |-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| hashCodes | Array\ | Yes | Array of unique notification IDs. It is the **hashCode** in the [NotificationRequest](js-apis-inner-notification-notificationRequest.md#notificationrequest) object of [SubscribeCallbackData](js-apis-notification.md#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onConsume) callback.|
+| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+
+**Error codes**
+
+For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md).
+
+| ID| Error Message |
+| -------- | ----------------------------------- |
+| 1600001 | Internal error. |
+| 1600002 | Marshalling or unmarshalling error. |
+| 1600003 | Failed to connect service. |
+
+**Example**
+
+```js
+let hashCodes = ['hashCode1', 'hashCode2'];
+
+function removeCallback(err) {
+ if (err) {
+ console.error(`remove failed, code is ${err.code}, message is ${err.message}`);
+ } else {
+ console.info("remove success");
+ }
+}
+let reason = notificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE;
+notificationSubscribe.remove(hashCodes, reason, removeCallback);
+```
+
+## NotificationSubscribe.remove
+
+remove(hashCodes: Array\, reason: RemoveReason): Promise\
+
+Removes specified notifications. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Notification.Notification
+
+**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER
+
+**System API**: This is a system API and cannot be called by third-party applications.
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+|-----------|-------------------------------| ---- |-------------|
+| hashCodes | Array\ | Yes | Array of unique notification IDs.|
+| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. |
+
+**Error codes**
+
+For details about the error codes, see [Notification Error Codes](../errorcodes/errorcode-notification.md).
+
+| ID| Error Message |
+| -------- | ----------------------------------- |
+| 1600001 | Internal error. |
+| 1600002 | Marshalling or unmarshalling error. |
+| 1600003 | Failed to connect service. |
+
+**Example**
+
+```js
+let hashCodes = ['hashCode1','hashCode2'];
+let reason = notificationSubscribe.RemoveReason.CLICK_REASON_REMOVE;
+notificationSubscribe.remove(hashCodes, reason).then(() => {
+ console.info("remove success");
+});
+```
## NotificationSubscribe.removeAll
diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md
index 9f949c10e762e34ae641d648d676f0d754c9b52c..39d64c64f8d0f015b44823b5fe87f42f8a06bde2 100644
--- a/en/application-dev/reference/apis/js-apis-pointer.md
+++ b/en/application-dev/reference/apis/js-apis-pointer.md
@@ -850,7 +850,7 @@ Enumerates mouse pointer styles.
| MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east ||
| MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west ||
| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions||
-| HORIZONTAL_TEXT_CURSOR10+ | 39 | Horizontal text selection||
+| HORIZONTAL_TEXT_CURSOR10+ | 39 | Horizontal text cursor||
| CURSOR_CROSS10+ | 40 | Cross cursor||
| CURSOR_CIRCLE10+ | 41 | Circular cursor||
@@ -1726,3 +1726,357 @@ try {
console.log(`getTouchpadRightClickType failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
}
```
+
+## pointer.setPointerSize10+
+
+setPointerSize(size: number, callback: AsyncCallback<void>): void
+
+Sets the pointer size. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------- | ---- | ------------------------------------- |
+| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
+
+**Example**
+
+```js
+try {
+ pointer.setPointerSize(1, (error) => {
+ if (error) {
+ console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+ return;
+ }
+ console.log(`setPointerSize success`);
+ });
+} catch (error) {
+ console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.setPointerSize10+
+
+setPointerSize(size: number): Promise<void>
+
+Sets the pointer size. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----------------------------------- |
+| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**.|
+
+**Return value**
+
+| Name | Description |
+| ------------------- | ---------------- |
+| Promise<void> | Promise that returns no value.|
+
+**Example**
+
+```js
+try {
+ pointer.setPointerSize(3).then(() => {
+ console.log(`setPointerSize success`);
+ });
+} catch (error) {
+ console.log(`setPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.setPointerSizeSync10+
+
+setPointerSizeSync(size: number): void;
+
+Sets the pointer size. This API returns the result synchronously.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----------------------------------- |
+| size | number | Yes | Pointer size. The value ranges from **1** to **7**. The default value is **1**.|
+
+**Example**
+
+```js
+try {
+ pointer.setPointerSizeSync(5);
+ console.log(`setPointerSizeSync success`);
+} catch (error) {
+ console.log(`setPointerSizeSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.getPointerSize10+
+
+getPointerSize(callback: AsyncCallback<number>): void
+
+Obtains the pointer size. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | -------------- |
+| callback | AsyncCallback<number> | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+try {
+ pointer.getPointerSize((error, size) => {
+ console.log(`getPointerSize success, size: ${JSON.stringify(size)}`);
+ });
+} catch (error) {
+ console.log(`getPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.getPointerSize10+
+
+getPointerSize(): Promise<number>
+
+Obtains the pointer size. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Return value**
+
+| Name | Description |
+| --------------------- | ------------------- |
+| Promise<number> | Promise used to return the result.|
+
+**Example**
+
+```js
+try {
+ pointer.getPointerSize().then((size) => {
+ console.log(`getPointerSize success, size: ${JSON.stringify(size)}`);
+ });
+} catch (error) {
+ console.log(`getPointerSize failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.getPointerSizeSync10+
+
+getPointerSizeSync(): number
+
+Obtains the pointer size. This API returns the result synchronously.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Return value**
+
+| Name | Description |
+| --------------------- | ------------------- |
+| number | Pointer size. |
+
+**Example**
+
+```js
+try {
+ let pointerSize = pointer.getPointerSizeSync();
+ console.log(`getPointerSizeSync success, pointerSize: ${JSON.stringify(pointerSize)}`);
+} catch (error) {
+ console.log(`getPointerSizeSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.setPointerColor10+
+
+setPointerColor(color: number, callback: AsyncCallback<void>): void
+
+Sets the pointer color. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------- | ---- | ------------------------------------- |
+| color | number | Yes | Pointer color. The default value is **black** (0x000000). |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
+
+**Example**
+
+```js
+try {
+ pointer.setPointerColor(0xF6C800, (error) => {
+ if (error) {
+ console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+ return;
+ }
+ console.log(`setPointerColor success`);
+ });
+} catch (error) {
+ console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.setPointerColor10+
+
+setPointerColor(color: number): Promise<void>
+
+Sets the pointer color. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----------------------------------- |
+| color | number | Yes | Pointer color. The default value is **black** (0x000000).|
+
+**Return value**
+
+| Name | Description |
+| ------------------- | ---------------- |
+| Promise<void> | Promise that returns no value.|
+
+**Example**
+
+```js
+try {
+ pointer.setPointerColor(0xF6C800).then(() => {
+ console.log(`setPointerColor success`);
+ });
+} catch (error) {
+ console.log(`setPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.setPointerColorSync10+
+
+setPointerColorSync(color: number): void;
+
+Sets the pointer color. This API returns the result synchronously.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----------------------------------- |
+| color | number | Yes | Pointer color. The default value is **black** (0x000000).|
+
+**Example**
+
+```js
+try {
+ pointer.setPointerColorSync(0xF6C800);
+ console.log(`setPointerColorSync success`);
+} catch (error) {
+ console.log(`setPointerColorSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.getPointerColor10+
+
+getPointerColor(callback: AsyncCallback<number>): void
+
+Obtains the pointer color. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | -------------- |
+| callback | AsyncCallback<number> | Yes | Callback used to return the result.|
+
+**Example**
+
+```js
+try {
+ pointer.getPointerColor((error, color) => {
+ console.log(`getPointerColor success, color: ${JSON.stringify(color)}`);
+ });
+} catch (error) {
+ console.log(`getPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.getPointerColor10+
+
+getPointerColor(): Promise<number>
+
+Obtains the pointer color. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Return value**
+
+| Name | Description |
+| --------------------- | ------------------- |
+| Promise<number> | Promise used to return the result.|
+
+**Example**
+
+```js
+try {
+ pointer.getPointerColor().then((color) => {
+ console.log(`getPointerColor success, color: ${JSON.stringify(color)}`);
+ });
+} catch (error) {
+ console.log(`getPointerColor failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
+
+## pointer.getPointerColorSync10+
+
+getPointerColorSync(): number
+
+Obtains the pointer color. This API returns the result synchronously.
+
+**System capability**: SystemCapability.MultimodalInput.Input.Pointer
+
+**System API**: This is a system API.
+
+**Return value**
+
+| Name | Description |
+| --------------------- | ------------------- |
+| number | Pointer color.|
+
+**Example**
+
+```js
+try {
+ let pointerColor = pointer.getPointerColorSync();
+ console.log(`getPointerColorSync success, pointerColor: ${JSON.stringify(pointerColor)}`);
+} catch (error) {
+ console.log(`getPointerColorSync failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
+```
diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md
index 644759435975c722de9fd274b704ecd01804d2fd..de1e1e04ddfc51d5e24ef783f022ab2f400f09dc 100644
--- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md
+++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md
@@ -1,8 +1,6 @@
-# @ohos.reminderAgentManager (reminderAgentManager)
+# @ohos.reminderAgentManager (Agent-Powered Reminders)
-The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent.
-
-You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits.
+The **reminderAgentManager** module provides APIs related to agent-powered reminders. When your application is frozen or exits, the timing and notification functions of your application will be taken over by a system service running in the background. You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks.
> **NOTE**
>
@@ -15,12 +13,15 @@ You can use the APIs to create scheduled reminders for countdown timers, calenda
import reminderAgentManager from'@ohos.reminderAgentManager';
```
-
## reminderAgentManager.publishReminder
publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\): void
-Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8).
+Publishes a reminder. This API uses an asynchronous callback to return the result.
+
+> **NOTE**
+>
+> This API can be called only after the [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8) permission is obtained.
**Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER
@@ -28,10 +29,10 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.|
- | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.|
+| callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.|
**Error codes**
@@ -62,26 +63,29 @@ try {
};
```
-
## reminderAgentManager.publishReminder
publishReminder(reminderReq: ReminderRequest): Promise\
-Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8).
+Publishes a reminder. This API uses a promise to return the result.
+
+> **NOTE**
+>
+> This API can be called only after the [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8) permission is obtained.
**Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER
**System capability**: SystemCapability.Notification.ReminderAgent
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | Promise\ | Promise used to return the published reminder's ID.|
+| Type| Description|
+| -------- | -------- |
+| Promise\ | Promise used to return the published reminder's ID.|
**Error codes**
@@ -115,7 +119,7 @@ try {
cancelReminder(reminderId: number, callback: AsyncCallback\): void
-Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result.
+Cancels a reminder published. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -124,7 +128,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reminderId | number | Yes| ID of the reminder to cancel.|
-| callback | AsyncCallback\ | Yes| Callback used to return the result.|
+| callback | AsyncCallback\ | Yes| Callback used to return the result. If the reminder is canceled, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
@@ -151,12 +155,11 @@ try {
};
```
-
## reminderAgentManager.cancelReminder
cancelReminder(reminderId: number): Promise\
-Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result.
+Cancels a reminder published. This API uses a promise to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -170,7 +173,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th
| Type| Description|
| -------- | -------- |
-| Promise\ | Promise used to return the result.|
+| Promise\ | Promise that returns no value.|
**Error codes**
@@ -199,8 +202,7 @@ try {
getValidReminders(callback: AsyncCallback>): void
-
-Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders.
+Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -208,7 +210,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| callback | AsyncCallback\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.|
+| callback | AsyncCallback\> | Yes| Callback used to return all the valid reminders.|
**Error codes**
@@ -259,7 +261,7 @@ try {
getValidReminders(): Promise\>
-Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders.
+Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -267,7 +269,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th
| Type| Description|
| -------- | -------- |
-| Promise\> | Promise used to return an array of all valid reminders set by the current application.|
+| Promise\> | Promise used to return all the valid reminders.|
**Error codes**
@@ -312,12 +314,11 @@ try {
};
```
-
## reminderAgentManager.cancelAllReminders
cancelAllReminders(callback: AsyncCallback\): void
-Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result.
+Cancels all reminders set by the current application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -325,7 +326,7 @@ Cancels all reminders set by the current application. This API uses an asynchron
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| callback | AsyncCallback\ | Yes| Callback used to return the result.|
+| callback | AsyncCallback\ | Yes| Callback used to return the result. If all the reminders are canceled, **err** is **undefined**. Otherwise, **err** is an error object. |
**Error codes**
@@ -351,12 +352,11 @@ try {
};
```
-
## reminderAgentManager.cancelAllReminders
cancelAllReminders(): Promise\
-Cancels all reminders set by the current application. This API uses a promise to return the cancellation result.
+Cancels all reminders set by the current application. This API uses a promise to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -364,7 +364,7 @@ Cancels all reminders set by the current application. This API uses a promise to
| Type| Description|
| -------- | -------- |
-| Promise\ | Promise used to return the result.|
+| Promise\ | Promise that returns no value.|
**Error codes**
@@ -401,8 +401,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.|
-| callback | AsyncCallback\ | Yes| Callback used to return the result.|
+| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot. Only the type can be set.|
+| callback | AsyncCallback\ | Yes| Callback used to return the result. If the notification slot is added, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
@@ -438,13 +438,13 @@ Adds a notification slot. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.|
+| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot. Only the type can be set.|
**Return value**
| Type| Description|
| -------- | -------- |
-| Promise\ | Promise used to return the result.|
+| Promise\ | Promise that returns no value.|
**Example**
@@ -470,7 +470,7 @@ try {
removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\): void
-Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result.
+Removes a notification slot. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -479,7 +479,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.|
-| callback | AsyncCallback\ | Yes| Callback used to return the result.|
+| callback | AsyncCallback\ | Yes| Callback used to return the result. If the notification slot is removed, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
@@ -504,7 +504,7 @@ try {
removeNotificationSlot(slotType: notification.SlotType): Promise\
-Removes a notification slot of a specified type. This API uses a promise to return the result.
+Removes a notification slot. This API uses a promise to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -518,7 +518,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu
| Type| Description|
| -------- | -------- |
-| Promise\ | Promise used to return the result.|
+| Promise\ | Promise that returns no value.|
**Example**
@@ -538,7 +538,7 @@ try {
## ActionButtonType
-Enumerates button types.
+Enumerates the button types.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -551,7 +551,7 @@ Enumerates button types.
## ReminderType
-Enumerates reminder types.
+Enumerates the reminder types.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -564,8 +564,7 @@ Enumerates reminder types.
## ActionButton
-Defines a button displayed for the reminder in the notification panel.
-
+Defines the button on the reminder displayed.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -573,7 +572,7 @@ Defines a button displayed for the reminder in the notification panel.
| -------- | -------- | -------- | -------- |
| title | string | Yes| Text on the button.|
| type | [ActionButtonType](#actionbuttontype) | Yes| Button type.|
-| wantAgent10+ | [WantAgent](#wantagent) | No| Ability information that is displayed after the button is clicked.
**System API**: This is a system API and cannot be called by third-party applications.|
+| wantAgent10+ | [WantAgent](#wantagent) | No| Information about the ability that is displayed after the button is clicked.
**System API**: This is a system API and cannot be called by third-party applications.|
## WantAgent
@@ -592,19 +591,19 @@ Defines the information about the redirected-to ability.
## MaxScreenWantAgent
-Provides the information about the target package and ability to start automatically when the reminder is displayed in full-screen mode. This API is reserved.
+Provides the information about the ability that is started automatically and displayed in full-screen mode when the reminder arrives. This API is reserved.
**System capability**: SystemCapability.Notification.ReminderAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.|
-| abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.|
+| pkgName | string | Yes| Name of the target package. (If the device is in use, only a notification banner is displayed.)|
+| abilityName | string | Yes| Name of the target ability. (If the device is in use, only a notification banner is displayed.)|
## ReminderRequest
-Defines the reminder to publish.
+Defines the request for publishing a reminder.
**System capability**: SystemCapability.Notification.ReminderAgent
@@ -613,7 +612,7 @@ Defines the reminder to publish.
| reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.|
| actionButton | [ActionButton](#actionbutton) | No| Buttons displayed for the reminder in the notification panel.
- For common applications, a maximum of two buttons are supported.
- For system applications, a maximum of two buttons are supported in API version 9, and a maximum of three buttons are supported in API version 10 and later versions.|
| wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the reminder is clicked.|
-| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.|
+| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is started automatically and displayed in full-screen mode when the reminder arrives. If the device is in use, only a notification banner is displayed.
This API is reserved.|
| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.|
| snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.|
| timeInterval | number | No| Reminder snooze interval, in seconds. The minimum value is 5 minutes.|
@@ -623,8 +622,8 @@ Defines the reminder to publish.
| snoozeContent | string | No| Content to be displayed when the reminder is snoozing.|
| notificationId | number | No| Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.|
| slotType | [notification.SlotType](js-apis-notificationManager.md#slottype) | No| Type of the slot used by the reminder.|
-| tapDismissed10+ | boolean | No| Whether the notification is automatically cleared. The value is the same as that of [NotificationRequest.tapDismissed](js-apis-inner-notification-notificationRequest.md#notificationrequest).|
-| autoDeletedTime10+ | number | No| Time when the notification is automatically cleared. The value is the same as that of [NotificationRequest.autoDeletedTime](js-apis-inner-notification-notificationRequest.md#notificationrequest).|
+| tapDismissed10+ | boolean | No| Whether the reminder is automatically cleared. For details, see [NotificationRequest.tapDismissed](js-apis-inner-notification-notificationRequest.md#notificationrequest). |
+| autoDeletedTime10+ | number | No| Time when the reminder is automatically cleared. For details, see [NotificationRequest.autoDeletedTime](js-apis-inner-notification-notificationRequest.md#notificationrequest).|
## ReminderRequestCalendar
diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md
index 40cb3dc087b7b7a756a602925699597ec557c294..d4807f0517fc537ac7283d612c856dae10c235d7 100644
--- a/en/application-dev/reference/apis/js-apis-resource-manager.md
+++ b/en/application-dev/reference/apis/js-apis-resource-manager.md
@@ -22,10 +22,10 @@ For details about how to reference context in the stage model, see [Context in t
import UIAbility from '@ohos.app.ability.UIAbility';
export default class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
- let context = this.context;
- let resourceManager = context.resourceManager;
- }
+ onWindowStageCreate(windowStage) {
+ let context = this.context;
+ let resourceManager = context.resourceManager;
+ }
}
```
@@ -48,17 +48,17 @@ Obtains the **ResourceManager** object of this application. This API uses an asy
**Example**
```js
resourceManager.getResourceManager((error, mgr) => {
+ if (error != null) {
+ console.log("error is " + error);
+ return;
+ }
+ mgr.getStringValue(0x1000000, (error, value) => {
if (error != null) {
- console.log("error is " + error);
- return;
+ console.log("error is " + error);
+ } else {
+ let str = value;
}
- mgr.getStringValue(0x1000000, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
- });
+ });
});
```
> **NOTE**
In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file.
@@ -107,15 +107,15 @@ Obtains the **ResourceManager** object of this application. This API uses a prom
**Example**
```js
resourceManager.getResourceManager().then(mgr => {
- mgr.getStringValue(0x1000000, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
- });
+ mgr.getStringValue(0x1000000, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
+ });
}).catch(error => {
- console.log("error is " + error);
+ console.log("error is " + error);
});
```
> **NOTE**
In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file.
@@ -150,7 +150,6 @@ Obtains the **ResourceManager** object of an application based on the specified
});
```
-
## resourceManager.getSystemResourceManager10+
getSystemResourceManager(): ResourceManager
@@ -177,16 +176,16 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
```js
import resourceManager from '@ohos.resourceManager';
-try {
+ try {
let systemResourceManager = resourceManager.getSystemResourceManager();
systemResourceManager.getStringValue($r('sys.string.ohos_lab_vibrate').id).then(value => {
- let str = value;
+ let str = value;
}).catch(error => {
- console.log("systemResourceManager getStringValue promise error is " + error);
+ console.log("systemResourceManager getStringValue promise error is " + error);
});
-} catch (error) {
+ } catch (error) {
console.error(`systemResourceManager getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
-}
+ }
```
@@ -259,7 +258,7 @@ Defines the device capability.
| Name | Type | Readable | Writable | Description |
| ------------- | ------------------------------- | ---- | ---- | -------- |
| screenDensity | [ScreenDensity](#screendensity) | Yes | No | Screen density of the device.|
-| deviceType | [DeviceType](#devicetype) | Yes | No | Type of the device. |
+| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. |
## RawFileDescriptor8+
@@ -301,20 +300,25 @@ Defines the capability of accessing application resources.
>
> - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**.
-### getStringValue9+
+### getStringSync9+
-getStringValue(resId: number, callback: AsyncCallback<string>): void
+getStringSync(resId: number): string
-Obtains the string corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the string corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | --------------- |
-| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ----------- |
+| string | String corresponding to the specified resource ID.|
**Error codes**
@@ -322,31 +326,24 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the module resId invalid. |
-| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
-**Example (stage)**
+**Example**
```ts
- try {
- this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
- });
- } catch (error) {
- console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
- }
+ try {
+ this.context.resourceManager.getStringSync($r('app.string.test').id);
+ } catch (error) {
+ console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
+ }
```
+### getStringSync10+
-### getStringValue9+
-
-getStringValue(resId: number): Promise<string>
+getStringSync(resId: number, ...args: Array): string
-Obtains the string corresponding to the specified resource ID. This API uses a promise to return the result.
+Obtains the string corresponding to the specified resource ID and formats the string based on **args**. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -355,42 +352,39 @@ Obtains the string corresponding to the specified resource ID. This API uses a p
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
+| args | Array | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.|
**Return value**
-| Type | Description |
-| --------------------- | ----------- |
-| Promise<string> | Promise used to return the result.|
+| Type | Description |
+| ------ | ---------------------------- |
+| string | Formatted string.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
-| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
+| -------- | ----------------------------------------------- |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
+| 9001007 | If the resource obtained by resId formatting error. |
**Example**
```ts
try {
- this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => {
- let str = value;
- }).catch(error => {
- console.log("getStringValue promise error is " + error);
- });
+ this.context.resourceManager.getStringSync($r('app.string.test').id, "format string", 10, 98.78);
} catch (error) {
- console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
+### getStringSync9+
-### getStringValue9+
-
-getStringValue(resource: Resource, callback: AsyncCallback<string>): void
+getStringSync(resource: Resource): string
-Obtains the string corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+Obtains the string corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -398,10 +392,15 @@ Obtains the string corresponding to the specified resource object. This API uses
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | --------------- |
-| resource | [Resource](#resource9) | Yes | Resource object. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | ---- | ---- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ---------------- |
+| string | String corresponding to the specified resource object.|
**Error codes**
@@ -416,30 +415,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.string.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
};
try {
- this.context.resourceManager.getStringValue(resource, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
- });
+ this.context.resourceManager.getStringSync(resource);
} catch (error) {
- console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
}
-
```
+### getStringSync10+
-### getStringValue9+
-
-getStringValue(resource: Resource): Promise<string>
+getStringSync(resource: Resource, ...args: Array): string
-Obtains the string corresponding to the specified resource object. This API uses a promise to return the result.
+Obtains the string corresponding to the specified resource object and formats the string based on **args**. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -450,12 +441,13 @@ Obtains the string corresponding to the specified resource object. This API uses
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
+| args | Array | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.|
**Return value**
-| Type | Description |
-| --------------------- | ---------------- |
-| Promise<string> | Promise used to return the result.|
+| Type | Description |
+| ------ | ---------------------------- |
+| string | Formatted string.|
**Error codes**
@@ -466,40 +458,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
| 9001006 | If the resource re-ref too much. |
+| 9001007 | If the resource obtained by resId formatting error. |
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.string.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
};
try {
- this.context.resourceManager.getStringValue(resource).then(value => {
- let str = value;
- }).catch(error => {
- console.log("getStringValue promise error is " + error);
- });
+ this.context.resourceManager.getStringSync(resource, "format string", 10, 98.78);
} catch (error) {
- console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
}
- ```
-
+ ```
-### getStringArrayValue9+
+### getStringByNameSync9+
-getStringArrayValue(resId: number, callback: AsyncCallback<Array<string>>): void
+getStringByNameSync(resName: string): string
-Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the string corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------------------------- | ---- | ----------------- |
-| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
+
+**Return value**
+
+| Type | Description |
+| ------ | ---------- |
+| string | String corresponding to the specified resource name.|
**Error codes**
@@ -507,45 +500,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let strArray = value;
- }
- });
+ this.context.resourceManager.getStringByNameSync("test");
} catch (error) {
- console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
+### getStringByNameSync10+
-### getStringArrayValue9+
-
-getStringArrayValue(resId: number): Promise<Array<string>>
+getStringByNameSync(resName: string, ...args: Array): string
-Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result.
+Obtains the string corresponding to the specified resource name and formats the string based on **args**. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ----- | ------ | ---- | ----- |
-| resId | number | Yes | Resource ID.|
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
+| args | Array | No | Arguments for formatting strings.
Supported arguments:
%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.|
**Return value**
-| Type | Description |
-| ---------------------------------- | ------------- |
-| Promise<Array<string>> | Promise used to return the result.|
+| Type | Description |
+| ------ | ---------------------------- |
+| string | Formatted string.|
**Error codes**
@@ -553,39 +540,34 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
| 9001006 | If the resource re-ref too much. |
+| 9001008 | If the resource obtained by resName formatting error. |
**Example**
```ts
try {
- this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => {
- let strArray = value;
- }).catch(error => {
- console.log("getStringArrayValue promise error is " + error);
- });
+ this.context.resourceManager.getStringByNameSync("test", "format string", 10, 98.78);
} catch (error) {
- console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
- ```
+ ```
-### getStringArrayValue9+
+### getStringValue9+
-getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<string>>): void
+getStringValue(resId: number, callback: AsyncCallback<string>): void
-Obtains the string array corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+Obtains the string corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------------------------- | ---- | ----------------- |
-| resource | [Resource](#resource9) | Yes | Resource object. |
-| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resId | number | Yes | Resource ID. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -593,51 +575,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
+| 9001001 | If the module resId invalid. |
+| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
-**Example**
+**Example (stage)**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.strarray.test').id
- };
try {
- this.context.resourceManager.getStringArrayValue(resource, (error, value) => {
+ this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => {
if (error != null) {
- console.log("error is " + error);
+ console.log("error is " + error);
} else {
- let strArray = value;
+ let str = value;
}
});
} catch (error) {
- console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getStringArrayValue9+
+### getStringValue9+
-getStringArrayValue(resource: Resource): Promise<Array<string>>
+getStringValue(resId: number): Promise<string>
-Obtains the string array corresponding to the specified resource object. This API uses a promise to return the result.
+Obtains the string corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | ---- | ---- |
-| resource | [Resource](#resource9) | Yes | Resource object.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
**Return value**
-| Type | Description |
-| ---------------------------------- | ------------------ |
-| Promise<Array<string>> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | ----------- |
+| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -651,36 +626,33 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.strarray.test').id
- };
try {
- this.context.resourceManager.getStringArrayValue(resource).then(value => {
- let strArray = value;
+ this.context.resourceManager.getStringValue($r('app.string.test').id).then(value => {
+ let str = value;
}).catch(error => {
- console.log("getStringArray promise error is " + error);
+ console.log("getStringValue promise error is " + error);
});
} catch (error) {
- console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContent9+
+### getStringValue9+
-getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void
+getStringValue(resource: Resource, callback: AsyncCallback<string>): void
-Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the string corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------- | ---- | ------------------ |
-| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -690,37 +662,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
+ };
try {
- this.context.resourceManager.getMediaContent($r('app.media.test').id, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let media = value;
- }
+ this.context.resourceManager.getStringValue(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
});
} catch (error) {
- console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContent10+
+### getStringValue9+
-getMediaContent(resId: number, density: number, callback: AsyncCallback<Uint8Array>): void
+getStringValue(resource: Resource): Promise<string>
-Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the string corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------- | ---- | ------------------ |
-| resId | number | Yes | Resource ID. |
-| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
-| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | ---- | ---- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ---------------- |
+| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -730,41 +714,85 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.string.test').id
+ };
try {
- this.context.resourceManager.getMediaContent($r('app.media.test').id, 120, (error, value) => {
- if (error != null) {
- console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
- } else {
- let media = value;
- }
+ this.context.resourceManager.getStringValue(resource).then(value => {
+ let str = value;
+ }).catch(error => {
+ console.log("getStringValue promise error is " + error);
});
} catch (error) {
- console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContent9+
+### getStringByName9+
-getMediaContent(resId: number): Promise<Uint8Array>
+getStringByName(resName: string, callback: AsyncCallback<string>): void
-Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result.
+Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ----- | ------ | ---- | ----- |
-| resId | number | Yes | Resource ID.|
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | --------------- |
+| resName | string | Yes | Resource name. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
+| 9001006 | If the resource re-ref too much. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getStringByName("test", (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
+ });
+ } catch (error) {
+ console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getStringByName9+
+
+getStringByName(resName: string): Promise<string>
+
+Obtains the string corresponding to the specified resource name. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
**Return value**
-| Type | Description |
-| ------------------------- | -------------- |
-| Promise<Uint8Array> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | ---------- |
+| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -772,27 +800,28 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => {
- let media = value;
- }).catch(error => {
- console.log("getMediaContent promise error is " + error);
- });
+ this.context.resourceManager.getStringByName("test").then(value => {
+ let str = value;
+ }).catch(error => {
+ console.log("getStringByName promise error is " + error);
+ });
} catch (error) {
- console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getStringByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContent10+
+### getStringArrayValueSync10+
-getMediaContent(resId: number, density: number): Promise<Uint8Array>
+getStringArrayValueSync(resId: number): Array<string>
-Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses a promise to return the result.
+Obtains the string array corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -801,13 +830,12 @@ Obtains the content of the media file with the screen density corresponding to t
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
-| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
-| Type | Description |
-| ------------------------- | -------------- |
-| Promise<Uint8Array> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | ----------- |
+| Array<string> | String array corresponding to the specified resource ID.|
**Error codes**
@@ -817,25 +845,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => {
- let media = value;
- }).catch(error => {
- console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
- });
+ this.context.resourceManager.getStringArrayValueSync($r('app.strarray.test').id);
} catch (error) {
- console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getStringArrayValueSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContent9+
+### getStringArrayValueSync10+
-getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): void
+getStringArrayValueSync(resource: Resource): Array<string>
-Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+Obtains the string array corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -843,10 +868,15 @@ Obtains the content of the media file corresponding to the specified resource ob
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------- | ---- | ------------------ |
-| resource | [Resource](#resource9) | Yes | Resource object. |
-| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ----------- |
+| Array<string> | String array corresponding to the specified resource object.|
**Error codes**
@@ -856,44 +886,36 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.strarray.test').id
};
try {
- this.context.resourceManager.getMediaContent(resource, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let media = value;
- }
- });
+ this.context.resourceManager.getStringArrayValueSync(resource);
} catch (error) {
- console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getStringArrayValueSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContent10+
+### getStringArrayValue9+
-getMediaContent(resource: Resource, density: number, callback: AsyncCallback<Uint8Array>): void
+getStringArrayValue(resId: number, callback: AsyncCallback<Array<string>>): void
-Obtains the content of the media file with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+Obtains the string array corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------- | ---- | ------------------ |
-| resource | [Resource](#resource9) | Yes | Resource object. |
-| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
-| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ----------------- |
+| resId | number | Yes | Resource ID. |
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
**Error codes**
@@ -903,48 +925,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.test').id
- };
try {
- this.context.resourceManager.getMediaContent(resource, 120, (error, value) => {
- if (error != null) {
- console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
- } else {
- let media = value;
- }
+ this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let strArray = value;
+ }
});
} catch (error) {
- console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContent9+
+### getStringArrayValue9+
-getMediaContent(resource: Resource): Promise<Uint8Array>
+getStringArrayValue(resId: number): Promise<Array<string>>
-Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result.
+Obtains the string array corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | ---- | ---- |
-| resource | [Resource](#resource9) | Yes | Resource object.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
**Return value**
-| Type | Description |
-| ------------------------- | ------------------- |
-| Promise<Uint8Array> | Promise used to return the result.|
+| Type | Description |
+| ---------------------------------- | ------------- |
+| Promise<Array<string>> | Promise used to return the result.|
**Error codes**
@@ -954,30 +970,26 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.test').id
- };
try {
- this.context.resourceManager.getMediaContent(resource).then(value => {
- let media = value;
+ this.context.resourceManager.getStringArrayValue($r('app.strarray.test').id).then(value => {
+ let strArray = value;
}).catch(error => {
- console.log("getMediaContent promise error is " + error);
+ console.log("getStringArrayValue promise error is " + error);
});
} catch (error) {
- console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContent10+
+### getStringArrayValue9+
-getMediaContent(resource: Resource, density: number): Promise<Uint8Array>
+getStringArrayValue(resource: Resource, callback: AsyncCallback<Array<string>>): void
-Obtains the content of the media file with the screen density corresponding to the specified resource object. This API uses a promise to return the result.
+Obtains the string array corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -985,16 +997,10 @@ Obtains the content of the media file with the screen density corresponding to t
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | ---- | ---- |
-| resource | [Resource](#resource9) | Yes | Resource object.|
-| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
-
-**Return value**
-
-| Type | Description |
-| ------------------------- | ------------------- |
-| Promise<Uint8Array> | Promise used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ----------------- |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
**Error codes**
@@ -1004,39 +1010,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.strarray.test').id
};
try {
- this.context.resourceManager.getMediaContent(resource, 120).then(value => {
- let media = value;
- }).catch(error => {
- console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ this.context.resourceManager.getStringArrayValue(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let strArray = value;
+ }
});
} catch (error) {
- console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContentBase649+
+### getStringArrayValue9+
-getMediaContentBase64(resId: number, callback: AsyncCallback<string>): void
+getStringArrayValue(resource: Resource): Promise<Array<string>>
-Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the string array corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | ------------------------ |
-| resId | number | Yes | Resource ID. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | ---- | ---- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------- | ------------------ |
+| Promise<Array<string>> | Promise used to return the result.|
**Error codes**
@@ -1046,37 +1062,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.strarray.test').id
+ };
try {
- this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let media = value;
- }
- });
+ this.context.resourceManager.getStringArrayValue(resource).then(value => {
+ let strArray = value;
+ }).catch(error => {
+ console.log("getStringArray promise error is " + error);
+ });
} catch (error) {
- console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getStringArrayValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContentBase6410+
+### getStringArrayByName9+
-getMediaContentBase64(resId: number, density: number, callback: AsyncCallback<string>): void
+getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): void
-Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | ------------------------ |
-| resId | number | Yes | Resource ID. |
-| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ----------------- |
+| resName | string | Yes | Resource name. |
+| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
**Error codes**
@@ -1084,43 +1103,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120, (error, value) => {
- if (error != null) {
- console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
- } else {
- let media = value;
- }
- });
+ this.context.resourceManager.getStringArrayByName("test", (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let strArray = value;
+ }
+ });
} catch (error) {
- console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContentBase649+
+### getStringArrayByName9+
-getMediaContentBase64(resId: number): Promise<string>
+getStringArrayByName(resName: string): Promise<Array<string>>
-Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result.
+Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ----- | ------ | ---- | ----- |
-| resId | number | Yes | Resource ID.|
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
**Return value**
-| Type | Description |
-| --------------------- | -------------------- |
-| Promise<string> | Promise used to return the result.|
+| Type | Description |
+| ---------------------------------- | ------------ |
+| Promise<Array<string>> | Promise used to return the result.|
**Error codes**
@@ -1128,27 +1148,28 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => {
- let media = value;
+ this.context.resourceManager.getStringArrayByName("test").then(value => {
+ let strArray = value;
}).catch(error => {
- console.log("getMediaContentBase64 promise error is " + error);
+ console.log("getStringArrayByName promise error is " + error);
});
} catch (error) {
- console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContentBase6410+
+### getPluralStringValueSync10+
-getMediaContentBase64(resId: number, density: number): Promise<string>
+getPluralStringValueSync(resId: number, num: number): string
-Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses a promise to return the result.
+Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -1157,13 +1178,13 @@ Obtains the Base64 code of an image with the screen density corresponding to the
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
-| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+| num | number | Yes | Number. |
**Return value**
-| Type | Description |
-| --------------------- | -------------------- |
-| Promise<string> | Promise used to return the result.|
+| Type | Description |
+| -------- | ----------- |
+| string | Singular-plural string corresponding to the specified resource ID.|
**Error codes**
@@ -1173,25 +1194,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => {
- let media = value;
- }).catch(error => {
- console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
- });
+ this.context.resourceManager.getPluralStringValueSync($r('app.plural.test').id, 1);
} catch (error) {
- console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getPluralStringValueSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContentBase649+
+### getPluralStringValueSync10+
-getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>): void
+getPluralStringValueSync(resource: Resource, num: number): string
-Obtains the Base64 code of the image corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -1199,10 +1217,16 @@ Obtains the Base64 code of the image corresponding to the specified resource obj
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | ------------------------ |
-| resource | [Resource](#resource9) | Yes | Resource object. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+| num | number | Yes | Number. |
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ----------- |
+| string | Singular-plural string corresponding to the specified resource object.|
**Error codes**
@@ -1212,43 +1236,36 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.plural.test').id
};
try {
- this.context.resourceManager.getMediaContentBase64(resource, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let media = value;
- }
- });
+ this.context.resourceManager.getPluralStringValueSync(resource, 1);
} catch (error) {
- console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getPluralStringValueSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContentBase6410+
+### getPluralStringValue9+
-getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback<string>): void
+getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): void
-Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
+Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | ------------------------ |
-| resource | [Resource](#resource9) | Yes | Resource object. |
-| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------------- |
+| resId | number | Yes | Resource ID. |
+| num | number | Yes | Number. |
| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -1259,48 +1276,84 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.test').id
- };
try {
- this.context.resourceManager.getMediaContentBase64(resource, 120, (error, value) => {
- if (error != null) {
- console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
- } else {
- let media = value;
- }
+ this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
});
} catch (error) {
- console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContentBase649+
+### getPluralStringValue9+
-getMediaContentBase64(resource: Resource): Promise<string>
+getPluralStringValue(resId: number, num: number): Promise<string>
-Obtains the Base64 code of the image corresponding to the specified resource object. This API uses a promise to return the result.
+Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | ---- | ---- |
-| resource | [Resource](#resource9) | Yes | Resource object.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
+| num | number | Yes | Number. |
**Return value**
| Type | Description |
| --------------------- | ------------------------- |
-| Promise<string> | Promise used to return the result.|
+| Promise<string> | Promise used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => {
+ let str = value;
+ }).catch(error => {
+ console.log("getPluralStringValue promise error is " + error);
+ });
+ } catch (error) {
+ console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getPluralStringValue9+
+
+getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback<string>): void
+
+Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Model restriction**: This API can be used only in the stage model.
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------------------ |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| num | number | Yes | Number. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -1310,30 +1363,33 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.plural.test').id
};
try {
- this.context.resourceManager.getMediaContentBase64(resource).then(value => {
- let media = value;
- }).catch(error => {
- console.log("getMediaContentBase64 promise error is " + error);
+ this.context.resourceManager.getPluralStringValue(resource, 1, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
});
} catch (error) {
- console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaContentBase6410+
+### getPluralStringValue9+
-getMediaContentBase64(resource: Resource, density: number): Promise<string>
+getPluralStringValue(resource: Resource, num: number): Promise<string>
-Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses a promise to return the result.
+Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
@@ -1344,13 +1400,13 @@ Obtains the Base64 code of an image with the screen density corresponding to the
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
-| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+| num | number | Yes | Number. |
**Return value**
-| Type | Description |
-| --------------------- | ------------------------- |
-| Promise<string> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | ------------------------------ |
+| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -1360,159 +1416,178 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.plural.test').id
};
try {
- this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => {
- let media = value;
+ this.context.resourceManager.getPluralStringValue(resource, 1).then(value => {
+ let str = value;
}).catch(error => {
- console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.log("getPluralStringValue promise error is " + error);
});
} catch (error) {
- console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getConfiguration
+### getPluralStringByName9+
-getConfiguration(callback: AsyncCallback<Configuration>): void
+getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void
-Obtains the device configuration. This API uses an asynchronous callback to return the result.
+Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------------------------- | ---- | ------------------------- |
-| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ----------------------------- |
+| resName | string | Yes | Resource name. |
+| num | number | Yes | Number. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getConfiguration((error, value) => {
+ this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => {
if (error != null) {
- console.error("getConfiguration callback error is " + error);
+ console.log("error is " + error);
} else {
- let direction = value.direction;
- let locale = value.locale;
+ let str = value;
}
});
} catch (error) {
- console.error("getConfiguration callback error is " + error);
+ console.error(`callback getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
+### getPluralStringByName9+
-### getConfiguration
-
-getConfiguration(): Promise<Configuration>
+getPluralStringByName(resName: string, num: number): Promise<string>
-Obtains the device configuration. This API uses a promise to return the result.
+Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
+| num | number | Yes | Number. |
+
**Return value**
-| Type | Description |
-| ---------------------------------------- | ---------------- |
-| Promise<[Configuration](#configuration)> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | ---------------------- |
+| Promise<string> | Promise used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getConfiguration().then(value => {
- let direction = value.direction;
- let locale = value.locale;
+ this.context.resourceManager.getPluralStringByName("test", 1).then(value => {
+ let str = value;
}).catch(error => {
- console.error("getConfiguration promise error is " + error);
+ console.log("getPluralStringByName promise error is " + error);
});
} catch (error) {
- console.error("getConfiguration promise error is " + error);
+ console.error(`promise getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
+### getMediaContentSync10+
-### getDeviceCapability
-
-getDeviceCapability(callback: AsyncCallback<DeviceCapability>): void
+getMediaContentSync(resId: number, density?: number): Uint8Array
-Obtains the device capability. This API uses an asynchronous callback to return the result.
+Obtains the content of the media file (with the default or specified screen density) corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------------------------- | ---- | ---------------------------- |
-| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the result.|
-
-**Example**
- ```ts
- try {
- this.context.resourceManager.getDeviceCapability((error, value) => {
- if (error != null) {
- console.error("getDeviceCapability callback error is " + error);
- } else {
- let screenDensity = value.screenDensity;
- let deviceType = value.deviceType;
- }
- });
- } catch (error) {
- console.error("getDeviceCapability callback error is " + error);
- }
- ```
-
-
-### getDeviceCapability
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
+| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
-getDeviceCapability(): Promise<DeviceCapability>
+**Return value**
-Obtains the device capability. This API uses a promise to return the result.
+| Type | Description |
+| -------- | ----------- |
+| Uint8Array | Content of the media file corresponding to the specified resource ID.|
-**System capability**: SystemCapability.Global.ResourceManager
+**Error codes**
-**Return value**
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
-| Type | Description |
-| ---------------------------------------- | ------------------- |
-| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.|
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
- this.context.resourceManager.getDeviceCapability().then(value => {
- let screenDensity = value.screenDensity;
- let deviceType = value.deviceType;
- }).catch(error => {
- console.error("getDeviceCapability promise error is " + error);
- });
+ this.context.resourceManager.getMediaContentSync($r('app.media.test').id); // Default screen density
} catch (error) {
- console.error("getDeviceCapability promise error is " + error);
+ console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+
+ try {
+ this.context.resourceManager.getMediaContentSync($r('app.media.test').id, 120); // Specified screen density
+ } catch (error) {
+ console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getPluralStringValue9+
+### getMediaContentSync10+
-getPluralStringValue(resId: number, num: number, callback: AsyncCallback<string>): void
+getMediaContentSync(resource: Resource, density?: number): Uint8Array
-Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result.
+Obtains the content of the media file (with the default or specified screen density) corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | ------------------------------- |
-| resId | number | Yes | Resource ID. |
-| num | number | Yes | Number. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ----------- |
+| Uint8Array | Content of the media file corresponding to the specified resource object|
**Error codes**
@@ -1522,44 +1597,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
- });
+ this.context.resourceManager.getMediaContentSync(resource); // Default screen density
} catch (error) {
- console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`);
}
- ```
+ try {
+ this.context.resourceManager.getMediaContentSync(resource, 120); // Specified screen density
+ } catch (error) {
+ console.error(`getMediaContentSync failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
-### getPluralStringValue9+
+### getMediaContent9+
-getPluralStringValue(resId: number, num: number): Promise<string>
+getMediaContent(resId: number, callback: AsyncCallback<Uint8Array>): void
-Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result.
+Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ----- | ------ | ---- | ----- |
-| resId | number | Yes | Resource ID.|
-| num | number | Yes | Number. |
-
-**Return value**
-
-| Type | Description |
-| --------------------- | ------------------------- |
-| Promise<string> | Promise used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ------------------ |
+| resId | number | Yes | Resource ID. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Error codes**
@@ -1569,38 +1641,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getPluralStringValue($r("app.plural.test").id, 1).then(value => {
- let str = value;
- }).catch(error => {
- console.log("getPluralStringValue promise error is " + error);
+ this.context.resourceManager.getMediaContent($r('app.media.test').id, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getPluralStringValue9+
+### getMediaContent10+
-getPluralStringValue(resource: Resource, num: number, callback: AsyncCallback<string>): void
+getMediaContent(resId: number, density: number, callback: AsyncCallback<Uint8Array>): void
-Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses an asynchronous callback to return the result.
+Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | ------------------------------------ |
-| resource | [Resource](#resource9) | Yes | Resource object. |
-| num | number | Yes | Number. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ------------------ |
+| resId | number | Yes | Resource ID. |
+| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Error codes**
@@ -1610,50 +1681,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.plural.test').id
- };
try {
- this.context.resourceManager.getPluralStringValue(resource, 1, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
+ this.context.resourceManager.getMediaContent($r('app.media.test').id, 120, (error, value) => {
+ if (error != null) {
+ console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`callback getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getPluralStringValue9+
+### getMediaContent9+
-getPluralStringValue(resource: Resource, num: number): Promise<string>
+getMediaContent(resId: number): Promise<Uint8Array>
-Obtains the singular-plural string corresponding to the specified resource object based on the specified number. This API uses a promise to return the result.
+Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | ---- | ---- |
-| resource | [Resource](#resource9) | Yes | Resource object.|
-| num | number | Yes | Number. |
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
**Return value**
-| Type | Description |
-| --------------------- | ------------------------------ |
-| Promise<string> | Promise used to return the result.|
+| Type | Description |
+| ------------------------- | -------------- |
+| Promise<Uint8Array> | Promise used to return the result.|
**Error codes**
@@ -1663,41 +1725,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.plural.test').id
- };
try {
- this.context.resourceManager.getPluralStringValue(resource, 1).then(value => {
- let str = value;
+ this.context.resourceManager.getMediaContent($r('app.media.test').id).then(value => {
+ let media = value;
}).catch(error => {
- console.log("getPluralStringValue promise error is " + error);
+ console.log("getMediaContent promise error is " + error);
});
} catch (error) {
- console.error(`promise getPluralStringValue failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
+### getMediaContent10+
-### getRawFileContent9+
-
-getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void
+getMediaContent(resId: number, density: number): Promise<Uint8Array>
-Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
+Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------- | ---- | ----------------------- |
-| path | string | Yes | Path of the raw file. |
-| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
+| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+
+**Return value**
+
+| Type | Description |
+| ------------------------- | -------------- |
+| Promise<Uint8Array> | Promise used to return the result.|
**Error codes**
@@ -1705,42 +1766,38 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001005 | If the resource not found by path. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
- this.context.resourceManager.getRawFileContent("test.xml", (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let rawFile = value;
- }
+ this.context.resourceManager.getMediaContent($r('app.media.test').id, 120).then(value => {
+ let media = value;
+ }).catch(error => {
+ console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
- console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getRawFileContent9+
+### getMediaContent9+
-getRawFileContent(path: string): Promise<Uint8Array>
+getMediaContent(resource: Resource, callback: AsyncCallback<Uint8Array>): void
-Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
+Obtains the content of the media file corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| ---- | ------ | ---- | ----------- |
-| path | string | Yes | Path of the raw file.|
+**Model restriction**: This API can be used only in the stage model.
-**Return value**
+**Parameters**
-| Type | Description |
-| ------------------------- | ----------- |
-| Promise<Uint8Array> | Promise used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ------------------ |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Error codes**
@@ -1748,36 +1805,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001005 | If the resource not found by path. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getRawFileContent("test.xml").then(value => {
- let rawFile = value;
- }).catch(error => {
- console.log("getRawFileContent promise error is " + error);
+ this.context.resourceManager.getMediaContent(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`promise getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
+### getMediaContent10+
-### getRawFd9+
-
-getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void
+getMediaContent(resource: Resource, density: number, callback: AsyncCallback<Uint8Array>): void
-Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
+Obtains the content of the media file (with the specified screen density) corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------------------------- | ---- | -------------------------------- |
-| path | string | Yes | Path of the raw file. |
-| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ------------------ |
+| resource | [Resource](#resource9) | Yes | Resource object. |
+| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Error codes**
@@ -1785,44 +1852,50 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001005 | If the resource not found by path. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getRawFd("test.xml", (error, value) => {
- if (error != null) {
- console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);
- } else {
- let fd = value.fd;
- let offset = value.offset;
- let length = value.length;
- }
+ this.context.resourceManager.getMediaContent(resource, 120, (error, value) => {
+ if (error != null) {
+ console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getRawFd9+
+### getMediaContent9+
-getRawFd(path: string): Promise<RawFileDescriptor>
+getMediaContent(resource: Resource): Promise<Uint8Array>
-Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
+Obtains the content of the media file corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| ---- | ------ | ---- | ----------- |
-| path | string | Yes | Path of the raw file.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | ---- | ---- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
-| Type | Description |
-| ---------------------------------------- | ------------------- |
-| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.|
+| Type | Description |
+| ------------------------- | ------------------- |
+| Promise<Uint8Array> | Promise used to return the result.|
**Error codes**
@@ -1830,37 +1903,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001005 | If the resource not found by path. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getRawFd("test.xml").then(value => {
- let fd = value.fd;
- let offset = value.offset;
- let length = value.length;
+ this.context.resourceManager.getMediaContent(resource).then(value => {
+ let media = value;
}).catch(error => {
- console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`);
+ console.log("getMediaContent promise error is " + error);
});
} catch (error) {
- console.error(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getRawFileList10+
+### getMediaContent10+
-getRawFileList(path: string, callback: AsyncCallback<Array\>): void;
+getMediaContent(resource: Resource, density: number): Promise<Uint8Array>
-Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
+Obtains the content of the media file (with the specified screen density) corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------- | ---- | ----------------------- |
-| path | string | Yes | Path of the **rawfile** folder. |
-| callback | AsyncCallback<Array\> | Yes| Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | ---- | ---- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+
+**Return value**
+
+| Type | Description |
+| ------------------------- | ------------------- |
+| Promise<Uint8Array> | Promise used to return the result.|
**Error codes**
@@ -1868,42 +1953,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001005 | If the resource not found by path. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
- try { // Passing "" means to obtain the list of files in the root directory of the raw file.
- this.context.resourceManager.getRawFileList("", (error, value) => {
- if (error != null) {
- console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
- } else {
- let rawFile = value;
- }
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
+ try {
+ this.context.resourceManager.getMediaContent(resource, 120).then(value => {
+ let media = value;
+ }).catch(error => {
+ console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
- console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getRawFileList10+
+### getMediaByName9+
-getRawFileList(path: string): Promise<Array\>
+getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void
-Obtains the list of files in the **resources/rawfile** directory. This API uses a promise to return the result.
+Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ---- | ------ | ---- | ----------- |
-| path | string | Yes | Path of the **rawfile** folder.|
-
-**Return value**
-
-| Type | Description |
-| ------------------------- | ----------- |
-| Promise<Array\> | List of files in the **rawfile** folder.|
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ------------------ |
+| resName | string | Yes | Resource name. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Error codes**
@@ -1911,35 +1995,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001005 | If the resource not found by path. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
**Example**
```ts
- try { // Passing "" means to obtain the list of files in the root directory of the raw file.
- this.context.resourceManager.getRawFileList("").then(value => {
- let rawFile = value;
- }).catch(error => {
- console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
+ try {
+ this.context.resourceManager.getMediaByName("test", (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### closeRawFd9+
+### getMediaByName10+
-closeRawFd(path: string, callback: AsyncCallback<void>): void
+getMediaByName(resName: string, density: number, callback: AsyncCallback<Uint8Array>): void
-Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
+Obtains the content of the media file (with the specified screen density) corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------- | ---- | ----------- |
-| path | string | Yes | Path of the raw file.|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ------------------ |
+| resName | string | Yes | Resource name. |
+| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
**Error codes**
@@ -1947,41 +2035,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001005 | The resource not found by path. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
- this.context.resourceManager.closeRawFd("test.xml", (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- }
+ this.context.resourceManager.getMediaByName("test", 120, (error, value) => {
+ if (error != null) {
+ console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`callback closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
}
-
```
-### closeRawFd9+
+### getMediaByName9+
-closeRawFd(path: string): Promise<void>
+getMediaByName(resName: string): Promise<Uint8Array>
-Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
+Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ---- | ------ | ---- | ----------- |
-| path | string | Yes | Path of the raw file.|
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
**Return value**
-| Type | Description |
-| ------------------- | ---- |
-| Promise<void> | Promise that returns no value.|
+| Type | Description |
+| ------------------------- | ------------- |
+| Promise<Uint8Array> | Promise used to return the result.|
**Error codes**
@@ -1989,97 +2079,85 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001005 | If the resource not found by path. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
- this.context.resourceManager.closeRawFd("test.xml").then(value => {
- let result = value;
+ this.context.resourceManager.getMediaByName("test").then(value => {
+ let media = value;
}).catch(error => {
- console.log("closeRawFd promise error is " + error);
+ console.log("getMediaByName promise error is " + error);
});
} catch (error) {
- console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`)
}
```
-### release7+
+### getMediaByName10+
-release()
+getMediaByName(resName: string, density: number): Promise<Uint8Array>
-Releases a created **resourceManager** object.
+Obtains the content of the media file (with the specified screen density) corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Example**
- ```ts
- try {
- this.context.resourceManager.release();
- } catch (error) {
- console.error("release error is " + error);
- }
- ```
+**Parameters**
-### getStringByName9+
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
+| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
-getStringByName(resName: string, callback: AsyncCallback<string>): void
+**Return value**
-Obtains the string corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
+| Type | Description |
+| ------------------------- | ------------- |
+| Promise<Uint8Array> | Promise used to return the result.|
-**System capability**: SystemCapability.Global.ResourceManager
+**Error codes**
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | --------------- |
-| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
-
-**Error codes**
-
-For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getStringByName("test", (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let string = value;
- }
+ this.context.resourceManager.getMediaByName("test", 120).then(value => {
+ let media = value;
+ }).catch(error => {
+ console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
- console.error(`callback getStringByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getStringByName9+
+### getMediaContentBase64Sync10+
-getStringByName(resName: string): Promise<string>
+getMediaContentBase64Sync(resId: number, density?: number): string
-Obtains the string corresponding to the specified resource name. This API uses a promise to return the result.
+Obtains the Base64 code of the image (with the default or specified screen density) corresponding to the specified resource ID.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
+| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
-| Type | Description |
-| --------------------- | ---------- |
-| Promise<string> | Promise used to return the result.|
+| Type | Description |
+| -------- | ----------- |
+| string | Base64 code of the image corresponding to the specified resource ID.|
**Error codes**
@@ -2087,82 +2165,46 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
- this.context.resourceManager.getStringByName("test").then(value => {
- let string = value;
- }).catch(error => {
- console.log("getStringByName promise error is " + error);
- });
+ this.context.resourceManager.getMediaContentBase64Sync($r('app.media.test').id); // Default screen density
} catch (error) {
- console.error(`promise getStringByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`);
}
- ```
-
-### getStringArrayByName9+
-
-getStringArrayByName(resName: string, callback: AsyncCallback<Array<string>>): void
-
-Obtains the string array corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
-
-**System capability**: SystemCapability.Global.ResourceManager
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------------------------- | ---- | ----------------- |
-| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the result.|
-
-**Error codes**
-
-For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
-
-| ID| Error Message|
-| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
-**Example**
- ```ts
try {
- this.context.resourceManager.getStringArrayByName("test", (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let strArray = value;
- }
- });
+ this.context.resourceManager.getMediaContentBase64Sync($r('app.media.test').id, 120); // Specified screen density
} catch (error) {
- console.error(`callback getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getStringArrayByName9+
+### getMediaContentBase64Sync10+
-getStringArrayByName(resName: string): Promise<Array<string>>
+getMediaContentBase64Sync(resource: Resource, density?: number): string
-Obtains the string array corresponding to the specified resource name. This API uses a promise to return the result.
+Obtains the Base64 code of the image (with the default or specified screen density) corresponding to the specified resource object.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
+| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
-| Type | Description |
-| ---------------------------------- | ------------ |
-| Promise<Array<string>> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | ----------- |
+| string | Base64 code of the media file corresponding to the specified resource object.|
**Error codes**
@@ -2170,37 +2212,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getStringArrayByName("test").then(value => {
- let strArray = value;
- }).catch(error => {
- console.log("getStringArrayByName promise error is " + error);
- });
+ this.context.resourceManager.getMediaContentBase64Sync(resource); // Default screen density
} catch (error) {
- console.error(`promise getStringArrayByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+
+ try {
+ this.context.resourceManager.getMediaContentBase64Sync(resource, 120); // Specified screen density
+ } catch (error) {
+ console.error(`getMediaContentBase64Sync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaByName9+
+### getMediaContentBase649+
-getMediaByName(resName: string, callback: AsyncCallback<Uint8Array>): void
+getMediaContentBase64(resId: number, callback: AsyncCallback<string>): void
-Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------- | ---- | ------------------ |
-| resName | string | Yes | Resource name. |
-| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------ |
+| resId | number | Yes | Resource ID. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -2208,39 +2256,39 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaByName("test", (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let media = value;
- }
+ this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaByName10+
+### getMediaContentBase6410+
-getMediaByName(resName: string, density: number, callback: AsyncCallback<Uint8Array>): void
+getMediaContentBase64(resId: number, density: number, callback: AsyncCallback<string>): void
-Obtains the content of the media file with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
+Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------------- | ---- | ------------------ |
-| resName | string | Yes | Resource name. |
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------ |
+| resId | number | Yes | Resource ID. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
-| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -2248,43 +2296,43 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaByName("test", 120, (error, value) => {
- if (error != null) {
- console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
- } else {
- let media = value;
- }
+ this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120, (error, value) => {
+ if (error != null) {
+ console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`callback getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaByName9+
+### getMediaContentBase649+
-getMediaByName(resName: string): Promise<Uint8Array>
+getMediaContentBase64(resId: number): Promise<string>
-Obtains the content of the media file corresponding to the specified resource name. This API uses a promise to return the result.
+Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
**Return value**
-| Type | Description |
-| ------------------------- | ------------- |
-| Promise<Uint8Array> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | -------------------- |
+| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -2292,42 +2340,42 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaByName("test").then(value => {
- let media = value;
+ this.context.resourceManager.getMediaContentBase64($r('app.media.test').id).then(value => {
+ let media = value;
}).catch(error => {
- console.log("getMediaByName promise error is " + error);
+ console.log("getMediaContentBase64 promise error is " + error);
});
} catch (error) {
- console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`)
+ console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaByName10+
+### getMediaContentBase6410+
-getMediaByName(resName: string, density: number): Promise<Uint8Array>
+getMediaContentBase64(resId: number, density: number): Promise<string>
-Obtains the content of the media file with the screen density corresponding to the specified resource name. This API uses a promise to return the result.
+Obtains the Base64 code of an image with the screen density corresponding to the specified resource ID. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
-| Type | Description |
-| ------------------------- | ------------- |
-| Promise<Uint8Array> | Promise used to return the result.|
+| Type | Description |
+| --------------------- | -------------------- |
+| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -2335,35 +2383,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
- this.context.resourceManager.getMediaByName("test", 120).then(value => {
- let media = value;
+ this.context.resourceManager.getMediaContentBase64($r('app.media.test').id, 120).then(value => {
+ let media = value;
}).catch(error => {
- console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
- console.error(`promise getMediaByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaBase64ByName9+
+### getMediaContentBase649+
-getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void
+getMediaContentBase64(resource: Resource, callback: AsyncCallback<string>): void
-Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
+Obtains the Base64 code of the image corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
-| resName | string | Yes | Resource name. |
+| resource | [Resource](#resource9) | Yes | Resource object. |
| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -2372,37 +2422,44 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getMediaBase64ByName("test", (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let media = value;
- }
+ this.context.resourceManager.getMediaContentBase64(resource, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaBase64ByName10+
+### getMediaContentBase6410+
-getMediaBase64ByName(resName: string, density: number, callback: AsyncCallback<string>): void
+getMediaContentBase64(resource: Resource, density: number, callback: AsyncCallback<string>): void
-Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
+Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | --------------------------- | ---- | ------------------------ |
-| resName | string | Yes | Resource name. |
+| resource | [Resource](#resource9) | Yes | Resource object. |
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
@@ -2412,42 +2469,49 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getMediaBase64ByName("test", 120, (error, value) => {
- if (error != null) {
- console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
- } else {
- let media = value;
- }
+ this.context.resourceManager.getMediaContentBase64(resource, 120, (error, value) => {
+ if (error != null) {
+ console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaBase64ByName9+
+### getMediaContentBase649+
-getMediaBase64ByName(resName: string): Promise<string>
+getMediaContentBase64(resource: Resource): Promise<string>
-Obtains the Base64 code of the image corresponding to the specified resource name. This API uses a promise to return the result.
+Obtains the Base64 code of the image corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | ---- | ---- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
**Return value**
-| Type | Description |
-| --------------------- | ------------------- |
+| Type | Description |
+| --------------------- | ------------------------- |
| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -2456,41 +2520,48 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getMediaBase64ByName("test").then(value => {
- let media = value;
+ this.context.resourceManager.getMediaContentBase64(resource).then(value => {
+ let media = value;
}).catch(error => {
- console.log("getMediaBase64ByName promise error is " + error);
+ console.log("getMediaContentBase64 promise error is " + error);
});
} catch (error) {
- console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getMediaBase64ByName10+
+### getMediaContentBase6410+
-getMediaBase64ByName(resName: string, density: number): Promise<string>
+getMediaContentBase64(resource: Resource, density: number): Promise<string>
-Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses a promise to return the result.
+Obtains the Base64 code of an image with the screen density corresponding to the specified resource object. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
+**Model restriction**: This API can be used only in the stage model.
+
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------- | ---- | ---- |
+| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
-| Type | Description |
-| --------------------- | ------------------- |
+| Type | Description |
+| --------------------- | ------------------------- |
| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -2499,36 +2570,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
+| 9001001 | If the resId invalid. |
+| 9001002 | If the resource not found by resId. |
**Example**
```ts
+ let resource = {
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.test').id
+ };
try {
- this.context.resourceManager.getMediaBase64ByName("test", 120).then(value => {
- let media = value;
+ this.context.resourceManager.getMediaContentBase64(resource, 120).then(value => {
+ let media = value;
}).catch(error => {
- console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
});
} catch (error) {
- console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaContentBase64 failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getPluralStringByName9+
+### getMediaBase64ByName9+
-getPluralStringByName(resName: string, num: number, callback: AsyncCallback<string>): void
+getMediaBase64ByName(resName: string, callback: AsyncCallback<string>): void
-Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses an asynchronous callback to return the result.
+Obtains the Base64 code of the image corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | --------------------------- | ---- | ----------------------------- |
-| resName | string | Yes | Resource name. |
-| num | number | Yes | Number. |
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------ |
+| resName | string | Yes | Resource name. |
| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -2539,44 +2614,37 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getPluralStringByName("test", 1, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
+ this.context.resourceManager.getMediaBase64ByName("test", (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`callback getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
}
-
```
-### getPluralStringByName9+
+### getMediaBase64ByName10+
-getPluralStringByName(resName: string, num: number): Promise<string>
+getMediaBase64ByName(resName: string, density: number, callback: AsyncCallback<string>): void
-Obtains the plural string corresponding to the specified resource name based on the specified number. This API uses a promise to return the result.
+Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
-| num | number | Yes | Number. |
-
-**Return value**
-
-| Type | Description |
-| --------------------- | ---------------------- |
-| Promise<string> | Promise used to return the result.|
+| Name | Type | Mandatory | Description |
+| -------- | --------------------------- | ---- | ------------------------ |
+| resName | string | Yes | Resource name. |
+| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
+| callback | AsyncCallback<string> | Yes | Callback used to return the result.|
**Error codes**
@@ -2586,40 +2654,41 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getPluralStringByName("test", 1).then(value => {
- let str = value;
- }).catch(error => {
- console.log("getPluralStringByName promise error is " + error);
+ this.context.resourceManager.getMediaBase64ByName("test", 120, (error, value) => {
+ if (error != null) {
+ console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
+ } else {
+ let media = value;
+ }
});
} catch (error) {
- console.error(`promise getPluralStringByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`callback getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getStringSync9+
+### getMediaBase64ByName9+
-getStringSync(resId: number): string
+getMediaBase64ByName(resName: string): Promise<string>
-Obtains the string corresponding to the specified resource ID. This API returns the result synchronously.
+Obtains the Base64 code of the image corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ----- | ------ | ---- | ----- |
-| resId | number | Yes | Resource ID.|
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
**Return value**
-| Type | Description |
-| ------ | ----------- |
-| string | String corresponding to the specified resource ID.|
+| Type | Description |
+| --------------------- | ------------------- |
+| Promise<string> | Promise used to return the result.|
**Error codes**
@@ -2627,81 +2696,85 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
- this.context.resourceManager.getStringSync($r('app.string.test').id);
+ this.context.resourceManager.getMediaBase64ByName("test").then(value => {
+ let media = value;
+ }).catch(error => {
+ console.log("getMediaBase64ByName promise error is " + error);
+ });
} catch (error) {
- console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getStringSync10+
+### getMediaBase64ByName10+
-getStringSync(resId: number, ...args: Array): string
+getMediaBase64ByName(resName: string, density: number): Promise<string>
-Obtains the string corresponding to the specified resource ID and formats the string based on **args**. This API returns the result synchronously.
+Obtains the Base64 code of an image with the screen density corresponding to the specified resource name. This API uses a promise to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ----- | ------ | ---- | ----- |
-| resId | number | Yes | Resource ID.|
-| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.|
+| Name | Type | Mandatory | Description |
+| ------- | ------ | ---- | ---- |
+| resName | string | Yes | Resource name.|
+| [density](#screendensity) | number | Yes | Screen density. The value **0** indicates the default screen density. |
**Return value**
-| Type | Description |
-| ------ | ---------------------------- |
-| string | Formatted string.|
+| Type | Description |
+| --------------------- | ------------------- |
+| Promise<string> | Promise used to return the result.|
**Error codes**
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
| ID| Error Message|
-| -------- | ----------------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
-| 9001007 | If the resource obtained by resId formatting error. |
+| -------- | ---------------------------------------- |
+| 9001003 | If the resName invalid. |
+| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
- this.context.resourceManager.getStringSync($r('app.string.test').id, "format string", 10, 98.78);
+ this.context.resourceManager.getMediaBase64ByName("test", 120).then(value => {
+ let media = value;
+ }).catch(error => {
+ console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
+ });
} catch (error) {
- console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getMediaBase64ByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getStringSync9+
+### getDrawableDescriptor10+
-getStringSync(resource: Resource): string
+getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor;
-Obtains the string corresponding to the specified resource object. This API returns the result synchronously.
+Obtains the **DrawableDescriptor** object corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
-
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | ---- | ---- |
-| resource | [Resource](#resource9) | Yes | Resource object.|
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ----- |
+| resId | number | Yes | Resource ID.|
+| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
-| Type | Description |
-| ------ | ---------------- |
-| string | String corresponding to the specified resource object.|
+| Type | Description |
+| ------ | ---------- |
+| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
**Error codes**
@@ -2711,27 +2784,26 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.string.test').id
- };
try {
- this.context.resourceManager.getStringSync(resource);
+ this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id);
} catch (error) {
- console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ try {
+ this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id, 120);
+ } catch (error) {
+ console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getStringSync10+
+### getDrawableDescriptor10+
-getStringSync(resource: Resource, ...args: Array): string
+getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor;
-Obtains the string corresponding to the specified resource object and formats the string based on **args**. This API returns the result synchronously.
+Obtains the **DrawableDescriptor** object corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -2742,13 +2814,13 @@ Obtains the string corresponding to the specified resource object and formats th
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
-| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.|
+| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
-| Type | Description |
-| ------ | ---------------------------- |
-| string | Formatted string.|
+| Type | Description |
+| ------- | ----------------- |
+| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
**Error codes**
@@ -2758,28 +2830,31 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
-| 9001007 | If the resource obtained by resId formatting error. |
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.string.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.media.icon').id
};
try {
- this.context.resourceManager.getStringSync(resource, "format string", 10, 98.78);
+ this.context.resourceManager.getDrawableDescriptor(resource);
} catch (error) {
- console.error(`getStringSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
}
- ```
+ try {
+ this.context.resourceManager.getDrawableDescriptor(resource, 120);
+ } catch (error) {
+ console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
-### getStringByNameSync9+
+### getDrawableDescriptorByName10+
-getStringByNameSync(resName: string): string
+getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor;
-Obtains the string corresponding to the specified resource name. This API returns the result synchronously.
+Obtains the **DrawableDescriptor** object corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -2788,12 +2863,13 @@ Obtains the string corresponding to the specified resource name. This API return
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
+| [density](#screendensity) | number | No | Screen density. The default value or value **0** indicates the default screen density.|
**Return value**
-| Type | Description |
-| ------ | ---------- |
-| string | String corresponding to the specified resource name.|
+| Type | Description |
+| ------ | --------- |
+| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
**Error codes**
@@ -2803,57 +2879,20 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getStringByNameSync("test");
+ this.context.resourceManager.getDrawableDescriptorByName('icon');
} catch (error) {
- console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`);
}
- ```
-
-### getStringByNameSync10+
-
-getStringByNameSync(resName: string, ...args: Array): string
-
-Obtains the string corresponding to the specified resource name and formats the string based on **args**. This API returns the result synchronously.
-
-**System capability**: SystemCapability.Global.ResourceManager
-
-**Parameters**
-
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
-| args | Array | No | Arguments for formatting strings.
Supported arguments:
-%d, %f, %s, and %%
Note: **%%** is used to translate **%**.
Example: **%%d** is translated into the **%d** string.|
-
-**Return value**
-
-| Type | Description |
-| ------ | ---------------------------- |
-| string | Formatted string.|
-
-**Error codes**
-
-For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
-
-| ID| Error Message|
-| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
-| 9001008 | If the resource obtained by resName formatting error. |
-
-**Example**
- ```ts
try {
- this.context.resourceManager.getStringByNameSync("test", "format string", 10, 98.78);
+ this.context.resourceManager.getDrawableDescriptorByName('icon', 120);
} catch (error) {
- console.error(`getStringByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`);
}
- ```
+ ```
### getBoolean9+
@@ -2928,9 +2967,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.boolean.boolean_test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.boolean.boolean_test').id
};
try {
this.context.resourceManager.getBoolean(resource);
@@ -3058,9 +3097,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.integer.integer_test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.integer.integer_test').id
};
try {
this.context.resourceManager.getNumber(resource);// integer refers to the original value; float refers to the actual pixel value.
@@ -3114,11 +3153,11 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
}
```
-### getDrawableDescriptor10+
+### getColorSync10+
-getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor;
+getColorSync(resId: number) : number;
-Obtains the **DrawableDescriptor** object corresponding to the specified resource ID. This API returns the result synchronously.
+Obtains the color value corresponding to the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -3127,13 +3166,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
-| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
-| Type | Description |
-| ------ | ---------- |
-| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
+| Type | Description |
+| ------ | ----------- |
+| number | Color value corresponding to the resource ID (decimal).|
**Error codes**
@@ -3143,26 +3181,22 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id);
- } catch (error) {
- console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
- }
- try {
- this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id, 120);
+ this.context.resourceManager.getColorSync($r('app.color.test').id);
} catch (error) {
- console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getDrawableDescriptor10+
+### getColorSync10+
-getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor;
+getColorSync(resource: Resource): number
-Obtains the **DrawableDescriptor** object corresponding to the specified resource object. This API returns the result synchronously.
+Obtains the color value corresponding to the specified resource object. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -3173,13 +3207,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
-| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
-| Type | Description |
-| ------- | ----------------- |
-| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
+| Type | Description |
+| ------ | ---------------- |
+| number | Color value corresponding to the resource object (decimal).|
**Error codes**
@@ -3189,31 +3222,27 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.media.icon').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.color.test').id
};
try {
- this.context.resourceManager.getDrawableDescriptor(resource);
- } catch (error) {
- console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
- }
- try {
- this.context.resourceManager.getDrawableDescriptor(resource, 120);
+ this.context.resourceManager.getColorSync(resource);
} catch (error) {
- console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getDrawableDescriptorByName10+
+### getColorByNameSync10+
-getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor;
+getColorByNameSync(resName: string) : number;
-Obtains the **DrawableDescriptor** object corresponding to the specified resource name. This API returns the result synchronously.
+Obtains the color value corresponding to the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
@@ -3222,13 +3251,12 @@ Obtains the **DrawableDescriptor** object corresponding to the specified resourc
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
-| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
-| Type | Description |
-| ------ | --------- |
-| DrawableDescriptor | **DrawableDescriptor** object corresponding to the specified resource ID.|
+| Type | Description |
+| ------ | ---------- |
+| number | Color value corresponding to the resource name (decimal).|
**Error codes**
@@ -3238,18 +3266,14 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
+| 9001006 | If the resource re-ref too much. |
**Example**
```ts
try {
- this.context.resourceManager.getDrawableDescriptorByName('icon');
- } catch (error) {
- console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`);
- }
- try {
- this.context.resourceManager.getDrawableDescriptorByName('icon', 120);
+ this.context.resourceManager.getColorByNameSync("test");
} catch (error) {
- console.error(`getDrawableDescriptorByName failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -3280,17 +3304,17 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example (stage)**
```ts
- try {
- this.context.resourceManager.getColor($r('app.color.test').id, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
- });
- } catch (error) {
- console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`);
- }
+ try {
+ this.context.resourceManager.getColor($r('app.color.test').id, (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
+ });
+ } catch (error) {
+ console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`);
+ }
```
### getColor10+
@@ -3311,7 +3335,7 @@ Obtains the color value corresponding to the specified resource ID. This API use
| Type | Description |
| --------------------- | ----------- |
-| Promise<number> | Color value corresponding to the resource ID (decimal).|
+| Promise<number> | Promise used to return the result.|
**Error codes**
@@ -3327,9 +3351,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
```ts
try {
this.context.resourceManager.getColor($r('app.color.test').id).then(value => {
- let str = value;
+ let str = value;
}).catch(error => {
- console.log("getColor promise error is " + error);
+ console.log("getColor promise error is " + error);
});
} catch (error) {
console.error(`promise getColor failed, error code: ${error.code}, message: ${error.message}.`);
@@ -3366,17 +3390,17 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.color.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.color.test').id
};
try {
this.context.resourceManager.getColor(resource, (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let str = value;
- }
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let str = value;
+ }
});
} catch (error) {
console.error(`callback getColor failed, error code: ${error.code}, message: ${error.message}.`);
@@ -3403,7 +3427,7 @@ Obtains the color value corresponding to the specified resource object. This API
| Type | Description |
| --------------------- | ---------------- |
-| Promise<number> | Color value corresponding to the resource object (decimal).|
+| Promise<number> | Promise used to return the result.|
**Error codes**
@@ -3418,9 +3442,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
**Example**
```ts
let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.color.test').id
+ bundleName: "com.example.myapplication",
+ moduleName: "entry",
+ id: $r('app.color.test').id
};
try {
this.context.resourceManager.getColor(resource).then(value => {
@@ -3462,11 +3486,11 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
```ts
try {
this.context.resourceManager.getColorByName("test", (error, value) => {
- if (error != null) {
- console.log("error is " + error);
- } else {
- let string = value;
- }
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let string = value;
+ }
});
} catch (error) {
console.error(`callback getColorByName failed, error code: ${error.code}, message: ${error.message}.`);
@@ -3491,7 +3515,7 @@ Obtains the color value corresponding to the specified resource name. This API u
| Type | Description |
| --------------------- | ---------- |
-| Promise<number> | Color value corresponding to the resource name (decimal).|
+| Promise<number> | Promise used to return the result.|
**Error codes**
@@ -3507,34 +3531,34 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
```ts
try {
this.context.resourceManager.getColorByName("test").then(value => {
- let string = value;
+ let string = value;
}).catch(error => {
- console.log("getColorByName promise error is " + error);
+ console.log("getColorByName promise error is " + error);
});
} catch (error) {
console.error(`promise getColorByName failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getColorSync10+
+### getRawFileContentSync10+
-getColorSync(resId: number) : number;
+getRawFileContentSync(path: string): Uint8Array
-Obtains the color value corresponding to the specified resource ID. This API returns the result synchronously.
+Obtains the content of the raw file in the **resources/rawfile** directory. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ----- | ------ | ---- | ----- |
-| resId | number | Yes | Resource ID.|
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ----------------------- |
+| path | string | Yes | Path of the raw file. |
**Return value**
-| Type | Description |
-| ------ | ----------- |
-| number | Color value corresponding to the resource ID (decimal).|
+| Type | Description |
+| --------------------- | ---------- |
+| Uint8Array | Content of the raw file.|
**Error codes**
@@ -3542,40 +3566,74 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
+| 9001005 | If the resource not found by path. |
**Example**
```ts
try {
- this.context.resourceManager.getColorSync($r('app.color.test').id);
+ this.context.resourceManager.getRawFileContentSync("test.txt");
} catch (error) {
- console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getRawFileContentSync failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getColorSync10+
+### getRawFileContent9+
-getColorSync(resource: Resource): number
+getRawFileContent(path: string, callback: AsyncCallback<Uint8Array>): void
-Obtains the color value corresponding to the specified resource object. This API returns the result synchronously.
+Obtains the content of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
-**Model restriction**: This API can be used only in the stage model.
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ----------------------- |
+| path | string | Yes | Path of the raw file. |
+| callback | AsyncCallback<Uint8Array> | Yes | Callback used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | If the resource not found by path. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getRawFileContent("test.xml", (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ } else {
+ let rawFile = value;
+ }
+ });
+ } catch (error) {
+ console.error(`callback getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getRawFileContent9+
+
+getRawFileContent(path: string): Promise<Uint8Array>
+
+Obtains the content of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ---------------------- | ---- | ---- |
-| resource | [Resource](#resource9) | Yes | Resource object.|
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ----------- |
+| path | string | Yes | Path of the raw file.|
**Return value**
-| Type | Description |
-| ------ | ---------------- |
-| number | Color value corresponding to the resource object (decimal).|
+| Type | Description |
+| ------------------------- | ----------- |
+| Promise<Uint8Array> | Promise used to return the result.|
**Error codes**
@@ -3583,43 +3641,40 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001001 | If the resId invalid. |
-| 9001002 | If the resource not found by resId. |
-| 9001006 | If the resource re-ref too much. |
+| 9001005 | If the resource not found by path. |
**Example**
```ts
- let resource = {
- bundleName: "com.example.myapplication",
- moduleName: "entry",
- id: $r('app.color.test').id
- };
try {
- this.context.resourceManager.getColorSync(resource);
+ this.context.resourceManager.getRawFileContent("test.xml").then(value => {
+ let rawFile = value;
+ }).catch(error => {
+ console.log("getRawFileContent promise error is " + error);
+ });
} catch (error) {
- console.error(`getColorSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`promise getRawFileContent failed, error code: ${error.code}, message: ${error.message}.`);
}
```
-### getColorByNameSync10+
+### getRawFileListSync10+
-getColorByNameSync(resName: string) : number;
+getRawFileListSync(path: string): Array\
-Obtains the color value corresponding to the specified resource name. This API returns the result synchronously.
+Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ------ | ---- | ---- |
-| resName | string | Yes | Resource name.|
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ----------------------- |
+| path | string | Yes | Path of the **rawfile** folder. |
**Return value**
-| Type | Description |
-| ------ | ---------- |
-| number | Color value corresponding to the resource name (decimal).|
+| Type | Description |
+| ------------------------- | ----------- |
+| Array\ | List of files in the **resources/rawfile** directory.|
**Error codes**
@@ -3627,16 +3682,454 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
| ID| Error Message|
| -------- | ---------------------------------------- |
-| 9001003 | If the resName invalid. |
-| 9001004 | If the resource not found by resName. |
-| 9001006 | If the resource re-ref too much. |
+| 9001005 | If the resource not found by path. |
**Example**
```ts
- try {
- this.context.resourceManager.getColorByNameSync("test");
+ try { // Passing "" means to obtain the list of files in the root directory of the raw file.
+ this.context.resourceManager.getRawFileListSync("")
} catch (error) {
- console.error(`getColorByNameSync failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`getRawFileListSync failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getRawFileList10+
+
+getRawFileList(path: string, callback: AsyncCallback<Array\>): void;
+
+Obtains the list of files in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------------- | ---- | ----------------------- |
+| path | string | Yes | Path of the **rawfile** folder. |
+| callback | AsyncCallback<Array\> | Yes| Callback used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | If the resource not found by path. |
+
+**Example**
+ ```ts
+ try { // Passing "" means to obtain the list of files in the root directory of the raw file.
+ this.context.resourceManager.getRawFileList("", (error, value) => {
+ if (error != null) {
+ console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
+ } else {
+ let rawFile = value;
+ }
+ });
+ } catch (error) {
+ console.error(`callback getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getRawFileList10+
+
+getRawFileList(path: string): Promise<Array\>
+
+Obtains the list of files in the **resources/rawfile** directory. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ----------- |
+| path | string | Yes | Path of the **rawfile** folder.|
+
+**Return value**
+
+| Type | Description |
+| ------------------------- | ----------- |
+| Promise<Array\> | Promise used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | If the resource not found by path. |
+
+**Example**
+ ```ts
+ try { // Passing "" means to obtain the list of files in the root directory of the raw file.
+ this.context.resourceManager.getRawFileList("").then(value => {
+ let rawFile = value;
+ }).catch(error => {
+ console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
+ });
+ } catch (error) {
+ console.error(`promise getRawFileList failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getRawFdSync10+
+
+getRawFdSync(path: string): RawFileDescriptor
+
+Obtains the descriptor of the raw file in the **resources/rawfile** directory.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | -------------------------------- |
+| path | string | Yes | Path of the raw file. |
+
+**Return value**
+
+| Type | Description |
+| ------------------------- | ----------- |
+| [RawFileDescriptor](#rawfiledescriptor8) | Descriptor of the raw file.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | If the resource not found by path. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getRawFdSync("test.txt");
+ } catch (error) {
+ console.error(`getRawFdSync failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getRawFd9+
+
+getRawFd(path: string, callback: AsyncCallback<RawFileDescriptor>): void
+
+Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | -------------------------------- |
+| path | string | Yes | Path of the raw file. |
+| callback | AsyncCallback<[RawFileDescriptor](#rawfiledescriptor8)> | Yes | Callback used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | If the resource not found by path. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getRawFd("test.xml", (error, value) => {
+ if (error != null) {
+ console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`);
+ } else {
+ let fd = value.fd;
+ let offset = value.offset;
+ let length = value.length;
+ }
+ });
+ } catch (error) {
+ console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getRawFd9+
+
+getRawFd(path: string): Promise<RawFileDescriptor>
+
+Obtains the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ----------- |
+| path | string | Yes | Path of the raw file.|
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------------- | ------------------- |
+| Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | If the resource not found by path. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getRawFd("test.xml").then(value => {
+ let fd = value.fd;
+ let offset = value.offset;
+ let length = value.length;
+ }).catch(error => {
+ console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`);
+ });
+ } catch (error) {
+ console.error(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### closeRawFdSync10+
+
+closeRawFdSync(path: string): void
+
+Closes the descriptor of the raw file in the **resources/rawfile** directory.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------- | ---- | ----------- |
+| path | string | Yes | Path of the raw file.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | The resource not found by path. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.closeRawFdSync("test.txt");
+ } catch (error) {
+ console.error(`closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### closeRawFd9+
+
+closeRawFd(path: string, callback: AsyncCallback<void>): void
+
+Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ------------------------- | ---- | ----------- |
+| path | string | Yes | Path of the raw file.|
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | The resource not found by path. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.closeRawFd("test.xml", (error, value) => {
+ if (error != null) {
+ console.log("error is " + error);
+ }
+ });
+ } catch (error) {
+ console.error(`callback closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### closeRawFd9+
+
+closeRawFd(path: string): Promise<void>
+
+Closes the descriptor of the raw file in the **resources/rawfile** directory. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ----------- |
+| path | string | Yes | Path of the raw file.|
+
+**Return value**
+
+| Type | Description |
+| ------------------- | ---- |
+| Promise<void> | Promise that returns no value.|
+
+**Error codes**
+
+For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
+
+| ID| Error Message|
+| -------- | ---------------------------------------- |
+| 9001005 | If the resource not found by path. |
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.closeRawFd("test.xml").then(value => {
+ let result = value;
+ }).catch(error => {
+ console.log("closeRawFd promise error is " + error);
+ });
+ } catch (error) {
+ console.error(`promise closeRawFd failed, error code: ${error.code}, message: ${error.message}.`);
+ }
+ ```
+
+### getConfiguration
+
+getConfiguration(callback: AsyncCallback<Configuration>): void
+
+Obtains the device configuration. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ------------------------- |
+| callback | AsyncCallback<[Configuration](#configuration)> | Yes | Callback used to return the result.|
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getConfiguration((error, value) => {
+ if (error != null) {
+ console.error("getConfiguration callback error is " + error);
+ } else {
+ let direction = value.direction;
+ let locale = value.locale;
+ }
+ });
+ } catch (error) {
+ console.error("getConfiguration callback error is " + error);
+ }
+ ```
+
+### getConfiguration
+
+getConfiguration(): Promise<Configuration>
+
+Obtains the device configuration. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------------- | ---------------- |
+| Promise<[Configuration](#configuration)> | Promise used to return the result.|
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getConfiguration().then(value => {
+ let direction = value.direction;
+ let locale = value.locale;
+ }).catch(error => {
+ console.error("getConfiguration promise error is " + error);
+ });
+ } catch (error) {
+ console.error("getConfiguration promise error is " + error);
+ }
+ ```
+
+### getDeviceCapability
+
+getDeviceCapability(callback: AsyncCallback<DeviceCapability>): void
+
+Obtains the device capability. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| -------- | ---------------------------------------- | ---- | ---------------------------- |
+| callback | AsyncCallback<[DeviceCapability](#devicecapability)> | Yes | Callback used to return the result.|
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getDeviceCapability((error, value) => {
+ if (error != null) {
+ console.error("getDeviceCapability callback error is " + error);
+ } else {
+ let screenDensity = value.screenDensity;
+ let deviceType = value.deviceType;
+ }
+ });
+ } catch (error) {
+ console.error("getDeviceCapability callback error is " + error);
+ }
+ ```
+
+### getDeviceCapability
+
+getDeviceCapability(): Promise<DeviceCapability>
+
+Obtains the device capability. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------------- | ------------------- |
+| Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.|
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.getDeviceCapability().then(value => {
+ let screenDensity = value.screenDensity;
+ let deviceType = value.deviceType;
+ }).catch(error => {
+ console.error("getDeviceCapability promise error is " + error);
+ });
+ } catch (error) {
+ console.error("getDeviceCapability promise error is " + error);
+ }
+ ```
+
+### release7+
+
+release()
+
+Releases a created **resourceManager** object.
+
+**System capability**: SystemCapability.Global.ResourceManager
+
+**Example**
+ ```ts
+ try {
+ this.context.resourceManager.release();
+ } catch (error) {
+ console.error("release error is " + error);
}
```
@@ -3666,9 +4159,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
```ts
let path = getContext().bundleCodeDir + "/library1-default-signed.hsp";
try {
- this.context.resourceManager.addResource(path);
+ this.context.resourceManager.addResource(path);
} catch (error) {
- console.error(`addResource failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`addResource failed, error code: ${error.code}, message: ${error.message}.`);
}
```
@@ -3698,9 +4191,9 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
```ts
let path = getContext().bundleCodeDir + "/library1-default-signed.hsp";
try {
- this.resmgr.removeResource(path);
+ this.resmgr.removeResource(path);
} catch (error) {
- console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`);
+ console.error(`removeResource failed, error code: ${error.code}, message: ${error.message}.`);
}
```
diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md
index d61b8272edee9b2b522139a9976df17027be98a5..99eb42bd5720fa12a833abcc030b45d02c7aefaf 100644
--- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md
+++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md
@@ -1,16 +1,9 @@
# @ohos.resourceschedule.backgroundTaskManager (Background Task Management)
-The **BackgroundTaskManager** module provides APIs to manage background tasks.
-
-If a service needs to be continued when the application or service module is running in the background (not visible to users), the application or service module can request a transient task to delay the suspension or a continuous task to prevent the suspension.
-
-If an application has a task that needs to be continued when the application is switched to the background and can be completed within a short period of time, the application can request a transient task. For example, if a user chooses to clear junk files in the **Files** application and exits the application, the application can request a transient task to complete the cleanup.
-
-If an application has a service that can be intuitively perceived by users and needs to run in the background for a long period of time (for example, music playback in the background), the application can request a continuous task.
-
-If a privileged system application needs to use certain system resources (for example, it wants to receive common events when suspended), it can request efficiency resources.
+The **backgroundTaskManager** module provides APIs to request background tasks. You can use the APIs to request transient tasks, continuous tasks, or efficiency resources to prevent the application process from being terminated or suspended when your application is switched to the background.
> **NOTE**
+>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -24,9 +17,11 @@ import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'
requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspendInfo
-Requests delayed suspension after the application switches to the background.
+Requests a transient task.
-The default duration of delayed suspension is 3 minutes when the battery level is higher than or equal to the broadcast low battery level and 1 minute when the battery level is lower than the broadcast low battery level.
+> **NOTE**
+>
+> The maximum duration of a transient task is 3 minutes in normal cases. In the case of a [low battery](js-apis-battery-info.md), the maximum duration is decreased to 1 minute.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
@@ -34,14 +29,14 @@ The default duration of delayed suspension is 3 minutes when the battery level i
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------ |
-| reason | string | Yes | Reason for delayed transition to the suspended state. |
-| callback | Callback<void> | Yes | Invoked when a delay is about to time out. Generally, this callback is used to notify the application 6 seconds before the delay times out.|
+| reason | string | Yes | Reason for requesting the transient task. |
+| callback | Callback<void> | Yes | Callback used to notify the application that the transient task is about to time out. Generally, the callback is invoked 6 seconds before the timeout.|
**Return value**
| Type | Description |
| ------------------------------------- | --------- |
-| [DelaySuspendInfo](#delaysuspendinfo) | Information about the suspension delay.|
+| [DelaySuspendInfo](#delaysuspendinfo) | Information about the transient task.|
**Error codes**
@@ -80,7 +75,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): void
-Obtains the remaining duration before the application is suspended. This API uses an asynchronous callback to return the result.
+Obtains the remaining time of a transient task. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
@@ -88,8 +83,8 @@ Obtains the remaining duration before the application is suspended. This API use
| Name | Type | Mandatory | Description |
| --------- | --------------------------- | ---- | ---------------------------------------- |
-| requestId | number | Yes | ID of the suspension delay request. |
-| callback | AsyncCallback<number> | Yes | Callback used to return the remaining duration before the application is suspended, in milliseconds.|
+| requestId | number | Yes | Request ID of the transient task. |
+| callback | AsyncCallback<number> | Yes | Callback used to return the remaining time, in milliseconds.|
**Error codes**
@@ -129,9 +124,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
getRemainingDelayTime(requestId: number): Promise<number>
-Obtains the remaining duration before the application is suspended. This API uses a promise to return the result.
-
-
+Obtains the remaining time of a transient task. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
@@ -139,13 +132,13 @@ Obtains the remaining duration before the application is suspended. This API use
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------- |
-| requestId | number | Yes | ID of the suspension delay request.|
+| requestId | number | Yes | Request ID of the transient task.|
**Return value**
| Type | Description |
| --------------------- | ---------------------------------------- |
-| Promise<number> | Promise used to return the remaining duration before the application is suspended, in milliseconds.|
+| Promise<number> | Promise used to return the remaining time, in milliseconds.|
**Error codes**
@@ -182,7 +175,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
cancelSuspendDelay(requestId: number): void
-Cancels the suspension delay.
+Cancels a transient task.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
@@ -190,7 +183,7 @@ Cancels the suspension delay.
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ---------- |
-| requestId | number | Yes | ID of the suspension delay request.|
+| requestId | number | Yes | Request ID of the transient task.|
**Error codes**
@@ -218,12 +211,11 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er
}
```
-
## backgroundTaskManager.startBackgroundRunning
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent, callback: AsyncCallback<void>): void
-Requests a continuous task from the system. This API uses an asynchronous callback to return the result.
+Requests a continuous task. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
@@ -234,9 +226,9 @@ Requests a continuous task from the system. This API uses an asynchronous callba
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).|
-| bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. |
-| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. |
-| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+| bgMode | [BackgroundMode](#backgroundmode) | Yes | Continuous task mode. |
+| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the continuous task is requested, **err** is **undefined**. Otherwise, **err** is an error object. |
**Error codes**
@@ -301,7 +293,7 @@ export default class EntryAbility extends UIAbility {
startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void>
-Requests a continuous task from the system. This API uses a promise to return the result.
+Requests a continuous task. This API uses a promise to return the result.
**Required permissions**: ohos.permission.KEEP_BACKGROUND_RUNNING
@@ -312,14 +304,14 @@ Requests a continuous task from the system. This API uses a promise to return th
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).|
-| bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. |
-| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. |
+| bgMode | [BackgroundMode](#backgroundmode) | Yes | Continuous task mode. |
+| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameters, which are used to specify the target page that is redirected to when a continuous task notification is clicked. |
**Return value**
| Type | Description |
| -------------- | ---------------- |
-| Promise\ | Promise used to return the result.|
+| Promise\ | Promise that returns no value.|
**Error codes**
@@ -380,7 +372,7 @@ export default class EntryAbility extends UIAbility {
stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): void
-Requests to cancel a continuous task. This API uses an asynchronous callback to return the result.
+Cancels a continuous task. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
@@ -389,7 +381,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to
| Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | ---------------------------------------- |
| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-inner-application-context.md).|
-| callback | AsyncCallback<void> | Yes | Callback used to return the result. |
+| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the continuous task is canceled, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes**
@@ -434,9 +426,7 @@ export default class EntryAbility extends UIAbility {
stopBackgroundRunning(context: Context): Promise<void>
-Requests to cancel a continuous task. This API uses a promise to return the result.
-
-
+Cancels a continuous task. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
@@ -450,7 +440,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu
| Type | Description |
| -------------- | ---------------- |
-| Promise\ | Promise used to return the result.|
+| Promise\ | Promise that returns no value.|
**Error codes**
@@ -489,10 +479,9 @@ export default class EntryAbility extends UIAbility {
## backgroundTaskManager.applyEfficiencyResources
-applyEfficiencyResources(request: [EfficiencyResourcesRequest](#efficiencyresourcesrequest)): void
+applyEfficiencyResources(request: EfficiencyResourcesRequest): void
-Requests efficiency resources from the system.
-A process and its application can request the same type of resources at the same time, for example, CPU resources. When the application releases the resources, the same type of resources requested by the process are also released.
+Requests efficiency resources.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
@@ -502,7 +491,7 @@ A process and its application can request the same type of resources at the same
| Name | Type | Mandatory | Description |
| ------- | ------- | ---- | ---------------------------------------- |
-| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest) | Yes | Necessary information carried in the request, including the resource type and timeout interval. For details, see [EfficiencyResourcesRequest](#efficiencyresourcesrequest).|
+| request | [EfficiencyResourcesRequest](#efficiencyresourcesrequest) | Yes | Necessary information carried in the request, including the resource type and timeout interval.|
**Error codes**
@@ -542,7 +531,7 @@ try {
resetAllEfficiencyResources(): void
-Releases all resources that have been requested.
+Releases all efficiency resources.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply
@@ -574,18 +563,19 @@ try {
## DelaySuspendInfo
-Provides the information about the suspension delay.
+Defines the information about the transient task.
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask
| Name | Type | Mandatory | Description |
| --------------- | ------ | ---- | ---------------------------------------- |
-| requestId | number | Yes | ID of the suspension delay request. |
-| actualDelayTime | number | Yes | Actual suspension delay duration of the application, in milliseconds.
The default duration is 180000 when the battery level is higher than or equal to the broadcast low battery level and 60000 when the battery level is lower than the broadcast low battery level.|
-
+| requestId | number | Yes | Request ID of the transient task. |
+| actualDelayTime | number | Yes | Actual duration of the transient task that the application requests, in milliseconds.
The maximum duration of a transient task is 3 minutes in normal cases. In the case of a [low battery](js-apis-battery-info.md), the maximum duration is decreased to 1 minute.|
## BackgroundMode
+Enumerates the continuous task modes.
+
**System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask
| Name | Value | Description |
@@ -596,9 +586,9 @@ Provides the information about the suspension delay.
| LOCATION | 4 | Positioning and navigation. |
| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. |
| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. |
-| WIFI_INTERACTION | 7 | WLAN-related (system API).|
-| VOIP | 8 | Audio and video calls (system API). |
-| TASK_KEEPING | 9 | Computing task (effective only for specific devices). |
+| WIFI_INTERACTION | 7 | WLAN-related.
**System API**: This is a system API.|
+| VOIP | 8 |Audio and video calls.
**System API**: This is a system API.|
+| TASK_KEEPING | 9 | Computing task (for specific devices only). |
## EfficiencyResourcesRequest
@@ -611,10 +601,10 @@ Describes the parameters for requesting efficiency resources.
| Name | Type | Mandatory | Description |
| --------------- | ------ | ---- | ---------------------------------------- |
| resourceTypes | number | Yes | Type of the resource to request. |
-| isApply | boolean | Yes | Whether the request is used to apply for resources. The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources. |
+| isApply | boolean | Yes | Whether the request is used to apply for resources.
The value **true** means that the request is used to apply for resources, and **false** means that the request is used to release resources.|
| timeOut | number | Yes | Duration for which the resource will be used, in milliseconds. |
-| isPersist | boolean | No | Whether the resource is permanently held. If the value is **true**, **timeOut** is invalid. |
-| isProcess | boolean | No | Whether the request is initiated by a process. The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. |
+| isPersist | boolean | No | Whether the resource is permanently held. The default value is **false**.
The value **true** means that the resource is permanently held, and **false** means the resource is held within a given period of time.|
+| isProcess | boolean | No | Whether the request is initiated by a process. The default value is **false**.
The value **true** means that the request is initiated by a process, and **false** means that the request is initiated by an application. |
| reason | string | Yes | Reason for requesting the resource. |
## ResourceType
@@ -627,12 +617,12 @@ Enumerates the efficiency resource types.
| Name | Value | Description |
| ----------------------- | ---- | --------------------- |
-| CPU | 1 | CPU resources, which prevent the application from being suspended. |
-| COMMON_EVENT | 2 | Common events are not proxied when the application is suspended.|
-| TIMER | 4 | System timers are not proxied when the application is suspended.|
-| WORK_SCHEDULER | 8 | Work Scheduler uses a loose control policy by default. For details about the constraints on the Work Scheduler usage, see [Constraints](../../task-management/work-scheduler.md#constraints).|
-| BLUETOOTH | 16 | Bluetooth resources are not proxied when the application is suspended.|
-| GPS | 32 | GPS resources are not proxied when the application is suspended.|
-| AUDIO | 64 | Audio resources are not proxied when the application is suspended.|
+| CPU | 1 | CPU resource. Such type of resource prevents an application from being suspended. |
+| COMMON_EVENT | 2 | Common event resource. Such type of resource ensures that an application in the suspended state can receive common events.|
+| TIMER | 4 | Timer resource. Such type of resource ensures that an application in the suspended state can be woken up by system timers.|
+| WORK_SCHEDULER | 8 | Deferred task resource. Such type of resource provides a loose control policy for an application.|
+| BLUETOOTH | 16 | Bluetooth resource. Such type of resource ensures that an application in the suspended state can be woken up by Bluetooth-related events.|
+| GPS | 32 | GPS resource. Such type of resource ensures that an application in the suspended state can be woken up by GPS-related events.|
+| AUDIO | 64 | Audio resource. Such type of resource prevents an application from being suspended when the application has an audio being played.|
| RUNNING_LOCK10+ | 128 | RUNNING_LOCK resources are not proxied when the application is suspended.|
| SENSOR10+ | 256 | Sensor callbacks are not intercepted.|
diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
index 85c085f6fb9ef65fb711aecbfe3610ab3d17f5d9..5fad64915cde48a0fe0150e83f1661bc0abb1aaa 100644
--- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
+++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md
@@ -1,15 +1,12 @@
# @ohos.resourceschedule.workScheduler (Deferred Task Scheduling)
-The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks.
-
-The system schedules and executes deferred tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
+The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks. You can use the APIs to register tasks that do not have high requirements on real-time performance as deferred tasks. The system schedules and executes the deferred tasks at an appropriate time, subject to the storage space, power consumption, and more.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
+>
> - The APIs of this module can be used only in the stage model.
-> - For details about the constraints on deferred task scheduling, see [Constraints](../../task-management/work-scheduler.md#constraints).
-
## Modules to Import
@@ -18,9 +15,10 @@ import workScheduler from '@ohos.resourceschedule.workScheduler';
```
## workScheduler.startWork
+
startWork(work: WorkInfo): void
-Instructs the WorkSchedulerService to add a task to the execution queue.
+Starts a deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -28,7 +26,7 @@ Instructs the WorkSchedulerService to add a task to the execution queue.
| Name | Type | Mandatory | Description |
| ---- | --------------------- | ---- | -------------- |
-| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.|
+| work | [WorkInfo](#workinfo) | Yes | Deferred task to start.|
**Error codes**
@@ -42,7 +40,6 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700004 | Check workInfo failed. |
| 9700005 | StartWork failed. |
-
**Example**
```js
@@ -69,9 +66,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.stopWork
+
stopWork(work: WorkInfo, needCancel?: boolean): void
-Instructs the WorkSchedulerService to stop a task.
+Stops a deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -79,8 +77,8 @@ Instructs the WorkSchedulerService to stop a task.
| Name | Type | Mandatory | Description |
| ---------- | --------------------- | ---- | ---------- |
-| work | [WorkInfo](#workinfo) | Yes | Task to stop. |
-| needCancel | boolean | No | Whether to cancel the task. The default value is **false**.|
+| work | [WorkInfo](#workinfo) | Yes | Deferred task to stop.|
+| needCancel | boolean | No | Whether to clear the task while stopping it.
The value **true** means to clear the task while stopping it, and **false** means to stop the task only. The default value is **false**.|
**Error codes**
@@ -119,9 +117,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.getWorkStatus
+
getWorkStatus(workId: number, callback : AsyncCallback\): void
-Obtains the latest task status. This API uses an asynchronous callback to return the result.
+Obtains the information a deferred task. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -129,8 +128,8 @@ Obtains the latest task status. This API uses an asynchronous callback to return
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------- |
-| workId | number | Yes | Task ID. |
-| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
+| workId | number | Yes | ID of the deferred task. |
+| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned. Otherwise, an exception is thrown.|
**Error codes**
@@ -162,9 +161,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.getWorkStatus
+
getWorkStatus(workId: number): Promise\
-Obtains the latest task status. This API uses a promise to return the result.
+Obtains the information a deferred task. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -172,13 +172,13 @@ Obtains the latest task status. This API uses a promise to return the result.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
-| workId | number | Yes | Task ID.|
+| workId | number | Yes | ID of the deferred task.|
**Return value**
| Type | Description |
| ------------------------------- | ---------------------------------------- |
-| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
+| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned.|
**Error codes**
@@ -208,9 +208,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.obtainAllWorks
+
obtainAllWorks(callback : AsyncCallback\): Array\
-Obtains all tasks associated with the application. This API uses an asynchronous callback to return the result.
+Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -218,13 +219,13 @@ Obtains all tasks associated with the application. This API uses an asynchronous
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ------------------------------- |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result. If all the deferred tasks are obtained, **err** is **undefined**. Otherwise, **err** is an error object.|
**Return value**
| Type | Description |
| ----------------------------- | --------------- |
-| Array\<[WorkInfo](#workinfo)> | All tasks associated with the application.|
+| Array\<[WorkInfo](#workinfo)> | All the deferred tasks.|
**Error codes**
@@ -253,9 +254,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.obtainAllWorks
+
obtainAllWorks(): Promise\>
-Obtains all tasks associated with the application. This API uses a promise to return the result.
+Obtains all the deferred tasks. This API uses a promise to return the result.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -263,7 +265,7 @@ Obtains all tasks associated with the application. This API uses a promise to re
| Type | Description |
| -------------------------------------- | ------------------------------ |
-| Promise> | Promise used to return all tasks associated with the application.|
+| Promise> | Promise used to return all the deferred tasks.|
**Error codes**
@@ -290,9 +292,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.stopAndClearWorks
+
stopAndClearWorks(): void
-Stops and cancels all tasks associated with the application.
+Stops and clears all the deferred tasks.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -318,6 +321,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.isLastWorkTimeOut
+
isLastWorkTimeOut(workId: number, callback : AsyncCallback\): boolean
Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result.
@@ -328,14 +332,14 @@ Checks whether the last execution of a task timed out. This API uses an asynchro
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ---------------------------------------- |
-| workId | number | Yes | Task ID. |
-| callback | AsyncCallback\ | Yes | Callback used to return the result. |
+| workId | number | Yes | ID of the deferred task. |
+| callback | AsyncCallback\ | Yes | Callback used to return the result.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
-| boolean | Returns **true** if the last execution of the task timed out; returns **false** otherwise.|
+| boolean | The value **true** means that the last execution of the specified task times out, and **false** means the opposite.|
**Error codes**
@@ -365,6 +369,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.isLastWorkTimeOut
+
isLastWorkTimeOut(workId: number): Promise\
Checks whether the last execution of a task timed out. This API uses a promise to return the result.
@@ -375,13 +380,13 @@ Checks whether the last execution of a task timed out. This API uses a promise t
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
-| workId | number | Yes | Task ID.|
+| workId | number | Yes | ID of the deferred task.|
**Return value**
| Type | Description |
| ----------------- | ---------------------------------------- |
-| Promise\ | Promise used to return the result. If the last execution of the task timed out, **true** is returned. Otherwise, **false** is returned.|
+| Promise\ | Promise used to return the result. The value **true** means that the last execution of the specified task times out, and **false** means the opposite.|
**Error codes**
@@ -411,31 +416,33 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## WorkInfo
-Provides detailed information about the task. For details about the constraints on setting the **WorkInfo** parameter, see [Constraints](../../task-management/work-scheduler.md#constraints).
+
+Defines the information about the deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Type | Mandatory | Description |
| --------------- | --------------------------------- | ---- | ---------------- |
-| workId | number | Yes | Task ID. |
+| workId | number | Yes | ID of the deferred task. |
| bundleName | string | Yes | Bundle name of the application that requests the task. |
| abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback.|
| networkType | [NetworkType](#networktype) | No | Network type. |
-| isCharging | boolean | No | Whether the device is charging. |
+| isCharging | boolean | No | Whether the device needs to enter the charging state to trigger deferred task scheduling.
The value **true** means that the device needs to enter the charging state to trigger deferred task scheduling, and **false** means the opposite.|
| chargerType | [ChargingType](#chargingtype) | No | Charging type. |
-| batteryLevel | number | No | Battery level. |
+| batteryLevel | number | No | Battery level. |
| batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. |
| storageRequest | [StorageRequest](#storagerequest) | No | Storage status. |
-| isRepeat | boolean | No | Whether the task is repeated. |
+| isRepeat | boolean | No | Whether the task is repeated.
The value** true** means that the task is repeated, and **false** means the opposite.|
| repeatCycleTime | number | No | Repeat interval. |
| repeatCount | number | No | Number of repeat times. |
-| isPersisted | boolean | No | Whether to enable persistent storage for the task. |
-| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. |
-| idleWaitTime | number | No | Time to wait in the idle state. |
-| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. |
+| isPersisted | boolean | No | Whether to enable persistent storage for the task.
The value **true** means to enable persistent storage for the task, and **false** means the opposite.|
+| isDeepIdle | boolean | No | Whether the device needs to enter the idle state to trigger deferred task scheduling.
The value **true** means that the device needs to enter the idle state to trigger deferred task scheduling, and **false** means the opposite. |
+| idleWaitTime | number | No | Time to wait in the idle state before triggering deferred task scheduling. |
+| parameters | [key: string]: number \| string \| boolean | No | Carried parameters.|
## NetworkType
-Enumerates the network types that can trigger task scheduling.
+
+Enumerates the network types that can trigger deferred task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -449,7 +456,8 @@ Enumerates the network types that can trigger task scheduling.
| NETWORK_TYPE_ETHERNET | 5 | Ethernet. |
## ChargingType
-Enumerates the charging types that can trigger task scheduling.
+
+Enumerates the charging types that can trigger deferred task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -461,7 +469,8 @@ Enumerates the charging types that can trigger task scheduling.
| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. |
## BatteryStatus
-Enumerates the battery states that can trigger task scheduling.
+
+Enumerates the battery statuses that can trigger deferred task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -472,7 +481,8 @@ Enumerates the battery states that can trigger task scheduling.
| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.|
## StorageRequest
-Enumerates the storage states that can trigger task scheduling.
+
+Enumerates the storage statuses that can trigger deferred task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
@@ -480,4 +490,4 @@ Enumerates the storage states that can trigger task scheduling.
| ------------------------- | ---- | ------------------------------ |
| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. |
| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. |
-| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.|
+| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is insufficient, or the storage space is restored from insufficient to normal.|
diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md
index 2d97910441aa8dc3d5fe958c5424a0b449ce0620..0643de31173d0737a10431bc0bb8eb7d06428f01 100644
--- a/en/application-dev/reference/apis/js-apis-router.md
+++ b/en/application-dev/reference/apis/js-apis-router.md
@@ -51,21 +51,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
-router.pushUrl({
- url: 'pages/routerpage2',
- params: {
- data1: 'message',
- data2: {
- data3: [123, 456, 789]
+try {
+ router.pushUrl({
+ url: 'pages/routerpage2',
+ params: {
+ data1: 'message',
+ data2: {
+ data3: [123, 456, 789]
+ }
}
- }
-})
- .then(() => {
- // success
- })
- .catch(err => {
- console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
})
+} catch (err) {
+ console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
+}
```
## router.pushUrl9+
@@ -146,21 +144,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
-router.pushUrl({
- url: 'pages/routerpage2',
- params: {
- data1: 'message',
- data2: {
- data3: [123, 456, 789]
+try {
+ router.pushUrl({
+ url: 'pages/routerpage2',
+ params: {
+ data1: 'message',
+ data2: {
+ data3: [123, 456, 789]
+ }
}
- }
-}, router.RouterMode.Standard)
- .then(() => {
- // success
- })
- .catch(err => {
- console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
- })
+ }, router.RouterMode.Standard)
+} catch (err) {
+ console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
+}
```
## router.pushUrl9+
@@ -241,18 +237,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
-router.replaceUrl({
- url: 'pages/detail',
- params: {
- data1: 'message'
- }
-})
- .then(() => {
- // success
- })
- .catch(err => {
- console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
+try {
+ router.replaceUrl({
+ url: 'pages/detail',
+ params: {
+ data1: 'message'
+ }
})
+} catch (err) {
+ console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
+}
```
## router.replaceUrl9+
@@ -330,18 +324,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
-router.replaceUrl({
- url: 'pages/detail',
- params: {
- data1: 'message'
- }
-}, router.RouterMode.Standard)
- .then(() => {
- // success
- })
- .catch(err => {
- console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
- })
+try {
+ router.replaceUrl({
+ url: 'pages/detail',
+ params: {
+ data1: 'message'
+ }
+ }, router.RouterMode.Standard)
+} catch (err) {
+ console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
+}
```
## router.replaceUrl9+
@@ -420,23 +412,23 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
-router.pushNamedRoute({
- name: 'myPage',
- params: {
- data1: 'message',
- data2: {
- data3: [123, 456, 789]
+try {
+ router.pushNamedRoute({
+ name: 'myPage',
+ params: {
+ data1: 'message',
+ data2: {
+ data3: [123, 456, 789]
+ }
}
- }
-})
- .then(() => {
- // success
- })
- .catch(err => {
- console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
})
+} catch (err) {
+ console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
+}
```
+For details, see [UI Development-Named Route](../../ui/arkts-routing.md#named-route).
+
## router.pushNamedRoute10+
pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback<void>): void
@@ -515,21 +507,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
-router.pushNamedRoute({
- name: 'myPage',
- params: {
- data1: 'message',
- data2: {
- data3: [123, 456, 789]
+try {
+ router.pushNamedRoute({
+ name: 'myPage',
+ params: {
+ data1: 'message',
+ data2: {
+ data3: [123, 456, 789]
+ }
}
- }
-}, router.RouterMode.Standard)
- .then(() => {
- // success
- })
- .catch(err => {
- console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
- })
+ }, router.RouterMode.Standard)
+} catch (err) {
+ console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
+}
```
## router.pushNamedRoute10+
@@ -610,18 +600,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
-router.replaceNamedRoute({
- name: 'myPage',
- params: {
- data1: 'message'
- }
-})
- .then(() => {
- // success
- })
- .catch(err => {
- console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
+try {
+ router.replaceNamedRoute({
+ name: 'myPage',
+ params: {
+ data1: 'message'
+ }
})
+} catch (err) {
+ console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
+}
```
## router.replaceNamedRoute10+
@@ -693,24 +681,22 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
-| 100001 | if UI execution context not found, only throw in standard system. |
+| 100001 | if can not get the delegate, only throw in standard system. |
| 100004 | if the named route is not exist. |
**Example**
```ts
-router.replaceNamedRoute({
- name: 'myPage',
- params: {
- data1: 'message'
- }
-}, router.RouterMode.Standard)
- .then(() => {
- // success
- })
- .catch(err => {
- console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
- })
+try {
+ router.replaceNamedRoute({
+ name: 'myPage',
+ params: {
+ data1: 'message'
+ }
+ }, router.RouterMode.Standard)
+} catch (err) {
+ console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
+}
```
## router.replaceNamedRoute10+
@@ -932,7 +918,7 @@ Describes the page routing options.
| Name | Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| url | string | Yes | URL of the target page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URL is a slash (/), the home page is displayed.|
-| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.|
+| params | object | No | Data that needs to be passed to the target page during redirection. The received data becomes invalid when the page is switched to another page. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.
**NOTE**
The **params** parameter cannot pass objects returned by methods and system APIs, for example, **PixelMap** objects defined and returned by media APIs. To pass such objects, extract from them the basic type attributes to be passed, and then construct objects of the object type.|
> **NOTE**
diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md
index fb3aa7540b8383f983436c0d713e09346ad6aa3e..cbc5ed086fff519da5b5c959304afeeac6f442d5 100644
--- a/en/application-dev/reference/apis/js-apis-sim.md
+++ b/en/application-dev/reference/apis/js-apis-sim.md
@@ -2732,7 +2732,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses an async
**System API**: This is a system API.
-**Required permission**: ohos.permission.GET_TELEPHONY_STATE
+**Required permission**: ohos.permission.GET_PHONE_NUMBERS
**System capability**: SystemCapability.Telephony.CoreService
@@ -2775,7 +2775,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses a promis
**System API**: This is a system API.
-**Required permission**: ohos.permission.GET_TELEPHONY_STATE
+**Required permission**: ohos.permission.GET_PHONE_NUMBERS
**System capability**: SystemCapability.Telephony.CoreService
diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md
index 76c7829cf8fdadad378305ba795212ac10f621ea..f193ed010e3b0eb1ba6a87fad70f81b19bf9b732 100644
--- a/en/application-dev/reference/apis/js-apis-socket.md
+++ b/en/application-dev/reference/apis/js-apis-socket.md
@@ -1691,7 +1691,7 @@ listen(address: NetAddress, callback: AsyncCallback\): void
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses an asynchronous callback to return the result.
-> **NOTE**
+> **NOTE**
> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number.
**Required permissions**: ohos.permission.INTERNET
@@ -1736,7 +1736,7 @@ listen(address: NetAddress): Promise\
Binds the IP address and port number. The port number can be specified or randomly allocated by the system. The server listens to and accepts TCP socket connections established over the socket. Multiple threads are used to process client data concurrently. This API uses a promise to return the result.
-> **NOTE**
+> **NOTE**
> The server uses this API to perform the **bind**, **listen**, and **accept** operations. If the **bind** operation fails, the system randomly allocates a port number.
**Required permissions**: ohos.permission.INTERNET
diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md
index adea4c22a9473f43b8092d0314918537ecaa98b6..d0b51d00e6ddb980ac95cdeeb8a20de3db84c1a7 100644
--- a/en/application-dev/reference/apis/js-apis-webview.md
+++ b/en/application-dev/reference/apis/js-apis-webview.md
@@ -254,20 +254,20 @@ struct WebComponent {
.onClick(() => {
// Use the local port to send messages to HTML5.
try {
- console.log("In eTS side send true start");
+ console.log("In ArkTS side send true start");
if (this.nativePort) {
this.message.setString("helloFromEts");
this.nativePort.postMessageEventExt(this.message);
}
}
catch (error) {
- console.log("In eTS side send message catch error:" + error.code + ", msg:" + error.message);
+ console.log("In ArkTS side send message catch error:" + error.code + ", msg:" + error.message);
}
})
Web({ src: $rawfile('index.html'), controller: this.controller })
.onPageEnd((e)=>{
- console.log("In eTS side message onPageEnd init mesaage channel");
+ console.log("In ArkTS side message onPageEnd init mesaage channel");
// 1. Create a message port.
this.ports = this.controller.createWebMessagePorts(true);
// 2. Send port 1 to HTML5.
@@ -276,10 +276,10 @@ struct WebComponent {
this.nativePort = this.ports[0];
// 4. Set the callback.
this.nativePort.onMessageEventExt((result) => {
- console.log("In eTS side got message");
+ console.log("In ArkTS side got message");
try {
var type = result.getType();
- console.log("In eTS side getType:" + type);
+ console.log("In ArkTS side getType:" + type);
switch (type) {
case web_webview.WebMessageType.STRING: {
this.msg1 = "result type:" + typeof (result.getString());
@@ -652,71 +652,71 @@ struct WebComponent {
There are three methods for loading local resource files:
1. Using $rawfile
- ```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 {
- // Load a local resource file through $rawfile.
- this.controller.loadUrl($rawfile('index.html'));
- } catch (error) {
- console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
- }
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
+```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 {
+ // Load a local resource file through $rawfile.
+ this.controller.loadUrl($rawfile('index.html'));
+ } catch (error) {
+ console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
+ }
+ })
+ Web({ src: 'www.example.com', controller: this.controller })
+ }
+ }
+}
+```
2. Using the resources protocol
- ```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 {
- // Load a local resource file through the resource protocol.
- this.controller.loadUrl("resource://rawfile/index.html");
- } catch (error) {
- console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
- }
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
+```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 {
+ // Load local resource files through the resource protocol.
+ this.controller.loadUrl("resource://rawfile/index.html");
+ } catch (error) {
+ console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
+ }
+ })
+ Web({ src: 'www.example.com', controller: this.controller })
+ }
+ }
+}
+```
3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web).
- HTML file to be loaded:
- ```html
-
-
-
-
- Hello World
-
-
- ```
+HTML file to be loaded:
+```html
+
+
+
+
+ Hello World
+
+
+```
### loadData
@@ -4320,6 +4320,107 @@ export default class EntryAbility extends UIAbility {
}
```
+### setCustomUserAgent10+
+
+setCustomUserAgent(userAgent: string): void
+
+Set a custom user agent.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+**Parameters**
+
+| Name | Type | Mandatory | Description |
+| ---------------| ------- | ---- | ------------- |
+| userAgent | string | Yes | Information about the custom user agent.|
+
+**Error codes**
+
+For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
+
+| ID | Error Message |
+| -------- | ------------------------------------------------------------ |
+| 17100001 | Init error. The WebviewController must be associated with a Web component. |
+
+**Example**
+
+```ts
+// xxx.ets
+import web_webview from '@ohos.web.webview'
+
+@Entry
+@Component
+struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController();
+ @State userAgent: string = 'test'
+
+ build() {
+ Column() {
+ Button('setCustomUserAgent')
+ .onClick(() => {
+ try {
+ this.controller.setCustomUserAgent(this.userAgent);
+ } catch (error) {
+ console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
+ }
+ })
+ Web({ src: 'www.example.com', controller: this.controller })
+ }
+ }
+}
+```
+
+### getCustomUserAgent10+
+
+getCustomUserAgent(): string
+
+Obtains a custom user agent.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+**Return value**
+
+| Type | Description |
+| ------ | ------------------------- |
+| string | Information about the custom user agent.|
+
+**Error codes**
+
+For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
+
+| ID | Error Message |
+| -------- | ------------------------------------------------------------ |
+| 17100001 | Init error. The WebviewController must be associated with a Web component. |
+
+**Example**
+
+```ts
+// xxx.ets
+import web_webview from '@ohos.web.webview'
+
+@Entry
+@Component
+struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController();
+ @State userAgent: string = ''
+
+ build() {
+ Column() {
+ Button('getCustomUserAgent')
+ .onClick(() => {
+ try {
+ this.userAgent = this.controller.getCustomUserAgent();
+ console.log("userAgent: " + this.userAgent);
+ } catch (error) {
+ console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
+ }
+ })
+ Web({ src: 'www.example.com', controller: this.controller })
+ }
+ }
+}
+```
+
## WebCookieManager
Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance.
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md
index cad8cd31309b0e6098e0ab5b521d5c6f10ce0843..110905369abcd03d58cccdab4380d31aadf03f33 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-navigation.md
@@ -13,44 +13,54 @@ Supported
Since API version 9, it is recommended that this component be used together with the **[\](ts-basic-components-navrouter.md)** component.
-
## APIs
-**API 1**: Navigation()
+### Navigation
+
+Navigation()
+
+### Navigation10+
-**API 2**: Navigation(pathInfos: NavPathStack)10+
+Navigation(pathInfos: NavPathStack)10+
Binds a navigation stack to the **\** component.
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------- | ----------------------------------- | ---- | ------------- |
-| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.|
+| Name | Type | Mandatory | Description |
+| --------- | ------------------------------- | ---- | ------ |
+| pathInfos | [NavPathStack](#navpathstack10) | No | Information about the navigation stack.|
## Attributes
In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported.
-| Name | Type | Description |
-| ----------------------------- | ---------------------------------------- | ---------------------------------------- |
-| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).|
-| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.|
-| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array\<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.|
-| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**|
-| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.|
+| Name | Type | Description |
+| ---------------------------------- | ---------------------------------------- | ---------------------------------------- |
+| title | [ResourceStr](ts-types.md#resourcestr)10+ \| [CustomBuilder](ts-types.md#custombuilder8)8+ \| [NavigationCommonTitle](#navigationcommontitle)9+ \| [NavigationCustomTitle](#navigationcustomtitle)9+ | Page title.
**NOTE**
When the NavigationCustomTitle type is used to set the height, the **titleMode** attribute does not take effect.
When the title string is too long: (1) If no subtitle is set, the string is scaled down, wrapped in two lines, and then clipped with an ellipsis (...); (2) If a subtitle is set, the subtitle is scaled down and then clipped with an ellipsis (...).|
+| subTitle(deprecated) | string | Subtitle of the page. If this attribute is not set, no subtitle is displayed. This attribute is deprecated since API version 9. You are advised to use **title** instead.|
+| menus | Array<[NavigationMenuItem](#navigationmenuitem)> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Menu items in the upper right corner of the page. If this attribute is not set, no menu item is displayed. When the value type is Array<[NavigationMenuItem](#navigationmenuitem)>, the menu shows a maximum of three icons in portrait mode and a maximum of five icons in landscape mode, with excess icons (if any) placed under the automatically generated **More** icon.|
+| titleMode | [NavigationTitleMode](#navigationtitlemode) | Display mode of the page title bar.
Default value: **NavigationTitleMode.Free**|
+| toolBar(deprecated) | [object](#object) \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**items**: all items on the toolbar.
**NOTE**
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area. If the text is too long, it is scaled down level by level, wrapped in two lines, and then clipped with an ellipsis (...).
This API is deprecated since API version 10. You are advised to use **toolbarConfiguration** instead.|
| toolbarConfiguration10+ | Array<[ToolbarItem](#toolbaritem10)10+> \| [CustomBuilder](ts-types.md#custombuilder8)8+ | Content of the toolbar. If this attribute is not set, no toolbar is displayed.
**NOTE**
When the value type is Array<[ToolbarItem](#ToolbarItem>, the toolbar exhibits the following features:
Items are evenly distributed on the toolbar at the bottom. Text and icons are evenly distributed in each content area.
If any item contains overlong text and there are fewer than five items, the following measures are taken: 1. Increase the item's width to accommodate the text until it is as large as the screen width; 2. Scale down the text level by level; 3. Wrap the text in two lines; 4. Clip the text with an ellipsis (...).
The toolbar shows a maximum of five icons in portrait mode, with excess icons (if any) placed under the automatically generated **More** icon. In landscape mode, this attribute must be used together with Array<[NavigationMenuItem](#navigationmenuitem)> of the **menus** attribute; the toolbar at the bottom is automatically hidden, and all items on the toolbar are moved to the menu in the upper right corner of the screen.
When the value type is [CustomBuilder](ts-types.md#custombuilder8), and the toolbar does not exhibit the preceding features except that items are evenly distributed on the toolbar at the bottom.|
-| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.|
-| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.|
-| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.|
-| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.|
-| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.|
-| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.|
-| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.|
-| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.|
-| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.|
-| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.|
-| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)|
+| hideToolBar | boolean | Whether to hide the toolbar.
Default value: **false**
**true**: Hide the toolbar.
**false**: Display the toolbar.|
+| hideTitleBar | boolean | Whether to hide the title bar.
Default value: **false**
**true**: Hide the title bar.
**false**: Display the title bar.|
+| hideBackButton | boolean | Whether to hide the back button.
Default value: **false**
**true**: Hide the back button.
**false**: Display the back button.
The back button in the title bar of the **\** component cannot be hidden.
**NOTE**
The back button works only when **titleMode** is set to **NavigationTitleMode.Mini**.|
+| navBarWidth9+ | [Length](ts-types.md#length) | Width of the navigation bar.
Default value: **240**
Unit: vp
**NOTE**
This attribute is valid only when the **\** component is split.|
+| navBarPosition9+ | [NavBarPosition](#navbarposition) | Position of the navigation bar.
Default value: **NavBarPosition.Start**
**NOTE**
This attribute is valid only when the **\** component is split.|
+| mode9+ | [NavigationMode](#navigationmode) | Display mode of the navigation bar.
Default value: **NavigationMode.Auto**
At the default settings, the component adapts to a single column or two columns based on the component width.
**NOTE**
Available options are **Stack**, **Split**, and **Auto**.|
+| backButtonIcon9+ | string \| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Back button icon on the navigation bar. The back button in the title bar of the **\** component cannot be hidden.|
+| hideNavBar9+ | boolean | Whether to hide the navigation bar. This attribute is valid only when **mode** is set to **NavigationMode.Split**.|
+| navDestination10+ | builder: (name: string, param: unknown) => void | Creates a **\** component.
**NOTE**
The **builder** function is used, with the **name** and **param** parameters passed in. In the builder, a layer of custom components can be included outside the **\** component. However, no attributes or events can be set for the custom components. Otherwise, only blank components are displayed.|
+| navBarWidthRange10+ | [[Dimension](ts-types.md#dimension10), [Dimension](ts-types.md#dimension10)] | Minimum and maximum widths of the navigation bar (valid in dual-column mode).
Default value: **240** for the minimum value; 40% of the component width (not greater than 432) for the maximum value
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.|
+| minContentWidth10+ | [Dimension](ts-types.md#dimension10) | Minimum width of the navigation bar content area (valid in dual-column mode).
Default value: **360**
Unit: vp
Priority rules:
Custom value > Default value
Minimum value > Maximum value
navBar > content
If values conflict, the global value takes precedence, and the local minimum value depends on the container size.
Breakpoint calculation in Auto mode: default 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp)|
+
+## Events
+
+| Name | Description |
+| ---------------------------------------- | ---------------------------------------- |
+| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.|
+| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.|
## NavPathStack10+
@@ -64,9 +74,9 @@ Pushes the NavDestination page information specified by **info** to the stack.
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ---- | ----------------------------- | ---- | -------------------- |
+| info | [NavPathInfo](#navpathinfo10) | Yes | Information about the navigation destination page.|
### pushPathByName10+
@@ -76,10 +86,10 @@ Pushes the navigation destination page specified by **name** to the navigation s
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| name | string | Yes | Name of the navigation destination page. |
-| param | unknown | Yes | Parameter information of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ----- | ------- | ---- | --------------------- |
+| name | string | Yes | Name of the navigation destination page. |
+| param | unknown | Yes | Parameter information of the navigation destination page.|
### pop10+
@@ -89,10 +99,10 @@ Pops the top element out of the navigation stack.
**Return value**
-| Type | Description |
-| ------ | -------- |
+| Type | Description |
+| ----------- | ------------------------ |
| NavPathInfo | Returns the information about the navigation destination page at the top of the stack.|
-| undefined | Returns **undefined** if the navigation stack is empty.|
+| undefined | Returns **undefined** if the navigation stack is empty. |
### popToName10+
@@ -102,14 +112,14 @@ Returns the navigation stack to the first navigation destination page that match
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| name | string | Yes | Name of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ------------------- |
+| name | string | Yes | Name of the navigation destination page.|
**Return value**
-| Type | Description |
-| ------ | -------- |
+| Type | Description |
+| ------ | ---------------------------------------- |
| number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.|
### popToIndex10+
@@ -120,9 +130,9 @@ Returns the navigation stack to the navigation destination page that matches the
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| index | number | Yes | Index of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ---------------------- |
+| index | number | Yes | Index of the navigation destination page.|
### moveToTop10+
@@ -132,14 +142,14 @@ Moves to the top of the navigation stack the first navigation destination page t
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| name | string | Yes | Name of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ------------------- |
+| name | string | Yes | Name of the navigation destination page.|
**Return value**
-| Type | Description |
-| ------ | -------- |
+| Type | Description |
+| ------ | ---------------------------------------- |
| number | Returns the index of the first navigation destination page that matches the value of **name** if it exists in the navigation stack; returns **-1** otherwise.|
### moveIndexToTop10+
@@ -150,9 +160,9 @@ Moves to the top of the navigation stack the navigation destination page that ma
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| index | number | Yes | Index of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ---------------------- |
+| index | number | Yes | Index of the navigation destination page.|
### clear10+
@@ -168,8 +178,8 @@ Obtains the names of all navigation destination pages in the navigation stack.
**Return value**
-| Type | Description |
-| ------ | -------- |
+| Type | Description |
+| -------------- | -------------------------- |
| Array | Names of all navigation destination pages in the navigation stack.|
### getParamByIndex10+
@@ -180,16 +190,16 @@ Obtains the parameter information of the navigation destination page that matche
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| index | number | Yes | Index of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ----- | ------ | ---- | ---------------------- |
+| index | number | Yes | Index of the navigation destination page.|
**Return value**
-| Type | Description |
-| ------ | -------- |
-| unknown | Returns the parameter information of the matching navigation destination page.|
-| undefined | Returns **undefined** if the passed index is invalid.|
+| Type | Description |
+| --------- | -------------------------- |
+| unknown | Returns the parameter information of the matching navigation destination page.|
+| undefined | Returns **undefined** if the passed index is invalid. |
### getParamByName10+
@@ -199,15 +209,15 @@ Obtains the parameter information of all the navigation destination pages that m
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| name | string | Yes | Name of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ------------------- |
+| name | string | Yes | Name of the navigation destination page.|
**Return value**
-| Type | Description |
-| ------ | -------- |
-| Array | Parameter information of all the matching navigation destination pages.|
+| Type | Description |
+| --------------- | --------------------------------- |
+| Array | Parameter information of all the matching navigation destination pages.|
### getIndexByName10+
@@ -217,15 +227,15 @@ Obtains the indexes information of all the navigation destination pages that mat
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| name | string | Yes | Name of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ---- | ------ | ---- | ------------------- |
+| name | string | Yes | Name of the navigation destination page.|
**Return value**
-| Type | Description |
-| ------ | -------- |
-| Array | Indexes of all the matching navigation destination pages.|
+| Type | Description |
+| -------------- | --------------------------------- |
+| Array | Indexes of all the matching navigation destination pages.|
### size10+
@@ -235,9 +245,9 @@ Obtains the stack size.
**Return value**
-| Type | Description |
-| ------ | -------- |
-| number | Stack size.|
+| Type | Description |
+| ------ | ------ |
+| number | Stack size.|
## NavPathInfo10+
@@ -249,52 +259,52 @@ constructor(name: string, param: unknown)
**Parameters**
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| name | string | Yes | Name of the navigation destination page. |
-| param | unknown | No | Parameter information of the navigation destination page. |
+| Name | Type | Mandatory | Description |
+| ----- | ------- | ---- | --------------------- |
+| name | string | Yes | Name of the navigation destination page. |
+| param | unknown | No | Parameter information of the navigation destination page.|
## NavigationMenuItem
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| value | string | Yes | Text of a menu item. |
-| icon | string | No | Icon path of a menu item.|
+| Name | Type | Mandatory | Description |
+| ------ | ------------- | ---- | --------------- |
+| value | string | Yes | Text of a menu item. |
+| icon | string | No | Icon path of a menu item.|
| action | () => void | No | Callback invoked when a menu item is selected. |
## object
-| Name | Type | Mandatory | Description |
-| ------ | ----------------------- | ---- | --------------- |
-| value | string | Yes | Text of a toolbar item. |
-| icon | string | No | Icon path of a toolbar item.|
+| Name | Type | Mandatory | Description |
+| ------ | ------------- | ---- | --------------- |
+| value | string | Yes | Text of a toolbar item. |
+| icon | string | No | Icon path of a toolbar item.|
| action | () => void | No | Callback invoked when a toolbar item is selected. |
## ToolbarItem10+
-| Name | Type | Mandatory| Description |
-| ---------- | ------------------------------------------------- | ---- | ----------------------------------------------------------- |
-| value | ResourceStr | Yes | Text of a toolbar item. |
-| icon | ResourceStr | No | Icon path of a toolbar item. |
-| action | () => void | No | Callback invoked when a toolbar item is selected. |
-| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**|
-| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. |
+| Name | Type | Mandatory | Description |
+| ---------- | ---------------------------------------- | ---- | ---------------------------------------- |
+| value | ResourceStr | Yes | Text of a toolbar item. |
+| icon | ResourceStr | No | Icon path of a toolbar item. |
+| action | () => void | No | Callback invoked when a toolbar item is selected. |
+| status | [ToolbarItemStatus](#toolbaritemstatus10) | No | Status of a toolbar item.
Default value: **ToolbarItemStatus.NORMAL**|
+| activeIcon | ResourceStr | No | Icon path of the toolbar item in the active state. |
## ToolbarItemStatus10+
-| Name | Description |
-| -------- | ------------------------------------------------------------ |
+| Name | Description |
+| -------- | ---------------------------------------- |
| NORMAL | Normal state. In this state, the toolbar item takes on the default style and can switch to another state-specific style by responding to the hover, press, and focus events.|
| DISABLED | Disabled state. In this state, the toolbar item is disabled and does not allow for user interactions.|
| ACTIVE | Active state. In this state, the toolbar item can update its icon to the one specified by **activeIcon** by responding to a click event.|
## NavigationTitleMode
-| Name| Description |
-| ---- | ------------------------------------------------------------ |
-| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores when the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.|
-| Mini | The title is fixed at mini mode. |
-| Full | The title is fixed at full mode. |
+| Name | Description |
+| ---- | ---------------------------------------- |
+| Free | When the content is a scrollable component, the main title shrinks as the content scrolls down (the subtitle fades out with its size remaining unchanged) and restores as the content scrolls up to the top.
**NOTE**
The size linkage effect works only when **title** is set to **ResourceStr** or **NavigationCommonTitle**. If **title** is set to any other value type, the main title changes in mere location when pulled down.|
+| Mini | The title is fixed at mini mode. |
+| Full | The title is fixed at full mode. |
## NavigationCommonTitle
@@ -322,7 +332,7 @@ constructor(name: string, param: unknown)
| Name | Description |
| ----- | ------------------------------------------------------------ |
| Stack | The navigation bar and content area are displayed independently of each other, which are equivalent to two pages. |
-| Split | The navigation bar and content area are displayed in different columns. |
+| Split | The navigation bar and content area are displayed in different columns.
The values of **navBarWidthRange** are represented by [minNavBarWidth,maxNavBarWidth].
1. When the value of **navBarWidth** is beyond the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **navBarWidth** < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) > Value of **maxNavBarWidth**: The value of **navBarWidth** is changed to that of **maxNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) < Value of **minNavBarWidth**: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **navBarWidth** > Value of **maxNavBarWidth** and Component width - Value of **minContentWidth** - Divider width (1 vp) is within the value range specified by **navBarWidthRange**: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
2. When the value of **navBarWidth** is within the value range specified by **navBarWidthRange**, **navBarWidth** is set according to the following rules:
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to that of **minNavBarWidth**.
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) > = Component width: The value of **navBarWidth** is changed to Component width - Value of **minContentWidth** - Divider width (1 vp).
Value of **minNavBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width and Value of **navBarWidth** + Value of **minContentWidth** + Divider width (1 vp) < Component width: The value of **navBarWidth** is the set value.
3. When the component size is decreased, the content area is shrunk until its width reaches the value defined by **minContentWidth**, and then the navigation bar is shrunk until its width reaches the value defined by **minNavBarWidth**; if the component size is further decreased, the content area is further shrunk until it disappears, and then navigation bar is shrunk.
4. When the navigation bar is set to a fixed size and the component size is continuously decreased, the navigation bar is shrunk.
5. If only **navBarWidth** is set, the width of the navigation bar is fixed at the value of **navBarWidth**, and the divider cannot be dragged.|
| Auto | In API version 9 and earlier versions: When the window width is greater than or equal to 520 vp, the Split mode is used. In other cases, the Stack mode is used.
In API version 10 and later versions: When the window width is greater than or equal to 600 vp, the Split mode is used. In other cases, the Stack mode is used. 600 vp = minNavBarWidth (240 vp) + minContentWidth (360 vp).|
## TitleHeight
@@ -334,17 +344,10 @@ constructor(name: string, param: unknown)
> **NOTE**
+>
> Among the scrollable components, only **\** is supported.
-## Events
-
-| Name | Description |
-| ---------------------------------------- | ---------------------------------------- |
-| onTitleModeChange(callback: (titleMode: NavigationTitleMode) => void) | Called when **titleMode** is set to **NavigationTitleMode.Free** and the title bar mode changes as content scrolls.|
-| onNavBarStateChange(callback: (isVisible: boolean) => void) | Called when the navigation bar visibility status changes. The value **true** means that the navigation bar is displayed, and **false** means the opposite.|
-
-
## Example
```ts
diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md
index 07b043411ed7ce7658cb575490e559e0dbd3aab0..daf26e98a24a303138f9f79c88c4340c73ba629a 100644
--- a/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md
+++ b/en/application-dev/reference/arkui-ts/ts-basic-components-stepperitem.md
@@ -26,6 +26,11 @@ StepperItem()
| nextLabel | string | Text label of the button on the right. The default value is **Start** for the last page and **Next** for the other pages.|
| status | [ItemState](#itemstate) | Display status of **nextLabel** in the stepper. Optional.
Default value: **ItemState.Normal**|
+> **NOTE**
+>
+> - The **\** component does not support setting of the universal width attribute. By default, its width is the same as that of the parent **\** component.
+> - The **\** component does not support setting of the universal height attribute. Its height is the height of the parent **\** component minus the height of the label button.
+> - The **\** component does not support setting of the **aspectRadio** or **constrainSize** attribute, which may affect the length and width.
## ItemState
| Name | Description|
diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md
index 4dd9922e85fcbb464dc189c032af8a2136e44f28..38195901492db82a74671c4dcdbaff902f44e707 100644
--- a/en/application-dev/reference/arkui-ts/ts-container-list.md
+++ b/en/application-dev/reference/arkui-ts/ts-container-list.md
@@ -41,7 +41,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Type | Mandatory | Description |
| ------------ | ---------------------------------------- | ---- | ---------------------------------------- |
-| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If the set value is a negative number, the default value will be used.
If the value of **space** is less than the width of the list divider, the latter is used as the spacing.|
+| space | number \| string | No | Spacing between list items along the main axis.
Default value: **0**
**NOTE**
If this parameter is set to a negative number or a value greater than or equal to the length of the list content area, the default value is used.
If this parameter is set to a value less than the width of the list divider, the width of the list divider is used as the spacing.|
| initialIndex | number | No | Item displayed at the beginning of the viewport when the current list is loaded for the first time, that is, the first item to be displayed.
Default value: **0**
**NOTE**
If the set value is a negative number or is greater than the index of the last item in the list, the value is invalid. In this case, the default value will be used.|
| scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.
**NOTE**
The scroller cannot be bound to other scrollable components.|
diff --git a/en/application-dev/reference/errorcodes/errorcode-hiappevent.md b/en/application-dev/reference/errorcodes/errorcode-hiappevent.md
index e0b7e16e0510883addf190635795e08c35a68502..11ac6f8288c316c21a1b410cabfaa42e5e62c7c7 100644
--- a/en/application-dev/reference/errorcodes/errorcode-hiappevent.md
+++ b/en/application-dev/reference/errorcodes/errorcode-hiappevent.md
@@ -1,4 +1,4 @@
-# Application Event Logging Error Codes
+# Application Event Logging Error Codes
> **NOTE**
>
@@ -63,8 +63,8 @@ This error code is reported if the **write** API is called to perform applicatio
The specified event name does not comply with the following rules:
-- The event name contains only digits, lowercase letters, and underscores (\_).
-- The event name starts with a lowercase letter and does not end with an underscore (\_).
+- An event name contains only digits, letters, and underscores (_).
+- An event name starts with a letter or dollar sign ($) and does not end with an underscore (_).
- The event name is not empty and contains a maximum of 48 characters.
**Solution**
@@ -119,11 +119,11 @@ This error code is reported if the **write** API is called to perform applicatio
**Possible Causes**
-The specified event parameter name does not comply with the following rules:
+The specified event name does not comply with the following rules:
-- The event parameter name contains only digits, lowercase letters, and underscores (\_).
-- The event parameter name starts with a lowercase letter and does not end with an underscore (\_).
-- The event parameter name is not empty and contains a maximum of 16 characters.
+- An event name contains only digits, letters, and underscores (_).
+- An event name starts with a letter or dollar sign ($) and does not end with an underscore (_).
+- An event parameter name is not empty and contains a maximum of 16 characters.
**Solution**
@@ -163,7 +163,7 @@ The specified watcher name does not comply with the following rules:
- The watcher name can contain only digits, lowercase letters, and underscores (\_).
- The watcher name starts with a lowercase letter and does not end with an underscore (\_).
-- The watcher name is not empty and contains a maximum of 32 characters.
+- A watcher name is not empty and contains a maximum of 32 characters.
**Solution**
diff --git a/en/application-dev/task-management/figures/bgtask_choice.png b/en/application-dev/task-management/figures/bgtask_choice.png
index a5200006128dcead88e00da8434b4621e6c36472..8ac048571e10bf6ba902bf844ba2a7e02d5a9ddb 100644
Binary files a/en/application-dev/task-management/figures/bgtask_choice.png and b/en/application-dev/task-management/figures/bgtask_choice.png differ
diff --git a/en/application-dev/task-management/work-scheduler.md b/en/application-dev/task-management/work-scheduler.md
index ca419ee8142d7cf281b2e0ce30e6e64a37b01694..22c012478ff92d8ab81e0490b8cad570ad17362e 100644
--- a/en/application-dev/task-management/work-scheduler.md
+++ b/en/application-dev/task-management/work-scheduler.md
@@ -62,8 +62,8 @@ The table below lists the APIs used for developing deferred tasks. For details a
| -------- | -------- |
| startWork(work: WorkInfo): void; | Starts a deferred task.|
| stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.|
-| getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void; | Obtains the status of a deferred task. This API uses an asynchronous callback to return the result.|
-| getWorkStatus(workId: number): Promise<WorkInfo>; | Obtains the status of a deferred task. This API uses a promise to return the result.|
+| getWorkStatus(workId: number, callback: AsyncCallback<WorkInfo>): void; | Obtains the information about a deferred task. This API uses an asynchronous callback to return the result.|
+| getWorkStatus(workId: number): Promise<WorkInfo>; | Obtains the information about a deferred task. This API uses a promise to return the result.|
| obtainAllWorks(callback: AsyncCallback<void>): Array<WorkInfo>; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.|
| obtainAllWorks(): Promise<Array<WorkInfo>>; | Obtains all the deferred tasks. This API uses a promise to return the result.|
| stopAndClearWorks(): void; | Stops and clears all the deferred tasks.|
@@ -77,7 +77,7 @@ The table below lists the APIs used for developing deferred tasks. For details a
| bundleName | string | Bundle name of the application that requests the deferred task.|
| abilityName | string | Name of the ability to be notified by a deferred task scheduling callback. This parameter is mandatory.|
| networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.|
-| isCharging | boolean | Whether the device is charging.|
+| isCharging | boolean | Whether the device needs to enter the charging state to trigger deferred task scheduling.|
| chargerType | [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.|
| batteryLevel | number | Battery level.|
| batteryStatus | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.|
diff --git a/en/application-dev/ui/arkts-layout-development-create-list.md b/en/application-dev/ui/arkts-layout-development-create-list.md
index 32c4322ae5247bbf8ac79b29667593d660795806..cbb633c5d19bda73a973fff66574dd537dd51f2c 100644
--- a/en/application-dev/ui/arkts-layout-development-create-list.md
+++ b/en/application-dev/ui/arkts-layout-development-create-list.md
@@ -299,7 +299,7 @@ List() {
})
```
-This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 8.
+This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 9.
>**NOTE**
>
@@ -653,8 +653,6 @@ The following describes the implementation of the pull-and-refresh feature:
3. Listen for the finger lift event. If the movement reaches the maximum value, trigger data loading and display the refresh view. After the loading is complete, hide the view.
- You can also use the third-party component [PullToRefresh](https://gitee.com/openharmony-sig/PullToRefresh) to implement this feature.
-
## Editing a List
diff --git a/en/application-dev/ui/arkts-routing.md b/en/application-dev/ui/arkts-routing.md
index 5ccf781293c12b40eedfb6949b0ef268c79d4699..ef6b72ab27dbd5847ceb16f9b732aadbff1ec402 100644
--- a/en/application-dev/ui/arkts-routing.md
+++ b/en/application-dev/ui/arkts-routing.md
@@ -11,23 +11,26 @@ Page redirection is an important part of the development process. When using an
**Figure 1** Page redirection

-The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). The two modes determine whether the target page will replace the current page.
+The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). Whether the target page will replace the current page depends on the mode used.
-- **router.pushUrl()**: The target page does not replace the current page. Instead, it is pushed into the [page stack](../application-models/page-mission-stack.md). In this way, the state of the current page can be retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API.
+- **router.pushUrl()**: The target page is pushed into the [page stack](../application-models/page-mission-stack.md) and does not replace the current page. In this mode, the state of the current page is retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API.
-- **router.replaceUrl()**: The target page replaces the current page and destroys the current page. In this way, the resources of the current page can be released, and users cannot return to the current page.
+- **router.replaceUrl()**: The target page replaces and destroys the current page. In this mode, the resources of the current page can be released, and users cannot return to the current page.
>**NOTE**
>
->The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory.
+>- When creating a page, configure the route to this page by following instructions in [Building the Second Page](../quick-start/start-with-ets-stage.md).
+>
+>
+>- The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory.
-The **Router** module also provides two instance modes: **Standard** and **Single**. The two modes determine whether the target URL corresponds to multiple instances.
+The **Router** module also provides two instance modes: **Standard** and **Single**. Depending on the mode, the target URL is mapped to one or more instances.
-- **Standard**: standard instance mode, which is the default instance mode. Each time this API is called, a target page is created and pushed to the top of the stack.
+- **Standard**: multi-instance mode. It is the default instance mode. In this mode, the target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.
-- **Single**: singleton mode. If the URL of the target page already exists in the page stack, the page with the same URL closest to the top of the stack is moved to the top of the stack and reloaded. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode.
+- **Single**: singleton mode. In this mode, if the URL of the target page already exists in the page stack, the page closest to the top of the stack with the same URL is moved to the top of the stack and becomes the new page. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode.
-Before using the **Router** module, you need to import it to the code.
+Before using the **Router** module, import it first.
```ts
@@ -54,7 +57,7 @@ import router from '@ohos.router';
>**NOTE**
>
- >In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted.
+ >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted.
- Scenario 2: There is a login page (**Login**) and a personal center page (**Profile**). After a user successfully logs in from the **Login** page, the **Profile** page is displayed. At the same time, the **Login** page is destroyed, and the application exits when the back button is pressed. In this scenario, you can use the **replaceUrl()** API and use the Standard instance mode (which can also be omitted).
@@ -76,7 +79,7 @@ import router from '@ohos.router';
>**NOTE**
>
- >In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted.
+ >In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted.
- Scenario 3: There is a setting page (**Setting**) and a theme switching page (**Theme**). You want to click a theme option on the **Setting** page to go to the **Theme** page. In addition, you want to ensure that only one **Theme** page exists in the page stack at a time. When the back button is clicked on the **Theme** page, the **Setting** page is displayed. In this scenario, you can use the **pushUrl()** API and use the **Single** instance mode.
@@ -115,7 +118,7 @@ import router from '@ohos.router';
The preceding scenarios do not involve parameter transfer.
-If you need to transfer some data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example:
+If you need to transfer data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example:
```ts
@@ -150,11 +153,11 @@ function onJumpClick(): void {
}
```
-On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the transferred parameters. Example:
+On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the passed parameters. Example:
```ts
-const params = router.getParams(); // Obtain the transferred parameter object.
+const params = router.getParams(); // Obtain the passed parameters.
const id = params['id']; // Obtain the value of the id attribute.
const age = params['info'].age; // Obtain the value of the age attribute.
```
@@ -162,13 +165,13 @@ const age = params['info'].age; // Obtain the value of the age attribute.
## Page Return
-After a user completes an operation on a page, the user usually needs to return to the previous page or a specified page. In this case, the page return function is required. During the return process, the data may need to be transferred to the target page, which requires the data transfer function.
+Implement the page return feature so that users can return to the previous page or a specified page. You can pass parameters to the target page during the return process.
**Figure 2** Page return

-Before using the **Router** module, you need to import it to the code.
+Before using the **Router** module, import it first.
```ts
@@ -195,7 +198,7 @@ You can use any of the following methods to return to a page:
});
```
- This method allows you to return to a specified page. You need to specify the path of the target page. For this method to work, the target page must it exist in the page stack.
+ This method allows uesrs to return to a page with the specified path. For this method to work, the target page must exist in the page stack.
- Method 3: Return to the specified page and transfer custom parameter information.
@@ -209,14 +212,14 @@ You can use any of the following methods to return to a page:
});
```
- This method not only allows you to return to the specified page, but also transfer custom parameter information when returning. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page.
+ This method not only allows you to return to the specified page, but also pass in custom parameter information during the return process. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page.
On the target page, call the **router.getParams()** API at the position where parameters need to be obtained, for example, in the **onPageShow()** lifecycle callback:
```ts
onPageShow() {
- const params = router.getParams(); // Obtain the transferred parameter object.
+ const params = router.getParams(); // Obtain the passed parameters.
const info = params['info']; // Obtain the value of the info attribute.
}
```
@@ -243,7 +246,7 @@ Such a dialog box can be in the [default style](#default-confirmation-dialog-box
To implement this function, you can use the [router.showAlertBeforeBackPage()](../reference/apis/js-apis-router.md#routershowalertbeforebackpage9) and [router.back()](../reference/apis/js-apis-router.md#routerback) APIs provided by the **Router** module.
-Before using the **Router** module, you need to import it to the code.
+Before using the **Router** module, import it first.
```ts
@@ -272,17 +275,16 @@ function onBackClick(): void {
The **router.showAlertBeforeBackPage()** API receives an object as a parameter. The object contains the following attributes:
-- **message**: content of the dialog box. The value is of the string type.
- If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**.
-
- When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
+**message**: content of the dialog box. The value is of the string type.
+If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**.
+When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
### Custom Confirmation Dialog Box
To implement a custom confirmation dialog box, use APIs in the [PromptAction](../reference/apis/js-apis-promptAction.md#promptactionshowdialog) module or customize a popup window. This topic uses the APIs in the **PromptAction** module an example to describe how to implement a custom confirmation dialog box.
-Before using the **Router** module, you need to import it to the code.
+Before using the **Router** module, import it first.
```ts
@@ -324,3 +326,63 @@ function onBackClick() {
```
When the user clicks the back button, the custom confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
+
+## Named Route
+
+To redirect to a [page in a shared package](../quick-start/shared-guide.md), you can use [router.pushNamedRoute()](../reference/apis/js-apis-router.md#routerpushnamedroute10).
+
+Before using the **Router** module, import it first.
+
+
+```ts
+import router from '@ohos.router';
+```
+
+In the target page in the [shared package](../quick-start/shared-guide.md), name the [@Entry decorated custom component](../quick-start/arkts-create-custom-components.md#entryoptions10).
+
+```ts
+// library/src/main/ets/pages/Index.ets
+@Entry({ routeName : 'myPage' })
+@Component
+struct MyComponent {
+}
+```
+
+When the configuration is successful, import the named route page to the page from which you want to redirect.
+
+```ts
+// entry/src/main/ets/pages/Index.ets
+import router from '@ohos.router';
+import 'library/src/main/ets/Index.ets' // Import the named route page from the shared package library.
+
+@Entry
+@Component
+struct Index {
+ build() {
+ Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
+ Text('Hello World')
+ .fontSize(50)
+ .fontWeight(FontWeight.Bold)
+ .margin({ top: 20 })
+ .backgroundColor('#ccc')
+ .onClick(() => { // Click to go to a page in another shared package.
+ try {
+ router.pushNamedRoute({
+ name: 'myPage',
+ params: {
+ data1: 'message',
+ data2: {
+ data3: [123, 456, 789]
+ }
+ }
+ })
+ } catch (err) {
+ console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
+ }
+ })
+ }
+ .width('100%')
+ .height('100%')
+ }
+}
+```
diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md
index 613c624e1a155a1a97e6e042eb9b4a906947ee76..95bdd78be0231342ffac333ca4f15c43654cd5e2 100644
--- a/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md
+++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-listening.md
@@ -4,156 +4,319 @@
## Overview
-### Introduction
+### Function Introduction
-HiSysEvent supports listening for events across processes. You can register a listener to listen for concerned events on a real-time basis. For example, you can enable the battery module to listen for power consumption events for power usage analysis.
+HiSysEvent supports listening for events across processes. You can register a listener to listen for concerned events on a real-time basis. For example, you can enable the battery module to subscribe to power consumption events for power usage analysis.
### Constraints
-Before subscribing to system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](../subsystems/subsys-dfx-hisysevent-logging-config.md).
+Before listening for system events, you need to configure HiSysEvent logging. For details, see [HiSysEvent Logging Configuration](../subsystems/subsys-dfx-hisysevent-logging-config.md).
-## Development Guidelines
-
+## How to Develop
### Available APIs
- **Table 1** Description of HiSysEventListener APIs
+#### C++ APIs
-| API| Description|
-| -------- | -------- |
-| int32_t HiSysEventManager::AddListener(std::shared_ptr<HiSysEventListener> listener, std::vector<ListenerRule>& rules) | Registers a listener for system events. You can listen for certain events by specifying rules.
Input arguments:
- **listener**: callback object for system events.
- **rules**: rules for event listening.
Return value:
- **0**: Registration is successful.
- A negative value: Registration has failed.|
-| int32_t HiSysEventManager::RemoveListener(std::shared_ptr<HiSysEventListener> listener) | Removes the listener for system events.
Input arguments:
- **listener**: callback object for system events.
Return value:
- **0**: Canceling registration is successful.
- A negative value: Canceling registration has failed. |
+HiSysEvent is implemented using the APIs provided by the **HiSysEventManager** class. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
- **Table 2** Description of ListenerRule
+> **NOTE**
+>
+> For details about the **RuleType** argument in the constructor of **ListenerRule**, see Table 4 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md).
+
+ **Table 1** Description of C++ HiSysEventManager APIs
-| API| Description|
+| Name| Description|
| -------- | -------- |
-| ListenerRule(const std::string& tag, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event tag.
Input arguments:
- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
-| ListenerRule(const std::string& domain, const std::string& eventName, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain and event name.
Input arguments:
- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.
- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
-| ListenerRule(const std::string& domain, const std::string& eventName, const std::string& tag, RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.
Input arguments:
- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.
- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.
- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
+| int32_t HiSysEventManager::AddListener(std::shared_ptr<HiSysEventListener> listener,
std::vector<ListenerRule>& rules) | Adds a listener to listen for system events based on the specified rules.
Input arguments:
- **listener**: listener for system events.
- **rules**: event listening rules.
Return value:
- **0**: The listener is added successfully.
- A negative value: The listener fails to be added.|
+| int32_t HiSysEventManager::RemoveListener(std::shared_ptr<HiSysEventListener> listener) | Removes the listener for system events.
Input arguments:
- **listener**: listener for system events.
Return value:
- **0**: The listener is removed successfully.
- A negative value: The listener fails to be removed. |
- **Table 3** Description of RuleType
+ **Table 2** Description of ListenerRule
-| Value| Description|
+| Name| Description|
| -------- | -------- |
-| WHOLE_WORD | Whole word matching|
-| PREFIX | Prefix matching|
-| REGULAR | Regular expression matching|
+| ListenerRule(const std::string& tag,
RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event tag.
Input arguments:
- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
+| ListenerRule(const std::string& domain,
const std::string& eventName,
RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain and event name.
Input arguments:
- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.
- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
+| ListenerRule(const std::string& domain,
const std::string& eventName,
const std::string& tag,
RuleType ruleType = RuleType::WHOLE_WORD) | Constructor used to create a **ListenerRule** object based on the event domain, event name, and event tag.
Input arguments:
- **tag**: event tag for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, lowercase letters, and digits.
- **domain**: event domain for the **ListenerRule** object. The value is a string of 1 to 16 characters, including uppercase letters, digits, and underscores.
- **eventName**: event name for the **ListenerRule** object. The value is a string of 1 to 32 characters, including uppercase letters, digits, and underscores.
- **ruleType**: type of the **ListenerRule** object. The value is an enum defined by **RuleType**.|
- **Table 4** Description of HiSysEventListener
+ **Table 3** Description of HiSysEventListener
-| API| Description|
+| Name| Description|
| -------- | -------- |
-| void HiSysEventListener::OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent) | Callback object for system events.
Input arguments:
- **sysEvent**: real-time system events.
Return value:
None.|
-| void HiSysEventListener::OnServiceDied() | Callback object for service exceptions.
Input arguments:
None.
Return value:
None.|
+| void HiSysEventListener::OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent) | Callback object for system events.
Input arguments:
- **sysEvent**: real-time system event.
Return value:
None.|
+| void HiSysEventListener::OnServiceDied() | Callback object for service exceptions.
Input arguments:
None.
Return value:
None.|
-**Table 5** Description of HiSysEventRecord
-| API| Description|
+ **Table 4** Description of HiSysEventRecord
+| Name| Description|
| -------- | -------- |
-|std::string HiSysEventRecord::AsJson()|Obtains the content of a system event.
Input arguments:
None.
Return value:
Content of the system event.|
-|std::string HiSysEventRecord::GetDomain()|Obtains the domain name of a system event.
Input arguments:
None.
Return value:
Domain name of the system event.|
-|std::string HiSysEventRecord::GetEventName()|Obtains the name of a system event.
Input arguments:
None.
Return value:
Name of the system event.|
-|HiSysEvent::EventType HiSysEventRecord::GetEventType()|Obtains the type of a system event.
Input arguments:
None.
Return value:
Type of the system event.|
-|std::string HiSysEventRecord::GetLevel()|Obtains the level of a system event.
Input arguments:
None.
Return value:
Level of the system event.|
-|std::string HiSysEventRecord::GetTag()|Obtains the tag of a system event.
Input arguments:
None.
Return value:
Tag of the system event.|
-|std::string HiSysEventRecord::GetTimeZone()|Obtains the time zone of a system event.
Input arguments:
None.
Return value:
Time zone, in the format of **+0800**.|
-|int HiSysEventRecord::GetTraceFlag()|Obtains the distributed call chain tracing flag of a system event.
Input arguments:
None.
Return value:
Distributed call chain tracing flag.|
-|int64_t HiSysEventRecord::GetPid()|Obtains the ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
Process ID.|
-|int64_t HiSysEventRecord::GetTid()|Obtains the thread ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
Thread ID.|
-|int64_t HiSysEventRecord::GetUid()|Obtains the user ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
User ID.|
-|uint64_t HiSysEventRecord::GetPspanId()|Obtains the parent span ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
Parent span ID of the distributed call chain tracing task.|
-|uint64_t HiSysEventRecord::GetSpandId()|Obtains the span ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
Span ID of the distributed call chain tracing task.|
-|uint64_t HiSysEventRecord::GetTime()|Obtains the timestamp of a system event.
Input arguments:
None.
Return value:
Timestamp of the system event.|
-|uint64_t HiSysEventRecord::GetTraceId()|Obtains the ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
ID of the distributed call chain tracing task.|
-|void HiSysEventRecord::GetParamNames(std::vector<std::string>& params)|Obtains all key names of a system event.
Input arguments:
- **params**: key name array reference.
Return value:
None.|
-|int HiSysEventRecord::GetParamValue(const std::string& param, int64_t& value)|Parses the value of the **param** key in a system event into an int64\_t value.
Input arguments:
- **param**: key name.
- **value**: int64\_t reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
-|int HiSysEventRecord::GetParamValue(const std::string& param, uint64_t& value)|Parses the value of the **param** key in a system event into a uint64\_t value.
Input arguments:
- **param**: key name.
- **value**: uint64\_t reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
-|int HiSysEventRecord::GetParamValue(const std::string& param, double& value)|Parses the value of the **param** key in a system event into a double value.
Input arguments:
- **param**: key name.
- **value**: double reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
-|int HiSysEventRecord::GetParamValue(const std::string& param, std::string& value)|Parses the value of the **param** key in a system event into a string value.
Input arguments:
- **param**: key name.
- **value**: std::string reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
-|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<int64_t>& value)|Parses the value of the **param** key in a system event into an int64\_t array.
Input arguments:
- **param**: key name.
- **value**: int64\_t array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
-|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<uint64_t>& value)|Parses the value of the **param** key in a system event into a uint64\_t array.
Input arguments:
- **param**: key name.
- **value**: uint64\_t array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
-|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<double>& value)|Parses the value of the **param** key in a system event into a double array.
Input arguments:
- **param**: key name.
- **value**: double array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
-|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<std::string>& value)|Parses the value of the **param** key in a system event into a string array.
Input arguments:
- **param**: key name.
- **value**: std::string array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
-
-
-## How to Develop
-
-
-### **C++**
-
-The following provides an example of how to use C++ APIs of **HiSysEvent**.
-
-1. Develop the source code.
- Import the **DemoListener.h** header file, which contains the **DemoListener** class for implementing the custom event callback.
-
- ```
- #ifndef DEMO_LISTENER_H
- #define DEMO_LISTENER_H
-
- #include "hisysevent_listener.h"
-
- #include
-
- class DemoListener : public OHOS::HiviewDFX::HiSysEventListener {
- public:
- explicit DemoListener() : HiSysEventListener() {}
- virtual ~DemoListener() {}
-
- public:
- void OnEvent(std::shared_ptr sysEvent);
- void OnServiceDied();
- };
-
- #endif // DEMO_LISTENER_H
- ```
-
- Create the **DemoListener.cpp** file, and add the implementation logic of the custom event callback API in the **DemoListener** class.
-
- ```
- #include "demo_listener.h"
-
- #include
-
- void DemoListener::OnEvent(std::shared_ptr sysEvent)
- {
- if (sysEvent == nullptr) {
- return;
+|std::string HiSysEventRecord::AsJson()|Obtains the content of a system event.
Input arguments:
None.
Return value:
Content of the system event.|
+|std::string HiSysEventRecord::GetDomain()|Obtains the domain name of a system event.
Input arguments:
None.
Return value:
Domain name of the system event.|
+|std::string HiSysEventRecord::GetEventName()|Obtains the name of a system event.
Input arguments:
None.
Return value:
Name of the system event.|
+|HiSysEvent::EventType HiSysEventRecord::GetEventType()|Obtains the type of a system event.
Input arguments:
None.
Return value:
Type of the system event.|
+|std::string HiSysEventRecord::GetLevel()|Obtains the level of a system event.
Input arguments:
None.
Return value:
Level of the system event.|
+|std::string HiSysEventRecord::GetTag()|Obtains the tag of a system event.
Input arguments:
None.
Return value:
Tag of the system event.|
+|std::string HiSysEventRecord::GetTimeZone()|Obtains the time zone of a system event.
Input arguments:
None.
Return value:
Time zone, in the format of **+0800**.|
+|int HiSysEventRecord::GetTraceFlag()|Obtains the distributed call chain tracing flag of a system event.
Input arguments:
None.
Return value:
Distributed call chain tracing flag.|
+|int64_t HiSysEventRecord::GetPid()|Obtains the ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
Process ID.|
+|int64_t HiSysEventRecord::GetTid()|Obtains the thread ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
Thread ID.|
+|int64_t HiSysEventRecord::GetUid()|Obtains the user ID of the process that flushes a system event to the disk.
Input arguments:
None.
Return value:
User ID.|
+|uint64_t HiSysEventRecord::GetPspanId()|Obtains the parent span ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
Parent span ID of the distributed call chain tracing task.|
+|uint64_t HiSysEventRecord::GetSpandId()|Obtains the span ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
Span ID of the distributed call chain tracing task.|
+|uint64_t HiSysEventRecord::GetTime()|Obtains the timestamp of a system event.
Input arguments:
None.
Return value:
Timestamp.|
+|uint64_t HiSysEventRecord::GetTraceId()|Obtains the ID of the distributed call chain tracing task.
Input arguments:
None.
Return value:
ID of the distributed call chain tracing task.|
+|void HiSysEventRecord::GetParamNames(std::vector<std::string>& params)|Obtains all key names of a system event.
Input arguments:
- **params**: key name array reference.
Return value:
None.|
+|int HiSysEventRecord::GetParamValue(const std::string& param, int64_t& value)|Parses the value of the **param** key in a system event into an int64\_t value.
Input arguments:
- **param**: key name.
- **value**: int64\_t reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
+|int HiSysEventRecord::GetParamValue(const std::string& param, uint64_t& value)|Parses the value of the **param** key in a system event into a uint64\_t value.
Input arguments:
- **param**: key name.
- **value**: uint64\_t reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
+|int HiSysEventRecord::GetParamValue(const std::string& param, double& value)|Parses the value of the **param** key in a system event into a double value.
Input arguments:
- **param**: key name.
- **value**: double reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
+|int HiSysEventRecord::GetParamValue(const std::string& param, std::string& value)|Parses the value of the **param** key in a system event into a string value.
Input arguments:
- **param**: key name.
- **value**: std::string reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
+|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<int64_t>& value)|Parses the value of the **param** key in a system event into an int64\_t array.
Input arguments:
- **param**: key name.
- **value**: int64\_t array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
+|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<uint64_t>& value)|Parses the value of the **param** key in a system event into a uint64\_t array.
Input arguments:
- **param**: key name.
- **value**: uint64\_t array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
+|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<double>& value)|Parses the value of the **param** key in a system event into a double array.
Input arguments:
- **param**: key name.
- **value**: double array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
+|int HiSysEventRecord::GetParamValue(const std::string& param, std::vector<std::string>& value)|Parses the value of the **param** key in a system event into a string array.
Input arguments:
- **param**: key name.
- **value**: std::string array reference.
Return value:
- **0**: Parsing is successful.
- **-1**: Parsing failed due to initialization error.
- **-2**: Parsing failed due to nonexistent key name.
- **-3**: Parsing failed due to type mismatch.|
+
+#### C APIs
+
+HiSysEvent listening is implemented using the API provided in the following table. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
+
+> **NOTE**
+>
+> For details about the **HiSysEventRecord** argument in the **OnEvent** callback of **HiSysEventWatcher**, see Table 11 and Table 12 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md).
+
+ **Table 5** Description of C HiSysEventManager APIs
+
+| Name | Description |
+| ------------------------------------------------------------ | ------------------------------------------------------------ |
+| int OH_HiSysEvent_Add_Watcher(HiSysEventWatcher* watcher,
HiSysEventWatchRule rules[],
size_t ruleSize); | Adds a listener to listen for system events based on the specified rules.
Input arguments:
- **watcher**: watcher for system events.
- **rules**: array of event listening rules.
- **ruleSize**: length of the array of event listening rules.
Return value:
- **0**: The listener is added successfully.
- A negative value: The listener fails to be added.|
+| int OH_HiSysEvent_Remove_Watcher(HiSysEventWatcher* watcher); | Remove the watcher for system events.
Input arguments:
- **watcher**: watcher for system events.
Return value:
- **0**: The watcher is removed successfully.
- A negative value: The watcher fails to be removed. |
+
+
+ **Table 6** Description of the HiSysEventWatcher structure
+| Field | Type | Description |
+| ------------- | -------------------------------------------------- | ------------------------------------------------------------ |
+| OnEvent | void (*)(HiSysEventRecord record); | Callback object for system events.
Input arguments:
- **record**: real-time system event.
Return value:
None.|
+| OnServiceDied | void (*)(); | Callback object for service exceptions.
Input arguments:
None.
Return value:
None. |
+
+ **Table 7** Description of the HiSysEventWatchRule structure
+| Field | Type | Description |
+| ------------- | --------- | ---------------------------------- |
+| domain | char[] | Event domain. |
+| name | char[] | Event name. |
+| tag | char[] | Event tag. |
+| ruleType | int | Event matching rule. For details about the values, see Table 4 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md). |
+| eventType | int | Event type. For details about the values, see Table 3 in [HiSysEvent Query](subsys-dfx-hisysevent-query.md). The value **0** indicates all event types. |
+
+### How to Develop
+
+#### C++ HiSysEvent Listening
+
+1. Import the corresponding header file.
+
+ ```c++
+ #include "hisysevent_manager.h"
+ ```
+
+2. Implement the callback API for the service domain.
+
+ ```c++
+ class TestListener : public OHOS::HiviewDFX::HiSysEventListener {
+ public:
+ void OnEvent(std::shared_ptr record)
+ {
+ if (record == nullptr) {
+ return;
+ }
+ std::cout << record->AsJson() << std::endl;
+ }
+
+ void OnServiceDied()
+ {
+ std::cout << std::string("service disconnect, exit") << std::endl;
+ exit(0);
+ }
+ };
+ ```
+
+3. Call the listening API while passing in parameters such as **listener** and **rules**. When the service ends, disable event listening.
+
+ ```c++
+ auto testListener = std::make_shared();
+ // Add a ListenerRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
+ ListenerRule tagRule("dfx");
+ // Add a ListenerRule object based on the event tag, with RuleType set as REGULAR.
+ ListenerRule regRule("dfx.*", RuleType::REGULAR);
+ // Add a ListenerRule object based on the event domain and event name, with RuleType set as PREFIX.
+ ListenerRule domainNameRule("HIVIEWDFX", "APP_USAGE", RuleType::PREFIX);
+ std::vector sysRules;
+ sysRules.push_back(tagRule);
+ sysRules.push_back(regRule);
+ sysRules.push_back(domainNameRule);
+ // Start event listening.
+ auto ret = HiSysEventManager::AddEventListener(testListener, sysRules);
+ // Remove the listener when the service ends.
+ if (ret == 0) {
+ HiSysEventManager::RemoveListener(testListener);
+ }
+ ```
+
+#### C HiSysEvent Listening
+
+1. Import the corresponding header file.
+
+ ```c++
+ #include "hisysevent_manager_c.h"
+ ```
+
+2. Implement the callback API for the service domain.
+
+ ```c++
+ void OnEventTest(HiSysEventRecord record)
+ {
+ printf("OnEventTest: event=%s", record.jsonStr);
+ }
+
+ void OnServiceDiedTest()
+ {
+ printf("OnServiceDied");
+ }
+ ```
+
+3. Call the listening API while passing in parameters such as **watcher** and **rules**. When the service ends, disable event listening.
+
+ ```c++
+ HiSysEventWatcher watcher;
+ watcher.OnEvent = OnEventTest;
+ watcher.OnServiceDied = OnServiceDiedTest;
+ // Add a HiSysEventWatchRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
+ constexpr char DFX_TAG[] = "dfx";
+ HiSysEventWatchRule tagRule;
+ (void)strcpy_s(tagRule.tag, strlen(DFX_TAG) + 1, DFX_TAG);
+ tagRule.ruleType = 1;
+ tagRule.eventType = 0;
+ // Add a HiSysEventWatchRule object based on the event tag, with RuleType set as REGULAR.
+ constexpr char DFX_PATTERN_TAG[] = "dfx.*";
+ HiSysEventWatchRule regRule;
+ (void)strcpy_s(regRule.tag, strlen(DFX_PATTERN_TAG) + 1, DFX_PATTERN_TAG);
+ regRule.ruleType = 3;
+ regRule.eventType = 0;
+ // Add a HiSysEventWatchRule object based on the event domain and event name, with RuleType set as PREFIX.
+ constexpr char DOMAIN[] = "HIVIEWDFX";
+ constexpr char NAME[] = "APP_USAGE";
+ HiSysEventWatchRule domainNameRule;
+ (void)strcpy_s(domainNameRule.domain, strlen(DOMAIN) + 1, DOMAIN);
+ (void)strcpy_s(domainNameRule.name, strlen(NAME) + 1, NAME);
+ domainNameRule.ruleType = 2;
+ domainNameRule.eventType = 0;
+ // Start event listening.
+ HiSysEventWatchRule rules[] = {tagRule, regRule, domainNameRule};
+ int ret = OH_HiSysEvent_Add_Watcher(&watcher, rules, sizeof(rules) / sizeof(HiSysEventWatchRule));
+ // Remove the watcher when the service ends.
+ if (ret == 0) {
+ ret = OH_HiSysEvent_Remove_Watcher(&watcher);
+ }
+ ```
+
+### Development Examples
+
+#### C++ HiSysEvent Listening
+
+Suppose you want to enable listening for all events whose domain is **HIVIEWDFX** and name is **PLUGIN_LOAD**. The sample code is as follows:
+
+1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to the **BUILD.gn** file of the service module.
+
+ ```c++
+ external_deps = [
+ "hisysevent:libhisysevent",
+ "hisysevent:libhisyseventmanager",
+ ]
+ ```
+
+2. Call the listening API in the **TestEventListening()** function. When the service ends, disable event listening.
+
+ ```c++
+ #include
+
+ #include "hisysevent_manager.h"
+
+ using namespace OHOS::HiviewDFX;
+
+ class TestListener : public HiSysEventQueryCallback {
+ public:
+ void OnEvent(std::shared_ptr record)
+ {
+ if (record == nullptr) {
+ return;
+ }
+ std::cout << record->AsJson() << std::endl;
+ }
+
+ void OnServiceDied()
+ {
+ std::cout << std::string("service disconnect, exit") << std::endl;
+ exit(0);
+ }
+ };
+
+ void TestEventListening()
+ {
+ auto testListener = std::make_shared();
+ ListenerRule domainNameRule("HIVIEWDFX", "PLUGIN_LOAD", RuleType::WHOLE_WORD);
+ std::vector sysRules;
+ sysRules.push_back(domainNameRule);
+ auto ret = HiSysEventManager::AddEventListener(testListener, sysRules);
+ if (ret == 0) {
+ HiSysEventManager::RemoveListener(testListener);
+ }
+ }
+ ```
+
+#### C HiSysEvent Listening
+
+Suppose you want to enable listening for all events whose domain is **HIVIEWDFX** and name is **PLUGIN_LOAD**. The sample code is as follows:
+
+1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to the **BUILD.gn** file of the service module.
+
+ ```c++
+ external_deps = [ "hisysevent:libhisyseventmanager" ]
+
+ // for strcpy_s
+ deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
+ ```
+
+2. Call the listening API in the **TestEventListening()** function. When the service ends, disable event listening.
+
+ ```c++
+ #include
+
+ #include "hisysevent_manager_c.h"
+
+ void OnEventTest(HiSysEventRecord record)
+ {
+ printf("OnEventTest: event=%s", record.jsonStr);
+ }
+
+ void OnServiceDiedTest()
+ {
+ printf("OnServiceDied");
+ }
+
+ void TestEventListening()
+ {
+ HiSysEventWatcher watcher;
+ watcher.OnEvent = OnEventTest;
+ watcher.OnServiceDied = OnServiceDiedTest;
+ constexpr char DOMAIN[] = "HIVIEWDFX";
+ constexpr char NAME[] = "PLUGIN_LOAD";
+ HiSysEventWatchRule domainNameRule;
+ (void)strcpy_s(domainNameRule.domain, strlen(DOMAIN) + 1, DOMAIN);
+ (void)strcpy_s(domainNameRule.name, strlen(NAME) + 1, NAME);
+ domainNameRule.ruleType = 1;
+ domainNameRule.eventType = 0;
+ HiSysEventWatchRule rules[] = {domainNameRule};
+ int ret = OH_HiSysEvent_Add_Watcher(&watcher, rules, sizeof(rules) / sizeof(HiSysEventWatchRule));
+ if (ret == 0) {
+ ret = OH_HiSysEvent_Remove_Watcher(&watcher);
}
- std::cout << sysEvent.AsJson() << std::endl;
- }
-
- void DemoListener::OnServiceDied()
- {
- std::cout << std::string("service disconnect, exit") << std::endl;
- exit(0);
- }
- ```
-
- Call the **AddEventListener** API of the **HiSysEventManager** class to add a listener for system events.
-
- ```
- auto demoListener = std::make_shared();
- // Add a ListenerRule object based on the event tag, with RuleType left unspecified (in this case, ruleType is defaulted to WHOLE_WORD).
- ListenerRule tagRule("dfx");
- // Add a ListenerRule object based on the event tag, with RuleType set as REGULAR.
- ListenerRule regRule("dfx.*", RuleType::REGULAR);
- // Add a ListenerRule object based on the event domain and event name, with RuleType set as PREFIX.
- ListenerRule domainNameRule("HIVIEWDFX", "APP_USAGE", RuleType::PREFIX);
- std::vector sysRules;
- sysRules.push_back(tagRule);
- sysRules.push_back(regRule);
- sysRules.push_back(domainNameRule);
- HiSysEventManager::AddEventListener(demoListener, sysRules);
- ```
-
-2. Configure the **BUILD.gn** file.
- In the **BUILD.gn** file, add the **libhisysevent** and **libhisyseventmanager** libraries that depend on the **hisysevent** component.
-
- ```
- external_deps = [
- "hisysevent:libhisysevent",
- "hisysevent:libhisyseventmanager",
- ]
- ```
+ }
+ ```
diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md
index 940b8188945ffdc01c6b35a44a27019339a69768..0e50997085deb3c75f917cfeaac8af51711d1eb1 100644
--- a/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md
+++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-logging-config.md
@@ -33,10 +33,11 @@ Constraints on the event domain, event name, and parameter
| Field| Description|
| -------- | -------- |
- | type | Event type. This field is mandatory.
Value:
- FAULT: fault
- STATISTIC: statistics
- SECURITY: security
- BEHAVIOR: user behavior|
+ | type | Event type. This field is mandatory.
Value:
- **FAULT**: fault
- STATISTIC: statistics
- **SECURITY**: security
- **BEHAVIOR**: behavior|
| level | Event level. This field is mandatory.
Value:
- CRITICAL: critical
- MINOR: minor|
| tag | Event tag. This field is mandatory.
Rule:
- You can define a maximum of five tags, separated with a space.
- A single tag can contain a maximum of 16 characters, including a to z, A to Z, and 0 to 9.|
- | desc | Event name. This field is mandatory.
Rule:
The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).|
+ | desc | Event name. This field is mandatory.
Rule:
- A string of 3 to 128 characters.|
+ | preserve | Whether events need to be logged in the event file. This field is optional. The default value is **true**.
Value:
- **true**: Events need to be logged in the event file.
- **false**: Events do not need to be logged in the event file.|
**Table 2** Description of custom parameters
@@ -44,7 +45,7 @@ Constraints on the event domain, event name, and parameter
| -------- | -------- |
| type | Parameter type. This field is mandatory.
Value:
- BOOL
- INT8
- UINT8
- INT16
- UINT16
- INT32
- UINT32
- INT64
- UINT64
- FLOAT
- DOUBLE
- STRING |
| arrsize | Length of the parameter of the array type. This field is optional.
Value:
1-100|
- | desc | Parameter description. This field is mandatory.
Rule:
The description contains 3 to 128 characters, including a to z, A to Z, 0 to 9, and underscores (_).|
+ | desc | Parameter description. This field is mandatory.
Rule:
- A string of 3 to 128 characters.|
## How to Develop
diff --git a/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md b/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md
index 88fd95fd4aafaa5d4d27d0da7649cceb7836d577..fe4151d04c5a38dd9edac2defa06648b7a849e49 100644
--- a/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md
+++ b/en/device-dev/subsystems/subsys-dfx-hisysevent-query.md
@@ -10,99 +10,119 @@ HiSysEvent allows you to query system events by specifying search criteria. For
### Available APIs
-#### C++ Event Query API
+#### C++ APIs
HiSysEvent query is implemented using the API provided by the **HiSysEventManager** class. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
> **NOTE**
>
-> For details about **HiSysEventRecord** in the **OnQuery()** API of **HiSysEventQueryCallback**, see Table 5 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
+> For details about **HiSysEventRecord** in the **OnQuery()** API of **HiSysEventQueryCallback**, see Table 4 in [HiSysEvent Listening](subsys-dfx-hisysevent-listening.md).
- **Table 1** Description of the HiSysEvent query API
+ **Table 1** Description of the C++ HiSysEvent query API
-| API| Description|
+| Name| Description|
| -------- | -------- |
-| int32_t Query(struct QueryArg& arg,
std::vector<QueryRule>& rules,
std::shared_ptr<HiSysEventQueryCallback> callback) | Queries system events by search criteria such as the time segment, event domain, and event name.
Input arguments:
- **arg**: event query parameter.
- **rules**: rules for event filtering.
- **callback**: callback object for event query.
Return value:
- **0**: Query is successful.
- A negative value: Query has failed.|
+| int32_t Query(struct QueryArg& arg,
std::vector<QueryRule>& rules,
std::shared_ptr<HiSysEventQueryCallback> callback) | Queries system events by search criteria such as the time segment, event domain, and event name.
Input arguments:
- **arg**: event query parameter.
- **rules**: event filtering rules.
- **callback**: callback object for event query.
Return value:
- **0**: Query is successful.
- A negative value: Query has failed.|
**Table 2** Description of QueryArg objects
-| Attribute| Type| Description|
+| Field| Type| Description|
| -------- | -------- | -------- |
| beginTime | long long | Start time for query. The value is a Unix timestamp, in milliseconds.|
| endTime | long long | End time for query. The value is a Unix timestamp, in milliseconds.|
| maxEvents | int | Maximum number of returned events.|
- **Table 3** Description of QueryRule objects
+ **Table 3** Description of EventType enums
-| API| Description|
+| Event Type| Value| Description|
+| ------------ | ---- | ------------------ |
+| FAULT | 1 | Fault type. |
+| STATISTIC | 2 | Statistical type. |
+| SECURITY | 3 | Security type. |
+| BEHAVIOR | 4 | User behavior type.|
+
+ **Table 4** RuleType enum values
+
+| Rule Type| Value| Description|
+| ------------ | ---- | ------------------ |
+| WHOLE_WORD | 1 | Whole word matching. |
+| PREFIX | 2 | Prefix matching. |
+| REGULAR | 3 | Regular expression matching. |
+
+ **Table 5** Description of QueryRule objects
+
+| Name| Description|
| -------- | -------- |
-| QueryRule(const std::string& domain,
const std::vector<std::string>& eventList) | Constructor used to create a **QueryRule** object.
Input arguments:
- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.
**eventList**: event name list, in the **std::vector<std::string>** format. By default, an empty string indicates that the event names on the list are successfully matched.|
+| QueryRule(const std::string& domain,
const std::vector<std::string>& eventList,
RuleType ruleType,
uint32_t eventType,
const std::string& cond) | Constructor used to create a **QueryRule** object.
Input arguments:
- **domain**: domain to which the event of the **QueryRule** object belongs, in the string format. By default, an empty string indicates that the domain is successfully matched.
**eventList**: event name list, in the **std::vector<std::string>** format. By default, an empty string indicates that the event names on the list are successfully matched.
- **ruleType**: rule type. For details, see Table 4.
- **eventType**: system event type. The value is of the uint32_t type. For details about the system event types, see Table 3. When **eventType** is set to **0**, all types of events are queried.
- **cond**: query criteria. The value is of the string type.|
+
+The **condition** parameter must be in the specified JSON string format. For example:
+
+ ```json
+ {
+ "version":"V1",
+ "condition":{
+ "and":[
+ {"param":"type_","op":">","value":0},
+ {"param":"uid_","op":"=","value":1201}
+ ]
+ }
+ }
+ ```
+- The **version** field is mandatory, indicating the supported version of the input condition. Currently, only **V1** is supported.
+- The **condition** field is mandatory, indicating the input condition.
+ - The **and** field is optional, indicating the AND relationship between conditions.
+ - The **param** field is mandatory, indicating the parameter name for condition matching. The value must be a string.
+ - The **op** field is mandatory, indicating the parameter comparison operator for condition matching. The value must be a string. Supported comparison operators include the following: =, >, <, >=, and <=.
+ - The **value** field is mandatory, indicating the parameter value for condition matching. The value must be a string or an integer.
- **Table 4** Description of HiSysEventQueryCallback objects
-| API| Description|
+
+
+
+**Table 6** Description of HiSysEventQueryCallback objects
+
+| Name| Description|
| -------- | -------- |
| void HiSysEventQueryCallback::OnQuery(std::shared_ptr<std::vector<HiSysEventRecord>> sysEvents) | Callback object for event query.
Input arguments:
- **sysEvents**: event list.|
| void HiSysEventQueryCallback::OnComplete(int32_t reason, int32_t total) | Callback object for completion of event query.
Input arguments:
- **reason**: reason for completion of event query. The value **0** indicates that the query is normal, and any other value indicates that the query has failed.
- **total**: total number of events returned in this query.|
-#### C Event Query API
+#### C APIs
HiSysEvent query is implemented using the API provided in the following table. For details, see the [API Header Files](/base/hiviewdfx/hisysevent/interfaces/native/innerkits/hisysevent_manager/include/).
- **Table 5** Description of the HiSysEvent query API
+ **Table 7** Description of the C HiSysEvent query API
-| API | Description |
+| Name | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
-| int OH_HiSysEvent_Query(const HiSysEventQueryArg& arg, HiSysEventQueryRule rules[], size_t ruleSize, HiSysEventQueryCallback& callback); | Queries system events by search criteria such as the time segment, event domain, event name, and event parameter.
Input arguments:
- **arg**: event query parameter.
- **rules**: rules for event filtering.
- **ruleSize**: number of event filtering rules.
- **callback**: callback object for event query.
Return value:
- **0**: Query is successful.
- A negative value: Query has failed.|
+| int OH_HiSysEvent_Query(const HiSysEventQueryArg& arg, HiSysEventQueryRule rules[], size_t ruleSize, HiSysEventQueryCallback& callback); | Queries system events by search criteria such as the time segment, event domain, event name, and event parameter.
Input arguments:
- **arg**: event query parameter.
- **rules**: event filtering rules.
- **ruleSize**: number of event filtering rules.
- **callback**: callback object for event query.
Return value:
- **0**: Query is successful.
- A negative value: Query has failed.|
- **Table 6** Description of the HiSysEventQueryArg structure
+ **Table 8** Description of the HiSysEventQueryArg structure
-| Attribute | Type| Description |
+| Field | Type| Description |
| --------- | -------- | ---------------------------------------------------- |
| beginTime | int64_t | Start time for query. The value is a Unix timestamp, in milliseconds.|
| endTime | int64_t | End time for query. The value is a Unix timestamp, in milliseconds.|
| maxEvents | int32_t | Maximum number of returned events. |
-**Table 7** Description of the HiSysEventQueryRule structure
+ **Table 9** Description of the HiSysEventQueryRule structure
-| Attribute | Type | Description |
+| Field | Type | Description |
| ------------- | --------- | ---------------------------------- |
| domain | char[] | Event domain. |
| eventList | char\[][] | Event name list. |
| eventListSize | size_t | Size of the event name list. |
| condition | char* | Custom event parameter conditions for the query.|
-The **condition** parameter must be in the specified JSON string format. For example:
-
-```json
-{
- "version":"V1",
- "condition":{
- "and":[
- {"param":"type_","op":">","value":0},
- {"param":"uid_","op":"=","value":1201}
- ]
- }
-}
-```
-
-- The **version** field is mandatory, indicating the supported version of the input condition. Currently, only **V1** is supported.
-- The **condition** field is mandatory, indicating the input condition.
- - The **and** field is optional, indicating the AND relationship between conditions.
- - The **param** field is mandatory, indicating the parameter name for condition matching. The value must be a string.
- - The **op** field is mandatory, indicating the parameter comparison operator for condition matching. The value must be a string. Supported comparison operators include the following: =, >, <, >=, and <=.
- - The **value** field is mandatory, indicating the parameter value for condition matching. The value must be a string or an integer.
-
-**Table 8** Description of the HiSysEventQueryCallback structure
+ **Table 10** Description of the HiSysEventQueryCallback structure
-| Attribute | Type | Description |
+| Field | Type | Description |
| ---------- | -------------------------------------------------- | ------------------------------------------------------------ |
| OnQuery | void (*)(HiSysEventRecord records[], size_t size); | Callback object for event query.
Input arguments:
- **records**: event list.
- **size**: size of the event list.|
| OnComplete | void (*)(int32_t reason, int32_t total); | Callback object for completion of event query.
Input arguments:
- **reason**: reason for completion of event query. The value **0** indicates that the query is normal, and any other value indicates that the query has failed.
- **total**: total number of events returned in this query.|
-**Table 9** Description of the HiSysEventRecord event structure
+ **Table 11** Description of the HiSysEventRecord event structure
-| Attribute | Type | Description |
+| Field | Type | Description |
| --------- | ------------------- | -------------------------- |
| domain | char[] | Event domain. |
| eventName | char\[] | Event name. |
@@ -120,13 +140,13 @@ The **condition** parameter must be in the specified JSON string format. For exa
| tag | char* | Event tag. |
| jsonStr | char* | Event content. |
-**Table 10** Description of HiSysEventRecord APIs
+ **Table 12** Description of HiSysEventRecord APIs
-| API | |
+| Name | |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| void OH_HiSysEvent_GetParamNames(const HiSysEventRecord& record, char*** params, size_t& len); | Obtains all parameter names of an event.
Input arguments:
- **record**: event structure.
- **params**: parameter name array.
- **len**: size of the parameter name array.|
| int OH_HiSysEvent_GetParamInt64Value(const HiSysEventRecord& record, const char* name, int64_t& value); | Parses the parameter value in the event to an int64_t value and assigns the value to **value**.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **value**: parameter value of the int64_t type.|
-| int OH_HiSysEvent_GetParamUint64Value(const HiSysEventRecord& record, const char* name, uint64_t& value); | Parses the parameter value in the event to an uint64_t value and assigns the value to **value**.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **value**: parameter value of the uint64_t type.|
+| int OH_HiSysEvent_GetParamUint64Value(const HiSysEventRecord& record, const char* name, uint64_t& value); | Parses the parameter value in the event to a uint64_t value and assigns the value to **value**.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **value**: parameter value of the uint64_t type.|
| int OH_HiSysEvent_GetParamDoubleValue(const HiSysEventRecord& record, const char* name, double& value); | Parses the parameter value in the event to a double value and assigns the value to **value**.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **value**: parameter value of the double type.|
| int OH_HiSysEvent_GetParamStringValue(const HiSysEventRecord& record, const char* name, char** value); | Parses the parameter value in the event to a char array value and assigns the value to **value**. You need to release the memory manually after usage.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **value**: char\* reference.|
| int OH_HiSysEvent_GetParamInt64Values(const HiSysEventRecord& record, const char* name, int64_t** value, size_t& len); | Parses the parameter value in the event to a int64_t array value and assigns the value to **value**. You need to release the memory manually after usage.
Input arguments:
- **record**: event structure.
- **name**: parameter name.
- **value**: int64_t\* reference.
- **len**: array size.|
@@ -143,240 +163,226 @@ The return values of the HiSysEventRecord APIs are described as follows:
### How to Develop
-#### C++ HiSysEvent Query API
-
-1. Import the corresponding header file:
-
- ```c++
- #include "hisysevent_manager.h"
- ```
-
-2. Implement the callback API.
-
- ```c++
- class TestQueryCallback : public HiSysEventQueryCallback {
- public:
- void OnQuery(std::shared_ptr> sysEvents) override
- {
- if (sysEvents == nullptr) {
- return;
- }
- for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
- std::cout << event.AsJson() << std::endl;
- });
- }
-
- void OnComplete(int32_t reason, int32_t total) override
- {
- std::cout << "Query completed" << std::endl;
- return;
- }
- };
- ```
-
-3. Call the query API while passing in the query parameter, rule, and callback object.
-
- ```c++
- // Create a query parameter object.
- long long startTime = 0;
- long long endTime = 1668245644000; //2022-11-12 09:34:04
- int queryCount = 10;
- QueryArg arg(startTime, endTime, queryCount);
-
- // Create a query rule object.
- QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
- std::vector queryRules = { rule };
-
- // Create a query callback object.
- auto queryCallback = std::make_shared();
-
- // Call the query API.
- HiSysEventManager::Query(arg, queryRules, queryCallback);
- ```
-
-#### C HiSysEvent Query API
-
-1. Import the corresponding header file:
-
- ```c++
- #include "hisysevent_manager_c.h"
- ```
-
-2. Implement the callback API.
-
- ```c++
- void OnQueryTest(HiSysEventRecord records[], size_t size)
- {
- for (size_t i = 0; i < size; i++) {
- printf("OnQuery: event=%s", records[i].jsonStr);
- }
- }
-
- void OnCompleteTest(int32_t reason, int32_t total)
- {
- printf("OnCompleted, res=%d, total=%d\n", reason, total);
- }
- ```
-
-3. Call the query API while passing in the query parameter, rule, and callback object.
-
- ```c++
- // Create a query parameter object.
- HiSysEventQueryArg arg;
- arg.beginTime = 0;
- arg.endTime = 1668245644000; //2022-11-12 09:34:04
- arg.maxEvents = 10;
-
- // Create a query rule object.
- constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
- constexpr char TEST_NAME[] = "PLUGIN_LOAD";
- HiSysEventQueryRule rule;
- (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN);
- (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME);
- rule.eventListSize = 1;
- rule.condition = nullptr;
- HiSysEventQueryRule rules[] = { rule };
-
- // Create a query callback object.
- HiSysEventQueryCallback callback;
- callback.OnQuery = OnQueryTest;
- callback.OnComplete = OnCompleteTest;
-
- // Call the query API.
- OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
- ```
-
-### Development Example
+#### C++ HiSysEvent Query
+
+1. Import the corresponding header file.
+
+ ```c++
+ #include "hisysevent_manager.h"
+ ```
+
+2. Implement the callback API for the service domain.
+
+ ```c++
+ class TestQueryCallback : public HiSysEventQueryCallback {
+ public:
+ void OnQuery(std::shared_ptr> sysEvents) override
+ {
+ if (sysEvents == nullptr) {
+ return;
+ }
+ for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
+ std::cout << event.AsJson() << std::endl;
+ });
+ }
+
+ void OnComplete(int32_t reason, int32_t total) override
+ {
+ std::cout << "Query completed" << std::endl;
+ return;
+ }
+ };
+ ```
+
+3. Call the query API while passing in **QueryArg**, **QueryRule**, and **QueryCallback**.
+
+ ```c++
+ // Create a QueryArg object.
+ long long startTime = 0;
+ long long endTime = 1668245644000; //2022-11-12 09:34:04
+ int queryCount = 10;
+ QueryArg arg(startTime, endTime, queryCount);
+
+ // Create a QueryRule object.
+ QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
+ std::vector queryRules = { rule };
+
+ // Create a QueryCallback object.
+ auto queryCallback = std::make_shared();
+
+ // Call the query API.
+ HiSysEventManager::Query(arg, queryRules, queryCallback);
+ ```
+
+#### C HiSysEvent Query
+
+1. Import the corresponding header file.
+
+ ```c++
+ #include "hisysevent_manager_c.h"
+ ```
+
+2. Implement the callback API for the service domain.
+
+ ```c++
+ void OnQueryTest(HiSysEventRecord records[], size_t size)
+ {
+ for (size_t i = 0; i < size; i++) {
+ printf("OnQuery: event=%s", records[i].jsonStr);
+ }
+ }
+
+ void OnCompleteTest(int32_t reason, int32_t total)
+ {
+ printf("OnCompleted, res=%d, total=%d\n", reason, total);
+ }
+ ```
+
+3. Call the query API while passing in **HiSysEventQueryArg**, **HiSysEventQueryRule**, and **HiSysEventQueryCallback**.
+
+ ```c++
+ // Create a HiSysEventQueryArg object.
+ HiSysEventQueryArg arg;
+ arg.beginTime = 0;
+ arg.endTime = 1668245644000; //2022-11-12 09:34:04
+ arg.maxEvents = 10;
+
+ // Create a HiSysEventQueryRule object.
+ constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
+ constexpr char TEST_NAME[] = "PLUGIN_LOAD";
+ HiSysEventQueryRule rule;
+ (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN);
+ (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME);
+ rule.eventListSize = 1;
+ rule.condition = nullptr;
+ HiSysEventQueryRule rules[] = { rule };
+
+ // Create a HiSysEventQueryCallback object.
+ HiSysEventQueryCallback callback;
+ callback.OnQuery = OnQueryTest;
+ callback.OnComplete = OnCompleteTest;
+
+ // Call the query API.
+ OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
+ ```
+
+### Development Examples
#### C++ HiSysEvent Query
-Assume that you need to query all **PLUGIN_LOAD** events that are generated for the **HIVIEWDFX** domain until the current time on a service module. The development procedure is as follows:
+Suppose you want to query all events generated up to the current time with domain being **HIVIEWDFX** and name being **PLUGIN_LOAD**. The sample code is as follows:
-1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to **BUILD.gn** of the service module.
+1. Add the **libhisysevent** and **libhisyseventmanager** dependencies of the **hisysevent** component to the **BUILD.gn** file of the service module.
- ```c++
- external_deps = [
- "hisysevent:libhisysevent",
- "hisysevent:libhisyseventmanager",
- ]
- ```
+ ```c++
+ external_deps = [
+ "hisysevent:libhisysevent",
+ "hisysevent:libhisyseventmanager",
+ ]
+ ```
2. Call the query API in the **TestQuery()** function of the service module.
-
- ```c++
- #include "hisysevent_manager.h"
- #include
- #include
-
- using namespace OHOS::HiviewDFX;
-
- class TestQueryCallback : public HiSysEventQueryCallback {
- public:
- void OnQuery(std::shared_ptr> sysEvents) override
- {
- if (sysEvents == nullptr) {
- return;
- }
- for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
- std::cout << event.AsJson() << std::endl;
- });
- }
-
- void OnComplete(int32_t reason, int32_t total) override
- {
- std::cout << "Query completed" << std::endl;
- return;
- }
- };
-
- int64_t GetMilliseconds()
- {
- auto now = std::chrono::system_clock::now();
- auto millisecs = std::chrono::duration_cast(now.time_since_epoch());
- return millisecs.count();
- }
-
- void TestQuery()
- {
- // Create a query parameter object.
- long long startTime = 0;
- long long endTime = GetMilliseconds();
- int maxEvents = 100;
- QueryArg arg(startTime, endTime, maxEvents);
-
- // Create a query rule object.
- QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
- std::vector queryRules = { rule };
-
- // Create a query callback object.
- auto queryCallback = std::make_shared();
-
- // Call the query API.
- int ret = HiSysEventManager::Query(arg, queryRules, queryCallback);
- }
- ```
+
+ ```c++
+ #include "hisysevent_manager.h"
+ #include
+ #include
+
+ using namespace OHOS::HiviewDFX;
+
+ class TestQueryCallback : public HiSysEventQueryCallback {
+ public:
+ void OnQuery(std::shared_ptr> sysEvents) override
+ {
+ if (sysEvents == nullptr) {
+ return;
+ }
+ for_each((*sysEvents).cbegin(), (*sysEvents).cend(), [](const HiSysEventRecord& event) {
+ std::cout << event.AsJson() << std::endl;
+ });
+ }
+
+ void OnComplete(int32_t reason, int32_t total) override
+ {
+ std::cout << "Query completed" << std::endl;
+ return;
+ }
+ };
+
+ int64_t GetMilliseconds()
+ {
+ auto now = std::chrono::system_clock::now();
+ auto millisecs = std::chrono::duration_cast(now.time_since_epoch());
+ return millisecs.count();
+ }
+
+ void TestQuery()
+ {
+ long long startTime = 0;
+ long long endTime = GetMilliseconds();
+ int maxEvents = 100;
+ QueryArg arg(startTime, endTime, maxEvents);
+ QueryRule rule("HIVIEWDFX", { "PLUGIN_LOAD" });
+ std::vector queryRules = { rule };
+ auto queryCallback = std::make_shared();
+ int ret = HiSysEventManager::Query(arg, queryRules, queryCallback);
+ }
+ ```
#### C HiSysEvent Query
-Assume that you need to query all **PLUGIN_LOAD** events that are generated for the **HIVIEWDFX** domain until the current time on a service module. The development procedure is as follows:
+Suppose you want to query all events generated up to the current time with domain being **HIVIEWDFX** and name being **PLUGIN_LOAD**. The sample code is as follows:
1. Add the **libhisyseventmanager** dependency of the **hisysevent** component to the **BUILD.gn** file of the service module.
- ```c++
- external_deps = [ "hisysevent:libhisyseventmanager" ]
-
- // for strcpy_s
- deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
- ```
+```c++
+ external_deps = [ "hisysevent:libhisyseventmanager" ]
+
+ // for strcpy_s
+ deps = [ "//third_party/bounds_checking_function:libsec_shared" ]
+```
2. Call the query API in the **TestQuery()** function of the service module.
- ```c++
- #include "hisysevent_manager_c.h"
- #include
- #include
+ ```c++
+ #include "hisysevent_manager_c.h"
+ #include
+ #include
- void OnQueryTest(HiSysEventRecord records[], size_t size)
- {
- for (size_t i = 0; i < size; i++) {
- printf("OnQuery: event=%s", records[i].jsonStr);
- }
- }
-
- void OnCompleteTest(int32_t reason, int32_t total)
- {
- printf("OnCompleted, res=%d, total=%d\n", reason, total);
- }
-
- int64_t GetMilliseconds()
- {
- return time(NULL);
- }
-
- void TestQuery()
- {
- // Create a query parameter object.
- HiSysEventQueryArg arg;
- arg.beginTime = 0;
- arg.endTime = GetMilliseconds();
- arg.maxEvents = 100;
-
- // Create a query rule object.
- constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
- constexpr char TEST_NAME[] = "PLUGIN_LOAD";
- HiSysEventQueryRule rule;
- (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN);
- (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME);
- rule.eventListSize = 1;
- rule.condition = nullptr;
- HiSysEventQueryRule rules[] = { rule };
-
- // Create a query callback object.
- HiSysEventQueryCallback callback;
- callback.OnQuery = OnQueryTest;
- callback.OnComplete = OnCompleteTest;
-
- // Call the query API.
- int ret = OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
- }
- ```
+ void OnQueryTest(HiSysEventRecord records[], size_t size)
+ {
+ for (size_t i = 0; i < size; i++) {
+ printf("OnQuery: event=%s", records[i].jsonStr);
+ }
+ }
+
+ void OnCompleteTest(int32_t reason, int32_t total)
+ {
+ printf("OnCompleted, res=%d, total=%d\n", reason, total);
+ }
+
+ int64_t GetMilliseconds()
+ {
+ return time(NULL);
+ }
+
+ void TestQuery()
+ {
+ HiSysEventQueryArg arg;
+ arg.beginTime = 0;
+ arg.endTime = GetMilliseconds();
+ arg.maxEvents = 100;
+ constexpr char TEST_DOMAIN[] = "HIVIEWDFX";
+ constexpr char TEST_NAME[] = "PLUGIN_LOAD";
+ HiSysEventQueryRule rule;
+ (void)strcpy_s(rule.domain, strlen(TEST_DOMAIN) + 1, TEST_DOMAIN);
+ (void)strcpy_s(rule.eventList[0], strlen(TEST_NAME) + 1, TEST_NAME);
+ rule.eventListSize = 1;
+ rule.condition = nullptr;
+ HiSysEventQueryRule rules[] = { rule };
+ HiSysEventQueryCallback callback;
+ callback.OnQuery = OnQueryTest;
+ callback.OnComplete = OnCompleteTest;
+ int ret = OH_HiSysEvent_Query(arg, rules, sizeof(rules) / sizeof(HiSysEventQueryRule), callback);
+ }
+ ```
diff --git a/en/release-notes/OpenHarmony-v4.0-beta2.md b/en/release-notes/OpenHarmony-v4.0-beta2.md
index 892d95e83883ddd30781465bd87481d9897f8bbc..56acfca9e0916441a7ca86aee7adcb19da88747c 100644
--- a/en/release-notes/OpenHarmony-v4.0-beta2.md
+++ b/en/release-notes/OpenHarmony-v4.0-beta2.md
@@ -40,7 +40,7 @@ The standard system capabilities of OpenHarmony 4.0 are continuously improved. A
- RDB store NDK interfaces are provided. These interfaces are used for transaction addition, deletion, modification, and query, data encryption, hierarchical data protection, and backup and restore.
-- The system can automatically selects a Bluetooth or Wi-Fi P2P channel for synchronization of key-value and distributed data objects based on the data volume.
+- The system can automatically select a Bluetooth or Wi-Fi P2P channel for synchronization of key-value and distributed data objects based on the data volume.
### DSoftBus
@@ -391,7 +391,7 @@ This version has the following updates to OpenHarmony 4.0 Beta1.
### API
-For details about the API changes over OpenHarmony 4.0 Beta1, see [API Differences](/api-diff/v4.0-beta2/Readme-EN.md). A few API changes may affect applications developed using API version 9 or earlier. For details about the change impact and adaptation guide, see [Changelogs](changelogs/v4.0-beta2/Readme-EN.md).
+For details about the API changes over OpenHarmony 4.0 Beta1, see [API Differences](https://gitee.com/openharmony/docs/blob/OpenHarmony-4.0-Beta2/en/release-notes/api-diff/v4.0-beta2/Readme-EN.md). A few API changes may affect applications developed using API version 9 or earlier. For details about the change impact and adaptation guide, see [Changelogs](https://gitee.com/openharmony/docs/blob/OpenHarmony-4.0-Beta2/en/release-notes/changelogs/v4.0-beta2/Readme-EN.md).
### Feature Updates
diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.10.2/changelogs-netstack.md b/en/release-notes/changelogs/OpenHarmony_4.0.10.2/changelogs-netstack.md
new file mode 100644
index 0000000000000000000000000000000000000000..4f431b96993df02786377279b2e3fc839f911f1b
--- /dev/null
+++ b/en/release-notes/changelogs/OpenHarmony_4.0.10.2/changelogs-netstack.md
@@ -0,0 +1,43 @@
+# Network Management Subsystem Changelog
+
+## request2 API Name Change
+
+Changed the name of the HTTP streaming request from **request2** to **requestInStream**. The original name **request2** does not clearly express the intent of the API and may cause ambiguity, which does not comply with the OpenHarmony API specifications.
+
+ -
+
+## dataProgress Event Name Change
+
+Changed the name of the streaming data receiving event from **dataProgress** to **dataReceiveProgress**. The original name **dataProgress** does not clearly express the meaning of the event, which does not comply with the OpenHarmony API specifications.
+
+ -
+
+**Change Impact**
+
+For applications developed based on earlier versions, the corresponding API and event names must be updated. Otherwise, API calls may fail, affecting the service logic.
+
+**Key API/Component Changes**
+
+Involved APIs:
+
+ - request2;
+ - on(type: "dataProgress", callback: Callback<{ receiveSize: number, totalSize: number }>): void;
+ - off(type: "dataProgress", callback: Callback<{ receiveSize: number, totalSize: number }>): void;
+
+Before change:
+ - request2(url: string, callback: AsyncCallback): void;
+ - request2(url: string, options: HttpRequestOptions, callback: AsyncCallback): void;
+ - request2(url: string, options?: HttpRequestOptions): Promise;
+ - on(type: "dataProgress", callback: Callback<{ receiveSize: number, totalSize: number }>): void;
+ - off(type: 'dataProgress', callback?: Callback<{ receiveSize: number, totalSize: number }>): void;
+
+After change:
+ - requestInStream(url: string, callback: AsyncCallback): void;
+ - requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback): void;
+ - requestInStream(url: string, options?: HttpRequestOptions): Promise;
+ - on(type: "dataReceiveProgress", callback: Callback<{ receiveSize: number, totalSize: number }>): void;
+ - off(type: 'dataReceiveProgress', callback?: Callback<{ receiveSize: number, totalSize: number }>): void;
+
+**Adaptation Guide**
+
+Replace the API name **request2** and event name **dataProgress** in the original service code with **requestInStream** and **dataReceiveProgress**, respectively.
diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelogs-dfx.md b/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelogs-dfx.md
new file mode 100644
index 0000000000000000000000000000000000000000..06f477d67eeb1c536d6e4a7d68219d82a2d2eddc
--- /dev/null
+++ b/en/release-notes/changelogs/OpenHarmony_4.0.10.3/changelogs-dfx.md
@@ -0,0 +1,22 @@
+# DFX Subsystem Changelog
+
+## cl.hiviewdfx.1 Event Verification Specification Change for the write Method of the HiAppEvent Module
+
+Extended the event verification specifications for the **write** method of the HiAppEvent module to support predefined events of HUAWEI Analytics. Specific changes are as follows:
+
+ - The event name can start with a dollar sign ($) and can contain uppercase letters, lowercase letters, digits, and underscores (_). Before the change, the event name can contain lowercase letters, digits, and underscores (_).
+ - The event parameter name can start with a dollar sign ($) and can contain uppercase letters, lowercase letters, digits, and underscores (_). Before the change, the event parameter name can contain lowercase letters, digits, and underscores (_).
+
+**Change Impact**
+
+More event definition formats are supported for event logging.
+
+**Key API/Component Changes**
+
+Involved APIs:
+
+ - hiAppEvent.write;
+
+**Adaptation Guide**
+
+The event verification specifications are downward compatible. No additional adaptation is required.
diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.11.1/changelogs-file-management.md b/en/release-notes/changelogs/OpenHarmony_4.0.11.1/changelogs-file-management.md
new file mode 100644
index 0000000000000000000000000000000000000000..382fef8b2a763a62643c594cfb4df16e6e25e5a8
--- /dev/null
+++ b/en/release-notes/changelogs/OpenHarmony_4.0.11.1/changelogs-file-management.md
@@ -0,0 +1,115 @@
+# File Subsystem Changelog
+
+## cl.file.1 Change of the userFileManager FileAsset Attribute
+
+Changed the [userFileManager.FileAsset](../../../application-dev/reference/apis/js-apis-userFileManager.md#fileasset) attribute.
+
+URI format before the change:
+
+'file://media/\/\/?networkid=xxx'
+
+URI format after the change:
+
+'file://media/Photo/\/IMG_datetime_0001/displayName.jpg'
+
+**Change Impact**
+
+For applications developed based on earlier versions, check whether the applications depend on or parse the media library URIs. If yes, make adaptation as required. The value of **file_id** is not unique. Do not parse the file ID. Use the URI instead.
+
+**Key API/Component Changes**
+
+| Module | Method/Attribute/Enum/Constant | Change Type|
+| ------------------------- | ------------------------------------------------------------ | -------- |
+| userFileManager | **interface** FileAsset | Attribute changed |
+
+**Adaptation Guide**
+
+In API version 10, the URI format of user files is changed so that basic file information (such as the file name) can be obtained based on the URI. If the new format is used, the URI parsing may yield unexpected result. For example, before the change, the ID obtained from the URI **'file://media/image/8'** is 8. If the new URI format is used, the file **displayName** is obtained. You are advised to use the URI to obtain file information.
+
+**Example**:
+
+```js
+import userFileManager from '@ohos.filemanagement.userFileManager';
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ let context = getContext(this);
+ let mgr = userFileManager.getUserFileMgr(context);
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let uri = 'file://media/Photo/1/IMG_datetime_0001/displayName.jpg' // The URI must exist.
+ predicates.equalTo('uri', uri);
+ let fetchOptions = {
+ fetchColumns: ['uri'],
+ predicates: predicates
+ };
+
+ mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => {
+ if (fetchResult != undefined) {
+ console.info('fetchResult success');
+ let fileAsset = await fetchResult.getFirstObject();
+ if (fileAsset != undefined) {
+ console.info('fileAsset.displayName : ' + fileAsset.displayName);
+ }
+ } else {
+ console.error('fetchResult fail' + err);
+ }
+ });
+}
+```
+
+## cl.file.2 Change of the photoAccessHelper PhotoAsset Attribute
+
+Changed the [photoAccessHelper.PhotoAsset](../../../application-dev/reference/apis/js-apis-photoAccessHelper.md#photoasset) attribute.
+
+URI format before the change:
+
+'file://media/\/\/?networkid=xxx'
+
+URI format after the change:
+
+'file://media/Photo/\/IMG_datetime_0001/displayName.jpg'
+
+**Change Impact**
+
+For applications developed based on earlier versions, check whether the applications depend on or parse the media library URIs. If yes, make adaptation as required. The value of **file_id** is not unique. Do not parse the file ID. Use the URI instead.
+
+**Key API/Component Changes**
+
+| Module | Method/Attribute/Enum/Constant | Change Type|
+| ------------------------- | ------------------------------------------------------------ | -------- |
+| photoAccessHelper | **interface** PhotoAsset | Attribute changed |
+
+**Adaptation Guide**
+
+In API version 10, the URI format of user files is changed so that basic file information (such as the file name) can be obtained based on the URI. If the new format is used, the URI parsing may yield unexpected result. For example, before the change, the ID obtained from the URI **'file://media/image/8'** is 8. If the new URI format is used, the file **displayName** is obtained. You are advised to use the URI to obtain file information.
+
+**Example**:
+
+```js
+import photoAccessHelper from '@ohos.file.photoAccessHelper';
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+
+async function example() {
+ let context = getContext(this);
+ let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
+ let predicates = new dataSharePredicates.DataSharePredicates();
+ let uri = 'file://media/Photo/1/IMG_datetime_0001/displayName.jpg' // The URI must exist.
+ predicates.equalTo('uri', uri);
+ let fetchOptions = {
+ fetchColumns: ['uri'],
+ predicates: predicates
+ };
+
+ phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => {
+ if (fetchResult != undefined) {
+ console.info('fetchResult success');
+ let photoAsset = await fetchResult.getFirstObject();
+ if (photoAsset != undefined) {
+ console.info('photoAsset.displayName : ' + photoAsset.displayName);
+ }
+ } else {
+ console.error('fetchResult fail' + err);
+ }
+ });
+}
+```
diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.7.2/changelogs-telephoy.md b/en/release-notes/changelogs/OpenHarmony_4.0.7.2/changelogs-telephoy.md
new file mode 100644
index 0000000000000000000000000000000000000000..91b9d4fa88ee004cf2e7f55d92e5265d599652df
--- /dev/null
+++ b/en/release-notes/changelogs/OpenHarmony_4.0.7.2/changelogs-telephoy.md
@@ -0,0 +1,122 @@
+# Telephony Subsystem Changelog
+
+
+
+## cl.telephony.1 VoNRState Enum Value Change of setVoNState
+
+Changed the **VoNRState** enum values of the **setVoNState** API. The values value of **VONR_STATE_ON** is changed from **0** to **1** and that of **VONR_STATE_OFF** is defined as **0** to keep consistency with boolean values.
+
+**Change Impact**
+
+The new **VoNRState** enum values need to be used when **setVoNState** is called. The API function remains unchanged.
+
+**Key API/Component Changes**
+
+Before change:
+
+```js
+function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback): void;
+
+/**
+ * @systemapi Hide this for inner system use.
+ * @since 10
+ */
+export enum VoNRState {
+ /** Indicates the VoNR switch is on */
+ VONR_STATE_ON = 0,
+}
+```
+
+After change:
+
+```js
+function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback): void;
+
+/**
+ * Indicates the VoNR state.
+ *
+ * @enum { number }
+ * @syscap SystemCapability.Telephony.CallManager
+ * @systemapi Hide this for inner system use.
+ * @since 10
+ */
+export enum VoNRState {
+ /**
+ * Indicates the VoNR switch is off.
+ *
+ * @syscap SystemCapability.Telephony.CallManager
+ * @systemapi Hide this for inner system use.
+ * @since 10
+ */
+ VONR_STATE_OFF = 0,
+
+ /**
+ * Indicates the VoNR switch is on.
+ *
+ * @syscap SystemCapability.Telephony.CallManager
+ * @systemapi Hide this for inner system use.
+ * @since 10
+ */
+ VONR_STATE_ON = 1,
+}
+```
+
+
+**Adaptation Guide**
+
+When calling **setVoNState**, use the new **VoNRState** enum values. The sample code is as follows:
+
+
+```js
+call.setVoNRState( 0, VONR_STATE_ON, (err) => {
+ if (err) {
+ console.log(`callback: err->${JSON.stringify(err)}`);
+ }
+
+});
+call.setVoNRState( 0, VONR_STATE_OFF, (err) => {
+ console.log(`callback: err->${JSON.stringify(err)}`);
+});
+```
+
+
+## cl.telephony.2 Callback Value Change of setVoNState
+
+Changed the callback value of **setVoNState** from a boolean value to **void**.
+
+**Change Impact**
+
+The callback value needs to be set to **void** when **setVoNState** is called.
+
+**Key API/Component Changes**
+
+Before change:
+
+```js
+function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback): void;
+function setVoNRState(slotId: number, state: VoNRState): Promise;
+
+```
+
+After change:
+
+```js
+function setVoNRState(slotId: number, state: VoNRState, callback: AsyncCallback): void;
+function setVoNRState(slotId: number, state: VoNRState): Promise;
+```
+
+**Adaptation Guide**
+
+Set the callback value to **void** when calling **setVoNState**. The sample code is as follows:
+
+```js
+call.setVoNRState( 0, VONR_STATE_ON, (err) => {
+ if (err) {
+ console.log(`callback: err->${JSON.stringify(err)}`);
+ }
+
+});
+call.setVoNRState( 0, VONR_STATE_OFF, (err) => {
+ console.log(`callback: err->${JSON.stringify(err)}`);
+});
+```
diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkcompiler.md b/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkcompiler.md
index a0d37340a474ee713030ae1177a4b9af4bc47a63..fa2c1a8f208e4a107201ccb4e6eb69a79d10f154 100644
--- a/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkcompiler.md
+++ b/en/release-notes/changelogs/OpenHarmony_4.0.8.1/changelogs-arkcompiler.md
@@ -1,23 +1,30 @@
# ArkCompiler Subsystem Changelog
-## cl.ArkCompiler.1 type compileMode uses es2abc by default
+## cl.ArkCompiler.1 Change of Default Compiler to es2abc in Type Compilation
-The composition of ArkCompiler in sdk has ts2abc compiler and es2abc compiler, supporting compilation of ets/ts/js files.
-Compilation Mode Introduction:
- Non-type compilation: convert ets/ts sourceCode into js sourceCode, and use ArkCompiler compiler es2abc to generate bytecode.
- type compilation: convert ets/ts sourceCode into ts sourceCode, and use ArkCompiler compiler ts2abc (previous version)/es2abc (enabled in this version) to generate bytecode.
-Application Project hvigor version:
- hvigorVersion field and @ohos/hvigor-ohos-plugin field in dependencies of hvigor-config.json5 file in the hvigor directory of the application project.
-Enable type compilation:
- When the hvigor version is greater than or equal to 2.6.0-rc.9.s, the type compilation mode is used by default, or in the build-profile.json5 file of the same level directory as the application sourceCode (src directory), configure the "aotCompileMode": "type" option under the buildOption tag
+In the SDK, ArkCompiler has two compilers that support ets/ts/js compilation: ts2abc compiler and es2abc compiler.
-When type compilation is enabled and this version of the SDK is used, the ArkCompiler compiler es2abc will be used by default to compile the ts sourceCode to generate bytecode, and it is not recommended to use the old version SDK with ts2abc enabled for type compilation.
+Introduction to compilation modes:
-**Change Impact**
-With DevEco Studio development, after the type compilation mode is enabled and the new version of the SDK is used, due to the change of the compilation mode and the change of the ArkCompiler compiler, application compilation failures and runtime crashes may occur.
+- Non-type compilation: converts ArkTS/TS source code into JS source code, and uses the ArkCompiler compiler es2abc to generate bytecode.
-**Key API/Component Changes**
-type compileMode uses arkcompiler frontend compiler es2abc by default
+- Type compilation: converts ArkTS/TS source code into TS source code, and uses the ArkCompiler compiler ts2abc (in earlier versions)/es2abc (enabled in this version) to generate bytecode.
+
+You can check the hvigor version of the application project in the following fields:
+**hvigorVersion** field and **@ohos/hvigor-ohos-plugin** field under **dependencies** in the **hvigor-config.json5** file in the **hvigor** directory of the application project
+
+Enable type compilation:
+
+If the hvigor version is 2.6.0-rc.9.s or later, the type compilation mode is enabled by default. You can also manually enable this mode by setting **aotCompileMode** to **type** under the **buildOption** tag in the **build-profile.json5** file at the same level directory as the application source code (**src** directory).
+
+When type compilation is enabled and the SDK of this version is used, the ArkCompiler compiler es2abc is used by default. The earlier version SDK with ts2abc enabled is not recommended for type compilation.
+
+**Change Impact**
+In DevEco Studio, when the type compilation mode is enabled and the SDK of this version is used, the change in the compilation mode and ArkCompiler compiler may result in application compilation failures and runtime crashes.
+
+**Key API/Component Changes**
+In type compilation mode, the ArkCompiler compiler es2abc is used by default.
**Adaptation Guide**
-1. When the hvigor version is greater than or equal to 2.6.0-rc.9.s, the developer needs to configure "aotCompileMode": "" in the build-profile.json5 file to switch to the original compilation mode (not type).
+
+If the hvigor version is 2.6.0-rc.9.s or later, to switch to the original compilation mode (non-type), you need to set **aotCompileMode** in the **build-profile.json5** file.
\ No newline at end of file
diff --git a/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-formfwk.md b/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-formfwk.md
new file mode 100644
index 0000000000000000000000000000000000000000..e5ed4eecd2e0d4e6c1f176d6bfa808c136a3889b
--- /dev/null
+++ b/en/release-notes/changelogs/OpenHarmony_4.0.9.5/changelogs-formfwk.md
@@ -0,0 +1,146 @@
+# formfwk Subsystem Changelog
+
+## cl.formfwk.1 Some APIs Moved from @ohos.app.form.formHost.d.ts and Their Permission Changed
+
+1. APIs used for listening for and obtaining dynamic widget information are moved from **@ohos.app.form.formHost.d.ts** to **@ohos.app.form.formObserver.d.ts**.
+
+2. The permission for these APIs is changed from **ohos.permission.REQUIRE_FORM** to **ohos.permission.OBSERVE_FORM_RUNNING**.
+
+**Change Impact**
+
+Applications that use the involved APIs may have compatibility issues.
+
+**Key API/Component Changes**
+
+| API | Home .d.ts File Before Modification| Home .d.ts File After Modification| Permission Required Before Modification| Permission Required After Modification|
+| -------- | -------- | -------- | -------- | -------- |
+| on('formAdd') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM|ohos.permission.OBSERVE_FORM_RUNNING|
+| off('formAdd')| @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM|ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| on('formRemove') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| off('formRemove') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| on('notifyVisible') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| off('notifyVisible') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| on('notifyInvisible') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| off('notifyInvisible') | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| getRunningFormInfos | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| getRunningFormInfosByFilter | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+| getRunningFormInfoById | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING | @ohos.app.form.formHost.d.ts | @ohos.app.form.formObserver.d.ts | ohos.permission.REQUIRE_FORM | ohos.permission.OBSERVE_FORM_RUNNING |
+
+**Adaptation Guide**
+
+Adapt your application code accordingly. To use these APIs in OpenHarmony 4.0.9.5 and later versions, import **@ohos.app.form.formObserver.d.ts** and request the **ohos.permission.OBSERVE_FORM_RUNNING** permission.
+
+**Example**
+
+```js
+import formObserver from @ohos.app.form.formObserver.d.ts;
+
+try {
+ formObserver.getRunningFormInfos((error, data) => {
+ if (error) {
+ console.error(`error, code: ${error.code}, message: ${error.message}`);
+ } else {
+ console.log('formHost getRunningFormInfos, data: ${JSON.stringify(data)}');
+ }
+ }, 'com.example.ohos.formjsdemo');
+} catch(error) {
+ console.error(`catch error, code: ${error.code}, message: ${error.message}`);
+}
+```
+
+
+## cl.formfwk.2 Adjusted the Parameter Sequence of Event Subscription and Unsubscription APIs (on/off)
+
+The **callback** parameter is moved as the last parameter in the event subscription and unsubscription APIs (**on**/**off**).
+
+**Change Impact**
+
+Applications that use the involved APIs may have compatibility issues.
+
+**Key API/Component Changes**
+
+Before change:
+
+```js
+function on(type: 'formAdd', observerCallback: Callback, bundleName?: string): void;
+function off(type: 'formAdd', observerCallback?: Callback, bundleName?: string): void;
+
+function on(type: 'formRemove', observerCallback: Callback, bundleName?: string): void;
+function off(type: 'formRemove', observerCallback?: Callback, bundleName?: string): void;
+
+function on(
+ type: 'notifyVisible',
+ observerCallback: Callback>,
+ hostBundleName?: string
+ ): void;
+function off(
+ type: 'notifyVisible',
+ observerCallback?: Callback>,
+ hostBundleName?: string
+ ): void;
+
+function on(
+ type: 'notifyInvisible',
+ observerCallback: Callback>,
+ hostBundleName?: string
+ ): void;
+function off(
+ type: 'notifyInvisible',
+ observerCallback?: Callback>,
+ hostBundleName?: string
+ ): void;
+```
+
+After change:
+
+```js
+function on(type: 'formAdd', observerCallback: Callback): void;
+function on(type: 'formAdd', hostBundleName: string, observerCallback: Callback): void;
+function off(type: 'formAdd', hostBundleName?: string, observerCallback?: Callback): void;
+
+function on(type: 'formRemove', observerCallback: Callback): void;
+function on(type: 'formRemove', hostBundleName: string, observerCallback: Callback): void;
+function off(type: 'formRemove', hostBundleName?: string, observerCallback?: Callback): void;
+
+function on(type: 'notifyVisible', observerCallback: Callback>): void;
+function on(
+ type: 'notifyVisible',
+ hostBundleName: string,
+ observerCallback: Callback>
+ ): void;
+function off(
+ type: 'notifyVisible',
+ hostBundleName?: string,
+ observerCallback?: Callback>
+ ): void;
+
+function on(type: 'notifyInvisible', observerCallback: Callback>): void;
+function on(
+ type: 'notifyInvisible',
+ hostBundleName: string,
+ observerCallback: Callback>,
+ ): void;
+function off(
+ type: 'notifyInvisible',
+ hostBundleName?: string,
+ observerCallback?: Callback>
+ ): void;
+```
+
+**Adaptation Guide**
+
+Adapt your application code accordingly. In OpenHarmony 4.0.9.5 and later versions, pass in **callback** as the last parameter when calling these APIs.
+
+**Example**
+
+```js
+import formObserver from @ohos.app.form.formObserver.d.ts;
+
+let bundleName = 'ohos.samples.FormApplication';
+let callback = function(data) {
+ console.log('a new form added, data: ${JSON.stringify(data)');
+}
+
+formHost.on('formAdd', callback);
+formHost.on('formAdd', bundleName, callback);
+```
diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-page-animation.md b/zh-cn/application-dev/application-models/arkts-ui-widget-page-animation.md
index 1cecd3aae69381ce4de7ed37411a177b83db899d..c8321d7165e9324aca8eb87b69085070f82fec53 100644
--- a/zh-cn/application-dev/application-models/arkts-ui-widget-page-animation.md
+++ b/zh-cn/application-dev/application-models/arkts-ui-widget-page-animation.md
@@ -21,22 +21,24 @@ ArkTS卡片开放了使用动画效果的能力,支持[显式动画](../refere
```ts
@Entry
@Component
-struct AttrAnimationExample {
+struct AnimationCard {
@State rotateAngle: number = 0;
build() {
- Column() {
+ Row() {
Button('change rotate angle')
+ .height('20%')
+ .width('90%')
+ .margin('5%')
.onClick(() => {
- this.rotateAngle = 90;
+ this.rotateAngle = (this.rotateAngle === 0 ? 90 : 0);
})
- .margin(50)
.rotate({ angle: this.rotateAngle })
.animation({
curve: Curve.EaseOut,
- playMode: PlayMode.AlternateReverse
+ playMode: PlayMode.Normal,
})
- }.width('100%').margin({ top: 20 })
+ }.height('100%').alignItems(VerticalAlign.Center)
}
}
```
diff --git a/zh-cn/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md b/zh-cn/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md
index b759f612959fe896f2dc1f8e25b74d13203ec24c..e69150e7ea9ad9d61a1a382ed1386d9e70ce2e5f 100644
--- a/zh-cn/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md
+++ b/zh-cn/application-dev/application-models/arkts-ui-widget-page-custom-drawing.md
@@ -6,7 +6,7 @@ ArkTS卡片开放了自定义绘制的能力,在卡片上可以通过[Canvas](
```ts
@Entry
@Component
-struct WidgetCard {
+struct CanvasCard {
private canvasWidth: number = 0;
private canvasHeight: number = 0;
// 初始化CanvasRenderingContext2D和RenderingContextSettings
diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png
new file mode 100644
index 0000000000000000000000000000000000000000..952218badc407b8bc2470fc1622ae0e607c4bcfb
Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration1.png differ
diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png
new file mode 100644
index 0000000000000000000000000000000000000000..a81cb2ab08506f4e368c6002be18d6931a056218
Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration2.png differ
diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png
new file mode 100644
index 0000000000000000000000000000000000000000..86158bc2bcd54b83e8dc73aec204788aab0b95a3
Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration3.png differ
diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png
new file mode 100644
index 0000000000000000000000000000000000000000..c743b3d10f8f1fa0a8be76cf10fff219c52d0ebf
Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration4.png differ
diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png
new file mode 100644
index 0000000000000000000000000000000000000000..854af7b632121a52c9e0364efb407b209dfb63bf
Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration5.png differ
diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png
new file mode 100644
index 0000000000000000000000000000000000000000..2d38c00bbb5d268b8072dac4b8bf22238bbe869b
Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration6.png differ
diff --git a/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png
new file mode 100644
index 0000000000000000000000000000000000000000..e789d748fe97d3c08bfaa6d22cf151bee31eccc9
Binary files /dev/null and b/zh-cn/application-dev/application-models/figures/hop-cross-device-migration7.png differ
diff --git a/zh-cn/application-dev/application-models/hop-cross-device-migration.md b/zh-cn/application-dev/application-models/hop-cross-device-migration.md
index fcc35ec4d4f36088ae25911afac9a23f89760862..84a034344f058c2ca415a028b817b1bd830525dc 100644
--- a/zh-cn/application-dev/application-models/hop-cross-device-migration.md
+++ b/zh-cn/application-dev/application-models/hop-cross-device-migration.md
@@ -1,21 +1,15 @@
# 跨端迁移
-
## 功能描述
跨端迁移的主要工作是实现将应用当前任务(包括页面控件状态变量等)迁移到目标设备,能在目标设备上接续。主要功能包括:
- 支持用户自定义数据存储及恢复。
-
- 支持页面路由信息和页面控件状态数据的存储及恢复。
-
- 支持应用兼容性检测。
-
-- 支持应用根据实际使用场景动态设置迁移状态(默认迁移状态为ACTIVE激活状态)。如编辑类应用在编辑文本的页面下才需要迁移,其他页面不需要迁移,则可以通过[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)进行控制。
-
+- 支持应用根据实际使用场景动态设置迁移状态(默认迁移状态为 **ACTIVE** 激活状态)。如编辑类应用在编辑文本的页面下才需要迁移,其他页面不需要迁移,则可以通过[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)进行控制。
- 支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如应用希望自定义迁移到其他设备后显示的页面,则可以通过[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。
-
-- 支持应用动态选择流转成功后是否退出迁移发起端应用(默认流转成功后退出迁移发起端应用)。则可以通过[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。
+- 支持应用动态选择迁移成功后是否退出迁移发起端应用(默认迁移成功后退出迁移发起端应用)。则可以通过[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)进行控制。
## 跨端迁移流程
@@ -28,14 +22,9 @@
## 约束限制
-- 由于“跨端迁移任务管理”能力尚未具备,开发者当前只能开发具备跨端迁移能力的应用,但不能发起迁移。
-
+- 应用迁移的发起依赖系统应用控制,系统应用开发者可以参考[验证指导中的demo示例](#验证指导)实现相关的控制能力。
- 跨端迁移要求在同UIAbility之间进行,也就是需要相同的bundleName、abilityName和签名。
-
-
-## 最佳实践
-
-为了获得最佳体验,使用wantParam传输的数据建议在100KB以下。
+- 为了获得最佳体验,使用wantParam传输的数据建议在100KB以下。
## 接口说明
@@ -46,22 +35,26 @@
| **接口名** | **描述** |
| -------- | -------- |
-| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | 迁移发起端在该回调中保存迁移所需要的数据,同时返回是否同意迁移:
- AGREE:表示同意。
- REJECT:表示拒绝:如应用在onContinue中异常可以直接REJECT。
- MISMATCH:表示版本不匹配:迁移发起端应用可以在onContinue中获取到迁移接收端应用的版本号,进行协商后,如果版本不匹配导致无法迁移,可以返回该错误。 |
-| onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 应用迁移接收端为冷启动或多实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) |
-| onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 迁移接收端为单实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) |
+| onContinue(wantParam : {[key: string]: Object}): OnContinueResult | 迁移发起端在该回调中保存迁移所需要的数据,同时返回是否同意迁移:
- AGREE:表示同意。
- REJECT:表示拒绝:如应用在onContinue中异常会导致钱以后数据恢复时显示异常,则可以建议REJECT。
- MISMATCH:表示版本不匹配:迁移发起端应用可以在onContinue中获取到迁移目标端应用的版本号,进行协商后,如果版本不匹配导致无法迁移,可以返回该错误。 |
+| onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 应用迁移目标端为冷启动或多实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) |
+| onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; | 迁移目标端为单实例应用热启动时,在该回调中完成数据恢复,并触发页面恢复。详见[应用组件启动模式](uiability-launch-type.md) |
## 开发步骤
-1. 需要申请`ohos.permission.DISTRIBUTED_DATASYNC`权限,配置方式请参见[配置文件权限声明](../security/accesstoken-guidelines.md#配置文件权限声明)。
+1.需要申请`ohos.permission.DISTRIBUTED_DATASYNC`权限
-2. 同时需要在应用首次启动时弹窗向用户申请授权,使用方式请参见[向用户申请授权](../security/accesstoken-guidelines.md#向用户申请授权)。
+配置方式请参见[配置文件权限声明](../security/accesstoken-guidelines.md#配置文件权限声明)。
-3. 在配置文件中配置跨端迁移相关标签字段。
+2.同时需要在应用首次启动时弹窗向用户申请授权
- 配置应用支持迁移
- 在module.json5中配置continuable标签:true表示支持迁移,false表示不支持,默认为false。配置为false的UIAbility将被系统识别为无法迁移。
+使用方式请参见[向用户申请授权](../security/accesstoken-guidelines.md#向用户申请授权)。
+
+3.在配置文件中配置跨端迁移相关标签字段。
+
+配置应用支持迁移
+在module.json5中配置continuable标签:true表示支持迁移,false表示不支持,默认为false。配置为false的UIAbility将被系统识别为无法迁移。
```json
@@ -80,131 +73,274 @@
根据需要配置应用启动模式类型,配置详情请参照[UIAbility组件启动模式](uiability-launch-type.md)。
-4. 在发起端UIAbility中实现[onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口。
- 当应用触发迁移时,[onContinue()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口在发起端被调用,开发者可以在该接口中保存迁移数据,实现应用兼容性检测,决定是否支持此次迁移。
- - 保存迁移数据:开发者可以将要迁移的数据通过键值对的方式保存在wantParam中。
+4.在发起端UIAbility中实现[onContinue](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口。
+
+当应用触发迁移时,[onContinue](../reference/apis/js-apis-app-ability-uiAbility.md#abilityoncontinue)接口在发起端被调用,开发者可以在该接口中保存迁移数据,实现应用兼容性检测,决定是否支持此次迁移。
+
+- 保存迁移数据:开发者可以将要迁移的数据通过键值对的方式保存在wantParam中。
+
+- 应用兼容性检测:开发者可以通过从wantParam中获取目标应用的版本号与本应用版本号做兼容性校验。开发者可以在触发迁移时从`onContinue`接口中`wantParam.version`获取到迁移目标端应用的版本号与迁移发起端应用版本号做兼容校验。
+
+- 迁移决策:开发者可以通过onContinue接口的返回值决定是否支持此次迁移,返回值信息见[接口说明](#接口说明)。
+
+ 示例如下:
+
+```ts
+import UIAbility from '@ohos.app.ability.UIAbility';
+import AbilityConstant from '@ohos.app.ability.AbilityConstant';
+
+onContinue(wantParam : {[key: string]: Object}) {
+ console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`) //准备迁移数据
+ let continueInput = '迁移的数据';
+ // 将要迁移的数据保存在wantParam的自定义字段(如:data)中;
+ wantParam["data"] = continueInput
+ console.info(`onContinue input = ${wantParam["input"]}`);
+ return AbilityConstant.OnContinueResult.AGREE
+}
+```
+
+5.在Stage模型中,应用在不同启动模式下将调用不同的接口,以恢复数据、加载界面。
+
+不同情况下的函数调用如下图所示:
+
+
+
+在目标端设备UIAbility中实现onCreate与onNewWant接口,恢复迁移数据。
+
+- onCreate实现示例
+ - 目标端设备上,在onCreate中根据launchReason判断该次启动是否为迁移LaunchReason.CONTINUATION。
+ - 开发者可以从want中获取保存的迁移数据。
+ - 完成数据恢复后,开发者需要调用restoreWindowStage来触发页面恢复:包括页面栈信息。
+
+ ```ts
+ import UIAbility from '@ohos.app.ability.UIAbility';
+ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
+
+ export default class EntryAbility extends UIAbility {
+ storage : LocalStorage;
+ onCreate(want, launchParam) {
+ console.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
+ if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
+ // 将上述的保存的数据取出恢复
+ let continueInput = want.parameters.data
+ console.info(`continue input ${continueInput}`)
+ // 将数据显示当前页面
+ this.storage = new LocalStorage();
+ this.context.restoreWindowStage(this.storage);
+ }
+ }
+ }
+ ```
+- 如果是单实例应用,需要额外实现onNewWant接口,实现方式与onCreate的实现相同。
+ - 在onNewWant中判断迁移场景,恢复数据,并触发页面恢复
+
+ ```ts
+ export default class EntryAbility extends UIAbility {
+ storage : LocalStorage;
+ onNewWant(want, launchParam) {
+ console.info(`EntryAbility onNewWant ${AbilityConstant.LaunchReason.CONTINUATION}`)
+ if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
+ // get user data from want params
+ let continueInput = want.parameters.data
+ console.info(`continue input ${continueInput}`)
+ this.storage = new LocalStorage();
+ this.context.restoreWindowStage(this.storage);
+ }
+ }
+ }
+ ```
+
+
+
+## 迁移功能可选配置
+
+### 1.动态配置迁移能力
+
+从API 10 起,提供了支持动态配置迁移能力的功能。即应用可以根据实际使用场景,在需要迁移功能时,设置开启应用迁移能力;在业务不需要迁移时,则可以关闭迁移能力。开发者可以通过调用[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)接口对迁移能力进行设置。默认状态下,可迁移应用的迁移能力为**ACTIVE**状态,即迁移能力开启,可以迁移。
+
+| 接口状态值 | 含义 |
+| :------------------------------------- | ---------------------- |
+| AbilityConstant.ContinueState.ACTIVE | 应用当前可迁移能力开启 |
+| AbilityConstant.ContinueState.INACTIVE | 应用当前可迁移能力关闭 |
+
+**设置迁移能力的时机**
+
+迁移能力的改变可以根据实际业务需求和代码实现,发生在应用生命周期的绝大多数时机。本文介绍常用的几种配置方式。
+
+在ability的onCreate函数中调用接口,可以在应用创建时设置应用的迁移状态。
+
+```ts
+// EntryAbility.ets
+onCreate(want, launchParam) {
+ ...
+ this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => {
+ console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result));
+ };
+ ...
+}
+```
+
+在页面的onPageShow函数中调用接口,可以设置单个页面出现时应用的迁移状态。
+
+```ts
+// PageName.ets
+struct PageName {
+ Build() {
+ ...
+ }
+ ...
+ onPageShow(){
+ // 进入该页面时,将应用设置为可迁移状态
+ this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => {
+ console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result));
+ };
+ }
+}
+```
+
+在某个组件的触发事件中设置应用迁移能力。如下例中,使用 **Button** 组件的 **onClick** 事件,触发迁移能力的改变。
+
+```ts
+// xxx.ets
+Button(){
+ ...
+}
+.onClick(()=>{
+ //点击该按钮时,将应用设置为可迁移状态
+ this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => {
+ console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result));
+ };
+})
+```
+
+**保证迁移连续性**
+
+由于迁移加载时,目标端拉起的应用可能执行过自己的迁移状态设置命令(如:冷启动时目标端在onCreate中设置了 **INACTIVE** ;热启动时对端已打开了不可迁移的页面,迁移状态为 **INACTIVE** 等情况)。为了保证迁移过后的应用依然具有可以迁移回发起端的能力,应在 onCreate和onNewWant的迁移调用判断中,将迁移状态设置为 **ACTIVE** 。
+
+```ts
+// EntryAbility.ets
+onCreate(want, launchparam) {
+ ...
+ // 调用原因为迁移时,设置状态为可迁移,应对冷启动情况
+ if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
+ this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => {
+ console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result));
+ };
+ }
+}
- - 应用兼容性检测:开发者可以通过从wantParam中获取目标应用的版本号与本应用版本号做兼容性校验。开发者可以在触发迁移时从`onContinue`接口中`wantParam.version`获取到迁移接收端应用的版本号与迁移发起端应用版本号做兼容校验。
+onNewWant(want, launchparam) {
+ ...
+ // 调用原因为迁移时,设置状态为可迁移,应对热启动情况
+ if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
+ this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => {
+ console.info('setMissionContinueState ACTIVE result: ', JSON.stringify(result));
+ };
+ }
+}
+```
- - 迁移决策:开发者可以通过onContinue接口的返回值决定是否支持此次迁移,返回值信息见[接口说明](#接口说明)。
- 示例如下:
- ```ts
- import UIAbility from '@ohos.app.ability.UIAbility';
- import AbilityConstant from '@ohos.app.ability.AbilityConstant';
+### 2.按需迁移页面栈
- onContinue(wantParam : {[key: string]: any}) {
- console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
- let workInput = AppStorage.Get('ContinueWork');
- // set user input data into want params
- wantParam["work"] = workInput // set user input data into want params
- console.info(`onContinue input = ${wantParam["input"]}`);
- return AbilityConstant.OnContinueResult.AGREE
- }
- ```
+支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如果应用不想使用系统默认恢复的页面栈,则可以设置不进行页面栈迁移,而需要在`onWindowStageRestore`设置迁移后进入的页面,参数定义见[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。
-5. 在目标端设备UIAbility中实现onCreate()与onNewWant()接口,恢复迁移数据。
- - onCreate实现示例
- - 目标端设备上,在onCreate中根据launchReason判断该次启动是否为迁移LaunchReason.CONTINUATION。
- - 开发者可以从want中获取保存的迁移数据。
- - 完成数据恢复后,开发者需要调用restoreWindowStage来触发页面恢复:包括页面栈信息。
-
- ```ts
- import UIAbility from '@ohos.app.ability.UIAbility';
- import AbilityConstant from '@ohos.app.ability.AbilityConstant';
- import distributedObject from '@ohos.data.distributedDataObject';
-
- export default class EntryAbility extends UIAbility {
- storage : LocalStorage;
- onCreate(want, launchParam) {
- console.info(`EntryAbility onCreate ${AbilityConstant.LaunchReason.CONTINUATION}`)
- if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
- // get user data from want params
- let workInput = want.parameters.work
- console.info(`work input ${workInput}`)
- AppStorage.SetOrCreate('ContinueWork', workInput)
- this.storage = new LocalStorage();
- this.context.restoreWindowStage(this.storage);
- }
- }
- }
- ```
- - 如果是单实例应用,需要额外实现onNewWant()接口,实现方式与onCreate()的实现相同。
- - 在onNewWant()中判断迁移场景,恢复数据,并触发页面恢复
-
- ```ts
- export default class EntryAbility extends UIAbility {
- storage : LocalStorage;
- onNewWant(want, launchParam) {
- console.info(`EntryAbility onNewWant ${AbilityConstant.LaunchReason.CONTINUATION}`)
- if (launchParam.launchReason == AbilityConstant.LaunchReason.CONTINUATION) {
- // get user data from want params
- let workInput = want.parameters.work
- console.info(`work input ${workInput}`)
- AppStorage.SetOrCreate('ContinueWork', workInput)
- this.storage = new LocalStorage();
- this.context.restoreWindowStage(this.storage);
- }
- }
- }
+应用在发起端的页面栈中存在Index和Second路由,而在目标端恢复时不需要按照发起端页面栈进行恢复,需要恢复到指定页面。
+
+- 示例:应用迁移不需要自动迁移页面栈信息
+
+ ```ts
+ import UIAbility from '@ohos.app.ability.UIAbility';
+ import wantConstant from '@ohos.app.ability.wantConstant';
+
+ onContinue(wantParam : {[key: string]: Object}) {
+ console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
+ wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false;
+ return AbilityConstant.OnContinueResult.AGREE;
+ }
+
+ onWindowStageRestore(windowStage) {
+ // 若不需要自动迁移页面栈信息,则需要在此处设置应用迁移后进入的页面
+ windowStage.setUIContent(this.contex, "pages/index", null);
+ }
+ ```
+
+### 3.按需退出
+
+支持应用动态选择迁移成功后是否退出迁移发起端应用(默认迁移成功后退出迁移发起端应用)。如果应用不想让系统自动退出迁移发起端应用,则可以设置不退出,参数定义见[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。
+
+- 示例:应用迁移设置不需要迁移成功后退出迁移发起端应用
+
+ ```ts
+ import UIAbility from '@ohos.app.ability.UIAbility';
+ import wantConstant from '@ohos.app.ability.wantConstant';
+
+ onContinue(wantParam : {[key: string]: Object}) {
+ console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
+ wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false;
+ return AbilityConstant.OnContinueResult.AGREE;
+ }
+ ```
+
+## 验证指导
+
+为方便开发者验证已开发的可迁移应用,当前OpenHarmony提供了一个全局任务中心demo作为迁移的入口。下面介绍通过安装全局任务中心来验证迁移的方式。
+
+### 1. 编译安装全局任务中心
+
+#### **配置环境**
+
+public-SDK不支持开发者使用所有的系统API,例如:全局任务中心使用的[**@ohos.distributedDeviceManager**](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/reference/apis/js-apis-distributedDeviceManager.md)不包括在public_SDK中。因此为了正确编译安装全局任务中心,开发者需要替换full-SDK,具体操作可参见[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/faqs/full-sdk-switch-guide.md)。
+
+**说明**:本文中的截图仅为参考,具体的显示界面请以实际使用的DevEco Studio和SDK的版本为准。
+
+#### **下载MissionCenter_Demo[示例代码](https://gitee.com/openharmony/ability_dmsfwk/tree/master/services/dtbschedmgr/test/missionCenterDemo/dmsDemo/entry/src/main)**
+
+#### **编译工程文件**
+
+**新建OpenHarmony 空的工程,找到对应的文件夹替换下载文件**
+
+
+
+**自动签名,编译安装。**
+
+ DevEco的自动签名模板默认签名权限为normal级。而本应用设计到ohos.permission.MANAGE_MISSIONS权限为system_core级别。自动生成的签名无法获得足够的权限,所以需要将权限升级为system_core级别,然后签名。
+
+**系统权限设置**(以api10目录为例): 将Sdk目录下的openharmony\api版本(如:10)\toolchains\lib\UnsgnedReleasedProfileTemplate.json文件中的"apl":"normal_core"改为"apl":"system_core"。
+
+①点击file->Project Structrue
+
+
+
+②点击Signing Configs 点击OK
-6. **可选配置:** 在应用支持迁移特性时,默认开启应用迁移状态开关,根据应用当前任务获取焦点/失去焦点通知周边的可信设备当前任务可流转/取消流转。若应用需要在特定场景下才通知周边设备可流转,则需要在应用打开时设置迁移状态为INACTIVE,在后续的业务流程中需要迁移时再设置迁移状态为ACTIVE。接口见[setMissionContinueState](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextsetmissioncontinuestate10)。
+
- - 示例:应用启动不需要流转
+③连接开发板运行生成demo。
- ```ts
- import UIAbility from '@ohos.app.ability.UIAbility';
- import AbilityConstant from '@ohos.app.ability.AbilityConstant';
+### 2.设备组网
- onCreate(want, launchParam) {
- this.context.setMissionContinueState(AbilityConstant.ContinueState.INACTIVE, (result) => {
- console.info(`setMissionContinueState: ${JSON.stringify(result)}`);
- });
- }
- ```
- - 示例:应用在后续的业务流程中需要流转了
+①打开A,B两设备的计算器
- ```ts
- import UIAbility from '@ohos.app.ability.UIAbility';
- import AbilityConstant from '@ohos.app.ability.AbilityConstant';
+②点击右上角箭头选择B设备
- this.context.setMissionContinueState(AbilityConstant.ContinueState.ACTIVE, (result) => {
- console.info(`setMissionContinueState: ${JSON.stringify(result)}`);
- });
- ```
+③在B设备选择信任设备,弹出PIN码
-7. **可选配置:** 支持应用动态选择是否进行页面栈恢复(默认进行页面栈信息恢复)。如果应用不想使用系统默认恢复的页面栈,则可以设置不进行页面栈迁移,而需要在`onWindowStageRestore`设置流转后进入的页面,参数定义见[SUPPORT_CONTINUE_PAGE_STACK_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。
+④在A设备输入PIN码
- - 示例:应用迁移不需要自动流转页面栈信息
+⑤已组网成功,验证方法:在A设备输入数字,B设备同步出现则证明组网成功
- ```ts
- import UIAbility from '@ohos.app.ability.UIAbility';
- import wantConstant from '@ohos.app.ability.wantConstant.d.ts';
+### 3.发起迁移
- onContinue(wantParam : {[key: string]: any}) {
- console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
- wantParam[wantConstant.Params.SUPPORT_CONTINUE_PAGE_STACK_KEY] = false;
- return AbilityConstant.OnContinueResult.AGREE;
- }
+1.在B设备打开多设备协同权限的应用,A设备打开全局任务中心demo,A设备出现A设备名称(即:本机:OpenHarmony 3.2)和B设备名称(OpenHarmony 3.2)。
- onWindowStageRestore(windowStage) {
- // 若不需要自动流转页面栈信息,则需要在此处设置应用流转后进入的页面
- windowStage.setUIContent(this.contex, "pages/index", null);
- }
- ```
+
-8. **可选配置:** 支持应用动态选择迁移成功后是否退出迁移发起端应用(默认流转成功后退出迁移发起端应用)。如果应用不想让系统自动退出迁移发起端应用,则可以设置不退出,参数定义见参数定义见[SUPPORT_CONTINUE_SOURCE_EXIT_KEY](../reference/apis/js-apis-app-ability-wantConstant.md#wantconstantparams)。
+2.点击B设备名称,然后出现B设备的应用。
- - 示例:应用迁移设置不需要迁移成功后退出迁移发起端应用
+
- ```ts
- import UIAbility from '@ohos.app.ability.UIAbility';
- import wantConstant from '@ohos.app.ability.wantConstant.d.ts';
+3.最后将应用拖拽到A设备名称处,A设备应用被拉起,B设备应用退出。
- onContinue(wantParam : {[key: string]: any}) {
- console.info(`onContinue version = ${wantParam.version}, targetDevice: ${wantParam.targetDevice}`)
- wantParam[wantConstant.Params.SUPPORT_CONTINUE_SOURCE_EXIT_KEY] = false;
- return AbilityConstant.OnContinueResult.AGREE;
- }
- ```
\ No newline at end of file
+
diff --git a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md
index cf099d3fcbd12db99b15ec9c2786ace76863d651..29146ab27c0535591cb1c368e818725e7afb0001 100644
--- a/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md
+++ b/zh-cn/application-dev/application-models/hop-multi-device-collaboration.md
@@ -1,4 +1,4 @@
-# 多端协同(仅对系统应用开放)
+# 多端协同
## 功能描述
@@ -56,29 +56,31 @@
3. 获取目标设备的设备ID。
```ts
- import deviceManager from '@ohos.distributedHardware.deviceManager';
+ import deviceManager from '@ohos.distributedDeviceManager';
- let dmClass;
+ let dmClass: deviceManager.DeviceManager;
function initDmClass() {
// 其中createDeviceManager接口为系统API
- deviceManager.createDeviceManager('ohos.samples.demo', (err, dm) => {
- if (err) {
- ...
- return
- }
- dmClass = dm
- })
+ try{
+ dmClass = deviceManager.createDeviceManager('ohos.samples.demo');
+ } catch(err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+ }
}
function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass !== null) {
- let list = dmClass.getTrustedDeviceListSync()
+ let list = dmClass.getAvailableDeviceListSync();
if (typeof (list) === 'undefined' || typeof (list.length) === 'undefined') {
- console.info('EntryAbility onButtonClick getRemoteDeviceId err: list is null')
+ console.info('getRemoteDeviceId err: list is null');
+ return;
+ }
+ if (list.length === 0) {
+ console.info("getRemoteDeviceId err: list is empty");
return;
}
- return list[0].deviceId
+ return list[0].networkId;
} else {
- console.info('EntryAbility onButtonClick getRemoteDeviceId err: dmClass is null')
+ console.info('getRemoteDeviceId err: dmClass is null');
}
}
```
@@ -89,8 +91,8 @@
let want = {
deviceId: getRemoteDeviceId(),
bundleName: 'com.example.myapplication',
- abilityName: 'FuncAbility',
- moduleName: 'module1', // moduleName非必选
+ abilityName: 'EntryAbility',
+ moduleName: 'entry', // moduleName非必选
}
// context为发起端UIAbility的AbilityContext
this.context.startAbility(want).then(() => {
@@ -100,7 +102,7 @@
})
```
-5. 当设备A发起端应用不需要设备B上的ServiceExtensionAbility时,可调用stopServiceExtensionAbility(../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstopserviceextensionability)接口退出。(该接口不支持UIAbility的退出,UIAbility由用户手动通过任务管理退出)
+5. 当设备A发起端应用不需要设备B上的ServiceExtensionAbility时,可调用[stopServiceExtensionAbility](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstopserviceextensionability)接口退出。(该接口不支持UIAbility的退出,UIAbility由用户手动通过任务管理退出)
```ts
let want = {
@@ -216,7 +218,7 @@
2. 同时需要在应用首次启动时弹窗向用户申请授权,使用方式请参见[向用户申请授权](../security/accesstoken-guidelines.md#向用户申请授权)。
-3. 如果已有后台服务,请直接进入下一步;如果没有,则[实现一个后台服务](serviceextensionability.md#实现一个后台服务仅对系统应用开放)。
+3. 如果已有后台服务,请直接进入下一步;如果没有,则[实现一个后台服务](serviceextensionability.md#实现一个后台服务(仅对系统应用开放))。
4. 连接一个后台服务。
- 实现IAbilityConnection接口。IAbilityConnection提供了以下方法供开发者实现:onConnect()是用来处理连接Service成功的回调,onDisconnect()是用来处理Service异常终止的回调,onFailed()是用来处理连接Service失败的回调。
@@ -471,8 +473,8 @@
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg';
- originMsg: string = '';
- backMsg: string = '';
+ let originMsg: string = '';
+ let backMsg: string = '';
async onButtonCallWithResult(originMsg, backMsg) {
try {
let msg = new MyParcelable(1, originMsg);
diff --git a/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md b/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md
index 94f2d55e2a39282e55ec353192854301107c02ad..e98c34bbb7523ebfdeee168607a29c9298a902b1 100644
--- a/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md
+++ b/zh-cn/application-dev/application-models/inter-device-interaction-hop-overview.md
@@ -12,7 +12,7 @@
- **流转**
- 在OpenHarmony中泛指跨多设备的分布式操作。流转能力打破设备界限,多设备联动,使用户应用程序可分可合、可流转,实现如邮件跨设备编辑、多设备协同健身、多屏游戏等分布式业务。流转为开发者提供更广的使用场景和更新的产品视角,强化产品优势,实现体验升级。流转按照使用场景可分为**跨端迁移**和**多端协同**。
+ 在OpenHarmony中泛指跨多设备的分布式操作。流转能力打破设备界限,多设备联动,使用户应用程序可分可合、可流转,实现如跨设备编辑邮件、多设备协同健身、多屏游戏等分布式业务。流转为开发者提供更广的使用场景和更新的产品视角,强化产品优势,实现体验升级。流转按照使用场景可分为**跨端迁移**和**多端协同**。
- **跨端迁移**
@@ -20,12 +20,15 @@
- **多端协同**
- 用户拥有的多个设备,可以作为一个整体,为用户提供比单设备更加高效、沉浸的体验,这就是多端协同场景。常见的多端协同场景实例:场景一:两台设备A和B打开备忘录同一篇笔记进行双端协同编辑,在设备A上可以使用本地图库中的图片资源插入编辑,设备B上进行文字内容编辑。场景二:设备A上正在和客户进行聊天,客户需要的资料在设备B上,可以通过聊天软件打开设备B上的文档应用选择到想要的资料回传到设备A上,然后通过聊天软件发送给客户。在应用开发层面,多端协同指多端上的不同UIAbility/ServiceExtensionAbility同时运行、或者交替运行实现完整的业务;或者多端上的相同UIAbility/ServiceExtensionAbility同时运行实现完整的业务。
+ 用户拥有的多个设备,可以作为一个整体,为用户提供比单设备更加高效、沉浸的体验,这就是多端协同场景。常见的多端协同场景实例:
+
+ - 场景一:两台设备A和B打开备忘录同一篇笔记进行双端协同编辑,在设备A上可以使用本地图库中的图片资源插入编辑,设备B上进行文字内容编辑。
+ - 场景二:设备A上正在和客户进行聊天,客户需要的资料在设备B上,可以通过聊天软件打开设备B上的文档应用选择到想要的资料回传到设备A上,然后通过聊天软件发送给客户。在应用开发层面,多端协同指多端上的不同UIAbility/ServiceExtensionAbility同时运行、或者交替运行实现完整的业务;或者多端上的相同UIAbility/ServiceExtensionAbility同时运行实现完整的业务。
## 流转架构
-OpenHarmony流转提供了一组API库,可让用户应用程序更轻松、快捷地完成流转体验。OpenHarmony流转架构有如下优势:
+OpenHarmony流转提供了可以流转的能力,可让用户应用程序更轻松、快捷地完成流转体验。OpenHarmony流转架构有如下优势:
- 支持远程服务调用等能力,可轻松设计业务。
@@ -39,9 +42,9 @@ OpenHarmony流转提供了一组API库,可让用户应用程序更轻松、快

-- 跨端迁移任务管理:在迁移发起端,接受用户迁移的意图,提供迁移流转入口,迁移结果显示等能力。(该能力尚未构建。)
+- 跨端迁移任务管理:在迁移发起端,接受用户迁移的意图,提供迁移流转入口,迁移结果显示等能力。
-- 多端协同任务管理:在协同发起端,接受用户应用程序注册,提供协同入口、状态显示、退出流转等管理能力。(该能力尚未构建。)
+- 多端协同任务管理:在协同发起端,接受用户应用程序注册,提供协同入口、状态显示、退出流转等管理能力。
- 分布式组件管理服务:提供远程服务启动、远程服务连接、远程迁移等能力,并通过不同能力组合,支撑用户应用程序完成跨端迁移或多端协同的业务体验。
diff --git a/zh-cn/application-dev/application-models/service-widget-overview.md b/zh-cn/application-dev/application-models/service-widget-overview.md
index f6c0368123f7994fe5205e875ddae6bd21da0192..943569f9b56cfbf5a459d5abe69af04cfd874754 100644
--- a/zh-cn/application-dev/application-models/service-widget-overview.md
+++ b/zh-cn/application-dev/application-models/service-widget-overview.md
@@ -58,6 +58,10 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上
## 相关实例
+此文档中示例代码均有完整示例工程对应,具体对应关系如下:
+
+- [ArkTS卡片开发指导 - 开发卡片页面](https://gitee.com/openharmony/applications_app_samples/tree/master/code/DocsSample/Form/ArkTSCardDocsSample)
+
针对Stage模型卡片提供方的开发,有以下相关实例可供参考:
- [ArkTS音乐卡片(ArkTS)(Full SDK)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/MusicControl)
@@ -69,3 +73,4 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上
- [ArkTS卡片Canvas小游戏(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/CanvasGame)
- [ArkTS卡片计算器(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/Calculator)
+
diff --git a/zh-cn/application-dev/application-test/arkxtest-guidelines.md b/zh-cn/application-dev/application-test/arkxtest-guidelines.md
index 29e2464dba9a5d09793be810c45b576aa1ca7699..d5aedd5640d18520cab208be7402a1a581e24c0f 100644
--- a/zh-cn/application-dev/application-test/arkxtest-guidelines.md
+++ b/zh-cn/application-dev/application-test/arkxtest-guidelines.md
@@ -71,33 +71,34 @@ DevEco Studio可参考其官网介绍进行[下载](https://developer.harmonyos.
如下示例代码实现的场景是:启动测试页面,检查设备当前显示的页面是否为预期页面。
-```TS
-import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
+```js
+import { describe, it, expect } from '@ohos/hypium';
import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
+import { BusinessError } from '@ohos.base';
+import UIAbility from '@ohos.app.ability.UIAbility';
const delegator = abilityDelegatorRegistry.getAbilityDelegator()
+function sleep(time: number) {
+ return new Promise((resolve: Function) => setTimeout(resolve, time));
+}
export default function abilityTest() {
- describe('ActsAbilityTest', function () {
- it('testUiExample',0, async function (done) {
+ describe('ActsAbilityTest', () =>{
+ it('testUiExample',0, async (done: Function) => {
console.info("uitest: TestUiExample begin");
//start tested ability
- await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{
+ await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then((result: abilityDelegatorRegistry.ShellCmdResult) =>{
console.info('Uitest, start ability finished:' + result)
- }).catch(err => {
+ }).catch((err: BusinessError) => {
console.info('Uitest, start ability failed: ' + err)
})
await sleep(1000);
//check top display ability
- await delegator.getCurrentTopAbility().then((Ability)=>{
+ await delegator.getCurrentTopAbility().then((Ability: UIAbility)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
})
done();
})
-
- function sleep(time) {
- return new Promise((resolve) => setTimeout(resolve, time));
- }
})
}
```
@@ -109,34 +110,44 @@ export default function abilityTest() {
1.增加依赖导包。
```js
-import {Driver,ON,Component,MatchPattern} from '@ohos.uitest'
+import { Driver, ON } from '@ohos.UiTest'
```
2.编写具体测试代码。
```js
+import { describe, it, expect } from '@ohos/hypium';
+import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
+import { Driver, ON } from '@ohos.UiTest'
+import { BusinessError } from '@ohos.base';
+import UIAbility from '@ohos.app.ability.UIAbility';
+
+const delegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator()
+function sleep(time: number) {
+ return new Promise((resolve: Function) => setTimeout(resolve, time));
+}
export default function abilityTest() {
- describe('ActsAbilityTest', function () {
- it('testUiExample',0, async function (done) {
+ describe('ActsAbilityTest', () => {
+ it('testUiExample',0, async (done: Function) => {
console.info("uitest: TestUiExample begin");
//start tested ability
- await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{
+ await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then((result: abilityDelegatorRegistry.ShellCmdResult) =>{
console.info('Uitest, start ability finished:' + result)
- }).catch(err => {
+ }).catch((err: BusinessError) => {
console.info('Uitest, start ability failed: ' + err)
})
await sleep(1000);
//check top display ability
- await delegator.getCurrentTopAbility().then((Ability)=>{
+ await delegator.getCurrentTopAbility().then((Ability: UIAbility)=>{
console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
})
//ui test code
//init driver
- var driver = await Driver.create();
+ let driver = await Driver.create();
await driver.delayMs(1000);
//find button on text 'Next'
- var button = await driver.findComponent(ON.text('Next'));
+ let button = await driver.findComponent(ON.text('Next'));
//click button
await button.click();
await driver.delayMs(1000);
@@ -145,10 +156,6 @@ export default function abilityTest() {
await driver.pressBack();
done();
})
-
- function sleep(time) {
- return new Promise((resolve) => setTimeout(resolve, time));
- }
})
}
```
diff --git a/zh-cn/application-dev/database/data-sync-of-rdb-store.md b/zh-cn/application-dev/database/data-sync-of-rdb-store.md
index 9f8030ff400296a9551cd000f41894c644d89787..6a9a67714174a2ffecd4927fcd09bcdfeb1e4363 100644
--- a/zh-cn/application-dev/database/data-sync-of-rdb-store.md
+++ b/zh-cn/application-dev/database/data-sync-of-rdb-store.md
@@ -44,8 +44,6 @@
- 单个数据库最多支持注册8个订阅数据变化的回调。
-- 不支持非系统应用调用需要指定设备的分布式能力接口。
-
## 接口说明
@@ -142,34 +140,35 @@
> **说明:**
>
- > deviceIds通过调用[devManager.getTrustedDeviceListSync](../reference/apis/js-apis-device-manager.md#gettrusteddevicelistsync)方法得到,deviceManager模块的接口均为系统接口,仅系统应用可用。
+ > deviceIds通过调用[deviceManager.getAvailableDeviceListSync](../reference/apis/js-apis-distributedDeviceManager.md#getavailabledevicelistsync)方法得到。
```js
// 获取deviceIds
- import deviceManager from '@ohos.distributedHardware.deviceManager';
-
- deviceManager.createDeviceManager("com.example.appdatamgrverify", (err, manager) => {
- if (err) {
- console.info(`Failed to create device manager. Code:${err.code},message:${err.message}`);
- return;
- }
- let devices = manager.getTrustedDeviceListSync();
- let deviceId = devices[0].deviceId;
-
- // 构造用于查询分布式表的谓词对象
- let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
- // 调用跨设备查询接口,并返回查询结果
- store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'],
- function (err, resultSet) {
- if (err) {
- console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`);
- return;
- }
- console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
+ import deviceManager from '@ohos.distributedDeviceManager';
+ let dmInstance = null;
+ let deviceId = null;
+
+ try {
+ dmInstance = deviceManager.createDeviceManager("com.example.appdatamgrverify");
+ let devices = dmInstance.getAvailableDeviceListSync();
+ deviceId = devices[0].networkId;
+
+ // 构造用于查询分布式表的谓词对象
+ let predicates = new relationalStore.RdbPredicates('EMPLOYEE');
+ // 调用跨设备查询接口,并返回查询结果
+ store.remoteQuery(deviceId, 'EMPLOYEE', predicates, ['ID', 'NAME', 'AGE', 'SALARY', 'CODES'],
+ function (err, resultSet) {
+ if (err) {
+ console.error(`Failed to remoteQuery data. Code:${err.code},message:${err.message}`);
+ return;
}
- )
- })
+ console.info(`ResultSet column names: ${resultSet.columnNames}, column count: ${resultSet.columnCount}`);
+ }
+ )
+ } catch (err) {
+ console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message);
+ }
```
## 相关实例
diff --git a/zh-cn/application-dev/database/share-data-by-datashareextensionability.md b/zh-cn/application-dev/database/share-data-by-datashareextensionability.md
index 831902663ef160655c5bb85b804fde2b62e0e77e..bda623ca8a2e402873f7727414d82128817b22e8 100644
--- a/zh-cn/application-dev/database/share-data-by-datashareextensionability.md
+++ b/zh-cn/application-dev/database/share-data-by-datashareextensionability.md
@@ -64,6 +64,8 @@
import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.relationalStore';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+ import relationalStore from '@ohos.data.relationalStore';
+ import Want from '@ohos.app.ability.Want';
```
4. 数据提供方的业务实现由开发者自定义。例如可以通过数据库、读写文件或访问网络等各方式实现数据提供方的数据存储。
@@ -75,20 +77,20 @@
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)';
- let rdbStore;
- let result;
+ let rdbStore: relationalStore.RdbStore;
+ let result: string;
export default class DataShareExtAbility extends Extension {
- private rdbStore_;
+ private rdbStore_: relationalStore.RdbStore;
// 重写onCreate接口
- onCreate(want, callback) {
+ onCreate(want: Want, callback: Function) {
result = this.context.cacheDir + '/datashare.txt';
// 业务实现使用RDB
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
- }, function (err, data) {
+ }, (err, data) => {
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => {
console.info(`DataShareExtAbility onCreate, executeSql done err:${err}`);
@@ -100,7 +102,7 @@
}
// 重写query接口
- query(uri, predicates, columns, callback) {
+ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) {
if (predicates === null || predicates === undefined) {
console.info('invalid predicates');
}
@@ -188,6 +190,8 @@
import UIAbility from '@ohos.app.ability.UIAbility';
import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates';
+ import { ValuesBucket } from '@ohos.data.ValuesBucket'
+ import window from '@ohos.window';
```
2. 定义与数据提供方通信的URI字符串。
@@ -200,11 +204,11 @@
3. 创建工具接口类对象。
```js
- let dsHelper;
- let abilityContext;
+ let dsHelper: dataShare.DataShareHelper;
+ let abilityContext: Context;
export default class EntryAbility extends UIAbility {
- onWindowStageCreate(windowStage) {
+ onWindowStageCreate(windowStage: window.WindowStage) {
abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err, data) => {
dsHelper = data;
@@ -217,8 +221,19 @@
```js
// 构建一条数据
- let valuesBucket = { 'name': 'ZhangSan', 'age': 21, 'isStudent': false, 'Binary': new Uint8Array([1, 2, 3]) };
- let updateBucket = { 'name': 'LiSi', 'age': 18, 'isStudent': true, 'Binary': new Uint8Array([1, 2, 3]) };
+ let key1 = 'name';
+ let key2 = 'age';
+ let key3 = 'isStudent';
+ let key4 = 'Binary';
+ let valueName1 = 'ZhangSan';
+ let valueName2 = 'LiSi';
+ let valueAge1 = 21;
+ let valueAge2 = 18;
+ let valueIsStudent1 = false;
+ let valueIsStudent2 = true;
+ let valueBinary = new Uint8Array([1, 2, 3]);
+ let valuesBucket: ValuesBucket = { key1: valueName1, key2: valueAge1, key3: valueIsStudent1, key4: valueBinary };
+ let updateBucket: ValuesBucket = { key1: valueName2, key2: valueAge2, key3: valueIsStudent2, key4: valueBinary };
let predicates = new dataSharePredicates.DataSharePredicates();
let valArray = ['*'];
// 插入一条数据
diff --git a/zh-cn/application-dev/database/unified-data-channels.md b/zh-cn/application-dev/database/unified-data-channels.md
index a8877b4abeb2857af04e57527d76b5aa2f0f9cec..3d4b0574e6cb0e274683ee5a50fb7356f5d8807b 100644
--- a/zh-cn/application-dev/database/unified-data-channels.md
+++ b/zh-cn/application-dev/database/unified-data-channels.md
@@ -29,7 +29,7 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化
## 接口说明
-以下是UDMF标准化数据通路的相关接口,均为异步接口。异步接口均有callback和Promise两种返回形式,下表均以callback形式为例,更多接口及使用方式请见[统一数据管理框架](../reference/apis/js-apis-data-udmf.md)。
+以下是UDMF标准化数据通路的相关接口,均为异步接口。异步接口均有callback和Promise两种返回形式,下表均以callback形式为例,更多接口及使用方式请见[标准化数据通路](../reference/apis/js-apis-data-unifiedDataChannel.md)和[标准化数据定义与描述](../reference/apis/js-apis-data-uniformTypeDescriptor.md)。
| 接口名称 | 描述 |
|-----------------------------------------------------------------------------------------|---------------------------------------------|
@@ -45,24 +45,25 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化
### 数据提供方
-1. 导入`@ohos.data.UDMF`模块。
+1. 导入`@ohos.data.unifiedDataChannel`和`@ohos.data.uniformTypeDescriptor`模块。
```ts
- import UDMF from '@ohos.data.UDMF';
+ import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+ import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
```
2. 创建一个统一数据对象并插入到UDMF的公共数据通路中。
```ts
- let plainText = new UDMF.PlainText();
+ let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'hello world!';
- let unifiedData = new UDMF.UnifiedData(plainText);
+ let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
// 指定要插入数据的数据通路枚举类型
let options = {
- intention: UDMF.Intention.DATA_HUB
+ intention: unifiedDataChannel.Intention.DATA_HUB
}
try {
- UDMF.insertData(options, unifiedData, (err, data) => {
+ unifiedDataChannel.insertData(options, unifiedData, (err, data) => {
if (err === undefined) {
console.info(`Succeeded in inserting data. key = ${data}`);
} else {
@@ -76,9 +77,9 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化
3. 更新上一步骤插入的统一数据对象。
```ts
- let plainText = new UDMF.PlainText();
+ let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'How are you!';
- let unifiedData = new UDMF.UnifiedData(plainText);
+ let unifiedData = new unifiedDataChannel.UnifiedData(plainText);
// 指定要更新的统一数据对象的URI
let options = {
@@ -86,7 +87,7 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化
};
try {
- UDMF.updateData(options, unifiedData, (err) => {
+ unifiedDataChannel.updateData(options, unifiedData, (err) => {
if (err === undefined) {
console.info('Succeeded in updating data.');
} else {
@@ -102,18 +103,18 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化
```ts
// 指定要删除数据的数据通路枚举类型
let options = {
- intention: UDMF.Intention.DATA_HUB
+ intention: unifiedDataChannel.Intention.DATA_HUB
};
try {
- UDMF.deleteData(options, (err, data) => {
+ unifiedDataChannel.deleteData(options, (err, data) => {
if (err === undefined) {
console.info(`Succeeded in deleting data. size = ${data.length}`);
for (let i = 0; i < data.length; i++) {
let records = data[i].getRecords();
for (let j = 0; j < records.length; j++) {
- if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) {
- let text = (records[j]);
+ if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let text = (records[j]);
console.info(`${i + 1}.${text.textContent}`);
}
}
@@ -129,28 +130,29 @@ UDMF针对多对多跨应用数据共享的不同业务场景提供了标准化
### 数据访问方
-1. 导入`@ohos.data.UDMF`模块。
+1. 导入`@ohos.data.unifiedDataChannel`和`@ohos.data.uniformTypeDescriptor`模块。
```ts
- import UDMF from '@ohos.data.UDMF';
+ import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+ import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
```
2. 查询存储在UDMF公共数据通路中的统一数据对象。
```ts
// 指定要查询数据的数据通路枚举类型
let options = {
- intention: UDMF.Intention.DATA_HUB
+ intention: unifiedDataChannel.Intention.DATA_HUB
};
try {
- UDMF.queryData(options, (err, data) => {
+ unifiedDataChannel.queryData(options, (err, data) => {
if (err === undefined) {
console.info(`Succeeded in querying data. size = ${data.length}`);
for (let i = 0; i < data.length; i++) {
let records = data[i].getRecords();
for (let j = 0; j < records.length; j++) {
- if (records[j].getType() === UDMF.UnifiedDataType.PLAIN_TEXT) {
- let text = (records[j]);
+ if (records[j].getType() === uniformTypeDescriptor.UniformDataType.PLAIN_TEXT) {
+ let text = (records[j]);
console.info(`${i + 1}.${text.textContent}`);
}
}
diff --git a/zh-cn/application-dev/database/unified-data-definition.md b/zh-cn/application-dev/database/unified-data-definition.md
index 154982e55bf74fda7cdfe889de58c78cea3b0352..8db772d70c636d25d01a12e80d13af377cac9d77 100644
--- a/zh-cn/application-dev/database/unified-data-definition.md
+++ b/zh-cn/application-dev/database/unified-data-definition.md
@@ -5,6 +5,7 @@
为了构建OpenHarmony数据跨应用交互的标准定义,降低应用/业务数据交互成本,促进数据生态建设,UDMF提供了标准化的数据定义,统一定义了多种常用的数据类型。应用可以使用统一数据管理框架提供的接口创建和使用这些标准化数据类型。
+例如跨应用拖拽场景,拖出方应用可以按照标准化数据定义将拖拽数据写入[拖拽事件](../reference/arkui-ts/ts-universal-events-drag-drop.md#dragevent说明),拖入方应用从拖拽事件中读取拖拽数据并按照标准化数据定义进行数据的解析。这使得不同应用间的数据交互遵从相同的标准定义,避免了穷举式的数据类型适配,有效减少了跨应用数据交互的开发工作量。
## 标准化数据类型
@@ -39,9 +40,9 @@ UDMF提供的标准化数据类型主要包括以下几类:
## 接口说明
-UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录UnifiedRecord。数据记录UnifiedRecord则是对UDMF支持的数据内容的抽象定义,例如一条文本记录、一条图片记录等。数据记录中的数据内容类型对应为各数据类型UnifiedDataType。
+UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录UnifiedRecord。数据记录UnifiedRecord则是对UDMF支持的数据内容的抽象定义,例如一条文本记录、一条图片记录等。数据记录中的数据内容类型对应为各数据类型UniformDataType。
-以下是常见的UDMF的接口说明,更多接口和具体说明,请见[统一数据管理框架](../reference/apis/js-apis-data-udmf.md)。
+以下是常见的UDMF的接口说明,更多接口和具体说明,请见[标准化数据通路](../reference/apis/js-apis-data-unifiedDataChannel.md)和[标准化数据定义与描述](../reference/apis/js-apis-data-uniformTypeDescriptor.md)。
| 类名称 | 接口名称 | 描述 |
|---------------|-------------------|-----------------------------------------------------------------------------------------------|
@@ -55,17 +56,18 @@ UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录Unifi
以一次创建统一数据对象(包含图片、纯文本两条数据记录)为例,说明开发步骤。
-1. 导入`@ohos.data.UDMF`模块。
+1. 导入`@ohos.data.unifiedDataChannel`和`@ohos.data.uniformTypeDescriptor`模块。
```ts
- import UDMF from '@ohos.data.UDMF';
+ import unifiedDataChannel from '@ohos.data.unifiedDataChannel';
+ import uniformTypeDescriptor from '@ohos.data.uniformTypeDescriptor';
```
2. 创建图片数据记录,并初始化得到带有该数据记录的UnifiedData对象。
(1)创建图片数据记录。
```ts
- let image = new UDMF.Image();
+ let image = new unifiedDataChannel.Image();
```
(2)修改对象属性。
@@ -84,12 +86,12 @@ UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录Unifi
(4)创建一个统一数据对象实例。
```ts
- let unifiedData = new UDMF.UnifiedData(image);
+ let unifiedData = new unifiedDataChannel.UnifiedData(image);
```
3. 创建纯文本数据类型记录,将其添加到刚才创建的UnifiedData对象。
```ts
- let plainText = new UDMF.PlainText();
+ let plainText = new unifiedDataChannel.PlainText();
plainText.textContent = 'this is textContent of plainText';
plainText.abstract = 'abstract of plainText';
plainText.details = {
@@ -110,13 +112,13 @@ UDMF提供了统一数据对象UnifiedData,用于封装一组数据记录Unifi
// 读取该数据记录的类型
let type = records[i].getType();
switch (type) {
- case UDMF.UnifiedDataType.IMAGE:
+ case uniformTypeDescriptor.UniformDataType.IMAGE:
// 转换得到原图片数据记录
- let image = (records[i]);
+ let image = (records[i]);
break;
- case UDMF.UnifiedDataType.PLAIN_TEXT:
+ case uniformTypeDescriptor.UniformDataType.PLAIN_TEXT:
// 转换得到原文本数据记录
- let plainText = (records[i]);
+ let plainText = (records[i]);
break;
default:
break;
diff --git a/zh-cn/application-dev/file-management/save-user-file.md b/zh-cn/application-dev/file-management/save-user-file.md
index 9818de82be9377a747e8ab2c063a01ba456ca0dc..ff52752af54a91a429b72449d96abacd912a472c 100644
--- a/zh-cn/application-dev/file-management/save-user-file.md
+++ b/zh-cn/application-dev/file-management/save-user-file.md
@@ -58,7 +58,7 @@ save接口会将文件保存在文件管理器,而不是图库。
save返回的uri权限是读写权限,可以根据结果集里面的uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。
```ts
- let uri:string;
+ let uris = null;
async photoViewPickerSave() {
try {
const photoSaveOptions = new picker.PhotoSaveOptions(); // 创建文件管理器保存选项实例
@@ -68,9 +68,8 @@ save接口会将文件保存在文件管理器,而不是图库。
try {
let photoSaveResult = await photoViewPicker.save(photoSaveOptions);
if (photoSaveResult != undefined) {
- console.info("[picker] photoViewPickerSave photoSaveResult = " + JSON.stringify(photoSaveResult));
- this.uri = photoSaveResult[0];
- console.info('photoViewPicker.save to file succeed and uri is:' + photoSaveResult[0]);
+ uris = photoSaveResult;
+ console.info('photoViewPicker.save to file succeed and uris are:' + uris);
}
} catch (err) {
console.error(`[picker] Invoke photoViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
@@ -112,6 +111,7 @@ save接口会将文件保存在文件管理器,而不是图库。
```ts
const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器选项实例
documentSaveOptions.newFileNames = ["DocumentViewPicker01.txt"]; // 保存文件名(可选)
+ documentSaveOptions.fileSuffixChoices = ['.png', '.txt', '.mp4']; // 保存文件类型(可选)
```
3. 创建文档选择器实例。调用[save()](../reference/apis/js-apis-file-picker.md#save-3)接口拉起FilePicker界面进行文件保存。用户选择目标文件夹,用户选择与文件类型相对应的文件夹,即可完成文件保存操作。保存成功后,返回保存文档的uri。
@@ -119,11 +119,11 @@ save接口会将文件保存在文件管理器,而不是图库。
save返回的uri权限是读写权限,可以根据结果集中uri进行文件读写等操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。
```ts
- let uri = null;
+ let uris = null;
const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例
documentViewPicker.save(documentSaveOptions).then((documentSaveResult) => {
- uri = documentSaveResult[0];
- console.info('documentViewPicker.save to file succeed and uri is:' + uri);
+ uris = documentSaveResult;
+ console.info('documentViewPicker.save to file succeed and uris are:' + uris);
}).catch((err) => {
console.error(`Invoke documentViewPicker.save failed, code is ${err.code}, message is ${err.message}`);
})
diff --git a/zh-cn/application-dev/file-management/select-user-file.md b/zh-cn/application-dev/file-management/select-user-file.md
index 7a850a82466a3fcb517ca9caf7fa2a04ab9876fb..8d8689edb49c72746e21c68b04d1970a244f46a2 100644
--- a/zh-cn/application-dev/file-management/select-user-file.md
+++ b/zh-cn/application-dev/file-management/select-user-file.md
@@ -38,11 +38,11 @@
select返回的uri权限是只读权限,可以根据结果集中uri进行读取文件数据操作。注意不能在picker的回调里直接使用此uri进行打开文件操作,需要定义一个全局变量保存uri,使用类似一个按钮去触发打开文件。
```ts
- let uri = null;
+ let uris = null;
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
- uri = photoSelectResult.photoUris[0];
- console.info('photoViewPicker.select to file succeed and uri is:' + uri);
+ uris = photoSelectResult.photoUris;
+ console.info('photoViewPicker.select to file succeed and uris are:' + uris);
}).catch((err) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
@@ -77,6 +77,9 @@
```ts
const documentSelectOptions = new picker.DocumentSelectOptions();
+ documentSelectOptions.maxSelectNumber = 5; // 选择文档的最大数目(可选)
+ documentSelectOptions.defaultFilePathUri = "file://docs/storage/Users/currentUser/test"; // 指定选择的文件或者目录路径(可选)
+ documentSelectOptions.fileSuffixFilters = ['.png', '.txt', '.mp4']; // 选择文件的后缀类型(可选)
```
3. 创建文档选择器实例。调用[select()](../reference/apis/js-apis-file-picker.md#select-3)接口拉起FilePicker界面进行文件选择。文件选择成功后,返回被选中文档的uri结果集。
@@ -85,16 +88,12 @@
例如通过[文件管理接口](../reference/apis/js-apis-file-fs.md)根据uri获取部分文件属性信息,比如文件大小、访问时间、修改时间等。如有获取文件名称需求,请暂时使用[startAbilityForResult](../../application-dev/application-models/uiability-intra-device-interaction.md)获取。
- > **说明:**
- >
- > 目前DocumentSelectOptions不支持参数配置,默认可以选择所有类型的用户文件。
-
```ts
- let uri = null;
+ let uris = null;
const documentViewPicker = new picker.DocumentViewPicker(); // 创建文件选择器实例
documentViewPicker.select(documentSelectOptions).then((documentSelectResult) => {
- uri = documentSelectResult[0];
- console.info('documentViewPicker.select to file succeed and uri is:' + uri);
+ uris = documentSelectResult;
+ console.info('documentViewPicker.select to file succeed and uris are:' + uris);
}).catch((err) => {
console.error(`Invoke documentViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
@@ -172,7 +171,7 @@
let uri = null;
const audioViewPicker = new picker.AudioViewPicker();
audioViewPicker.select(audioSelectOptions).then(audioSelectResult => {
- uri = audioSelectOptions[0];
+ uri = audioSelectResult[0];
console.info('audioViewPicker.select to file succeed and uri is:' + uri);
}).catch((err) => {
console.error(`Invoke audioViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
diff --git a/zh-cn/application-dev/media/using-avrecorder-for-recording.md b/zh-cn/application-dev/media/using-avrecorder-for-recording.md
index 98c9c4633eb25462ed4d8a6f09ab78a7b9883b4e..927c9e41f1add7583d63f14e0e41de41cfc135dc 100644
--- a/zh-cn/application-dev/media/using-avrecorder-for-recording.md
+++ b/zh-cn/application-dev/media/using-avrecorder-for-recording.md
@@ -20,11 +20,11 @@
```ts
import media from '@ohos.multimedia.media';
- let avRecorder = undefined;
- media.createAVRecorder().then((recorder) => {
+ let avRecorder: media.AVRecorder;
+ media.createAVRecorder().then((recorder: media.AVRecorder) => {
avRecorder = recorder;
- }, (err) => {
- console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`);
+ }, (error: Error) => {
+ console.error(`createAVRecorder failed`);
})
```
@@ -37,13 +37,13 @@
```ts
// 状态上报回调函数
- avRecorder.on('stateChange', (state, reason) => {
+ avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.log(`current state is ${state}`);
// 用户可以在此补充状态发生切换后想要进行的动作
})
// 错误上报回调函数
- avRecorder.on('error', (err) => {
+ avRecorder.on('error', (err: BusinessError) => {
console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`);
})
```
@@ -61,21 +61,21 @@
```ts
- let avProfile = {
+ let avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // 音频比特率
audioChannels: 2, // 音频声道数
audioCodec: media.CodecMimeType.AUDIO_AAC, // 音频编码格式,当前只支持aac
audioSampleRate: 48000, // 音频采样率
fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // 封装格式,当前只支持m4a
}
- let avConfig = {
+ let avConfig: media.AVRecorderConfig = {
audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // 音频输入源,这里设置为麦克风
profile: avProfile,
url: 'fd://35', // 参考应用文件访问与管理中的开发示例获取创建的音频文件fd填入此处
}
avRecorder.prepare(avConfig).then(() => {
console.log('Invoke prepare succeeded.');
- }, (err) => {
+ }, (err: BusinessError) => {
console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`);
})
```
@@ -99,17 +99,18 @@
```ts
import media from '@ohos.multimedia.media';
+import { BusinessError } from '@ohos.base';
export class AudioRecorderDemo {
- private avRecorder;
- private avProfile = {
+ private avRecorder: media.AVRecorder;
+ private avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // 音频比特率
audioChannels: 2, // 音频声道数
audioCodec: media.CodecMimeType.AUDIO_AAC, // 音频编码格式,当前只支持aac
audioSampleRate: 48000, // 音频采样率
fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // 封装格式,当前只支持m4a
};
- private avConfig = {
+ private avConfig: media.AVRecorderConfig = {
audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // 音频输入源,这里设置为麦克风
profile: this.avProfile,
url: 'fd://35', // 参考应用文件访问与管理开发示例新建并读写一个文件
@@ -118,11 +119,11 @@ export class AudioRecorderDemo {
// 注册audioRecorder回调函数
setAudioRecorderCallback() {
// 状态机变化回调函数
- this.avRecorder.on('stateChange', (state, reason) => {
+ this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.log(`AudioRecorder current state is ${state}`);
})
// 错误上报回调函数
- this.avRecorder.on('error', (err) => {
+ this.avRecorder.on('error', (err: BusinessError) => {
console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`);
})
}
diff --git a/zh-cn/application-dev/media/video-recording.md b/zh-cn/application-dev/media/video-recording.md
index 7cdf749e64ad558962d06fe7d15de88ab0f77b36..49bea13d413b18b100975e43a2cab41af8661d60 100644
--- a/zh-cn/application-dev/media/video-recording.md
+++ b/zh-cn/application-dev/media/video-recording.md
@@ -24,10 +24,10 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js
```ts
import media from '@ohos.multimedia.media'
- let avRecorder
- media.createAVRecorder().then((recorder) => {
+ let avRecorder: media.AVRecorder;
+ media.createAVRecorder().then((recorder: media.AVRecorder) => {
avRecorder = recorder
- }, (error) => {
+ }, (error: Error) => {
console.error('createAVRecorder failed')
})
```
@@ -40,11 +40,11 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js
```ts
// 状态上报回调函数
- avRecorder.on('stateChange', (state, reason) => {
+ avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.info('current state is: ' + state);
})
// 错误上报回调函数
- avRecorder.on('error', (err) => {
+ avRecorder.on('error', (err: BusinessError) => {
console.error('error happened, error message is ' + err);
})
```
@@ -62,7 +62,7 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js
> - 录制输出的url地址(即示例里avConfig中的url),形式为fd://xx (fd number)。需要调用基础文件操作接口([ohos.file.fs](../reference/apis/js-apis-file-fs.md))实现应用文件访问能力,获取方式参考[应用文件访问与管理](../file-management/app-file-access.md)。
```ts
- let avProfile = {
+ let avProfile: media.AVRecorderProfile = {
fileFormat : media.ContainerFormatType.CFT_MPEG_4, // 视频文件封装格式,只支持MP4
videoBitrate : 200000, // 视频比特率
videoCodec : media.CodecMimeType.VIDEO_AVC, // 视频文件编码格式,支持mpeg4和avc两种格式
@@ -70,15 +70,15 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js
videoFrameHeight : 480, // 视频分辨率的高
videoFrameRate : 30 // 视频帧率
}
- let avConfig = {
+ let avConfig: media.AVRecorderConfig = {
videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // 视频源类型,支持YUV和ES两种格式
- profile : this.avProfile,
+ profile : avProfile,
url : 'fd://35', // 参考应用文件访问与管理开发示例新建并读写一个文件
rotation : 0, // 视频旋转角度,默认为0不旋转,支持的值为0、90、180、270
}
avRecorder.prepare(avConfig).then(() => {
console.info('avRecorder prepare success')
- }, (error) => {
+ }, (error: Error) => {
console.error('avRecorder prepare failed')
})
```
@@ -89,9 +89,9 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js
输入源模块通过SurfaceID可以获取到Surface,通过Surface可以将视频数据流传递给AVRecorder,由AVRecorder再进行视频数据的处理。
```ts
- avRecorder.getInputSurface().then((surfaceId) => {
+ avRecorder.getInputSurface().then((surfaceId: string) => {
console.info('avRecorder getInputSurface success')
- }, (error) => {
+ }, (error: Error) => {
console.error('avRecorder getInputSurface failed')
})
```
@@ -118,11 +118,12 @@ AVRecorder详细的API说明请参考[AVRecorder API参考](../reference/apis/js
```ts
import media from '@ohos.multimedia.media'
+import { BusinessError } from '@ohos.base';
const TAG = 'VideoRecorderDemo:'
export class VideoRecorderDemo {
- private avRecorder;
- private videoOutSurfaceId;
- private avProfile = {
+ private avRecorder: media.AVRecorder;
+ private videoOutSurfaceId: string;
+ private avProfile: media.AVRecorderProfile = {
fileFormat : media.ContainerFormatType.CFT_MPEG_4, // 视频文件封装格式,只支持MP4
videoBitrate : 100000, // 视频比特率
videoCodec : media.CodecMimeType.VIDEO_AVC, // 视频文件编码格式,支持mpeg4和avc两种格式
@@ -130,7 +131,7 @@ export class VideoRecorderDemo {
videoFrameHeight : 480, // 视频分辨率的高
videoFrameRate : 30 // 视频帧率
}
- private avConfig = {
+ private avConfig: media.AVRecorderConfig = {
videoSourceType : media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // 视频源类型,支持YUV和ES两种格式
profile : this.avProfile,
url : 'fd://35', // 参考应用文件访问与管理开发示例新建并读写一个文件
@@ -140,11 +141,11 @@ export class VideoRecorderDemo {
// 注册avRecorder回调函数
setAvRecorderCallback() {
// 状态机变化回调函数
- this.avRecorder.on('stateChange', (state, reason) => {
+ this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.info(TAG + 'current state is: ' + state);
})
// 错误上报回调函数
- this.avRecorder.on('error', (err) => {
+ this.avRecorder.on('error', (err: BusinessError) => {
console.error(TAG + 'error ocConstantSourceNode, error message is ' + err);
})
}
@@ -183,7 +184,7 @@ export class VideoRecorderDemo {
// 5.启动相机出流
await this.startCameraOutput();
// 6. 启动录制
- await this.videoRecorder.start();
+ await this.avRecorder.start();
}
// 暂停录制对应的流程
diff --git a/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md b/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md
index 7df90501a582c02e796a5eb61a73013dc14335ee..d63149dcb8418d6d5bf6028dcbeb074f1b1ff1fa 100644
--- a/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md
+++ b/zh-cn/application-dev/quick-start/arkts-observed-and-objectlink.md
@@ -35,7 +35,7 @@
| ----------------- | ---------------------------------------- |
| 装饰器参数 | 无 |
| 同步类型 | 不与父组件中的任何类型同步变量。 |
-| 允许装饰的变量类型 | 必须为被\@Observed装饰的class实例,必须指定类型。
不支持简单类型,可以使用[\@Prop](arkts-prop.md)。
\@ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。 |
+| 允许装饰的变量类型 | 必须为被\@Observed装饰的class实例,必须指定类型。
不支持简单类型,可以使用[\@Prop](arkts-prop.md)。
支持继承Date或者Array的class实例,示例见[观察变化](#观察变化)。
\@ObjectLink的属性是可以改变的,但是变量的分配是不允许的,也就是说这个装饰器装饰变量是只读的,不能被改变。 |
| 被装饰变量的初始值 | 不允许。 |
\@ObjectLink装饰的数据为可读示例。
@@ -75,7 +75,7 @@ this.objLink= ...
## 观察变化和行为表现
-### 观察的变化
+### 观察变化
\@Observed装饰的类,如果其属性为非简单类型,比如class、Object或者数组,也需要被\@Observed装饰,否则将观察不到其属性的变化。
@@ -121,6 +121,67 @@ this.b.a.c = 5
- 如果数据源是数组,则可以观察到数组item的替换,如果数据源是class,可观察到class的属性的变化,示例请参考[对象数组](#对象数组)。
+继承Date的class时,可以观察到Date整体的赋值,同时可通过调用Date的接口`setFullYear`, `setMonth`, `setDate`, `setHours`, `setMinutes`, `setSeconds`, `setMilliseconds`, `setTime`, `setUTCFullYear`, `setUTCMonth`, `setUTCDate`, `setUTCHours`, `setUTCMinutes`, `setUTCSeconds`, `setUTCMilliseconds` 更新Date的属性。
+
+```ts
+@Observed
+class DateClass extends Date {
+ constructor(args: any) {
+ super(args)
+ }
+}
+
+@Observed
+class ClassB {
+ public a: DateClass;
+
+ constructor(a: DateClass) {
+ this.a = a;
+ }
+}
+
+@Component
+struct ViewA {
+ label: string = 'date';
+ @ObjectLink a: DateClass;
+
+ build() {
+ Column() {
+ Button(`child increase the day by 1`)
+ .onClick(() => {
+ this.a.setDate(this.a.getDate() + 1);
+ })
+ DatePicker({
+ start: new Date('1970-1-1'),
+ end: new Date('2100-1-1'),
+ selected: this.a
+ })
+ }
+ }
+}
+
+@Entry
+@Component
+struct ViewB {
+ @State b: ClassB = new ClassB(new DateClass('2023-1-1'));
+
+ build() {
+ Column() {
+ ViewA({ label: 'date', a: this.b.a })
+
+ Button(`parent update the new date`)
+ .onClick(() => {
+ this.b.a = new DateClass('2023-07-07');
+ })
+ Button(`ViewB: this.b = new ClassB(new DateClass('2023-08-20'))`)
+ .onClick(() => {
+ this.b = new ClassB(new DateClass('2023-08-20'));
+ })
+ }
+ }
+}
+```
+
### 框架行为
diff --git a/zh-cn/application-dev/quick-start/module-configuration-file.md b/zh-cn/application-dev/quick-start/module-configuration-file.md
index 5e4386be6f46b3990fadaaa080681d0736c4c48d..085ef79b42632f790059ce8da80322055b85af94 100644
--- a/zh-cn/application-dev/quick-start/module-configuration-file.md
+++ b/zh-cn/application-dev/quick-start/module-configuration-file.md
@@ -97,6 +97,7 @@ module.json5配置文件包含以下标签。
| isolationMode | 标识当前Module的多进程配置项。类型有4种,分别:
- nonisolationFirst:优先在非独立进程中运行。
- isolationFirst:优先在独立进程中运行。
- isolationOnly:只在独立进程中运行。
- nonisolationOnly:只在非独立进程中运行。 |字符串|该标签可缺省, 缺省值为nonisolationFirst。|
| generateBuildHash |标识当前HAP/HSP是否由打包工具生成哈希值。如果存在,则在系统OTA升级但应用的versionCode保持不变时,可根据哈希值判断应用是否需要升级。
该字段仅在[app.json5文件](./app-configuration-file.md)中的generateBuildHash字段为false时使能。**
注:该字段仅对预置应用生效。**|布尔值|该标签可缺省, 缺省值为false。|
| compressNativeLibs | 标识libs库是否以压缩存储的方式打包到HAP。
- true:libs库以压缩方式存储。
- false:libs库以不压缩方式存储,HAP在安装时无需解压libs,运行时会直接从HAP内加载libs库。 | 布尔值 | 可缺省,缺省值为true。 |
+| libIsolation | 用于区分同应用不同hap下的so文件,以防止so冲突。
- true:当前hap的so会储存在libs目录中以Module名命名的路径下。
- false:当前hap的so会直接储存在libs目录中。 | 布尔值 | 该标签可缺省, 缺省值为false。 |
## deviceTypes标签
diff --git a/zh-cn/application-dev/quick-start/module-structure.md b/zh-cn/application-dev/quick-start/module-structure.md
index 58e1254a06a0ec69494b52a5a74f1770b772e6dc..afc0c0451ae6a5a1aeecea3ff91b65d8b4457829 100644
--- a/zh-cn/application-dev/quick-start/module-structure.md
+++ b/zh-cn/application-dev/quick-start/module-structure.md
@@ -25,6 +25,7 @@ module对象包含HAP的配置信息。
| entryTheme | 此标签标识OpenHarmony内部主题的关键字。将标记值设置为名称的资源索引。 | 字符串 | 可缺省,缺省值为空。 |
|testRunner | 此标签用于支持对测试框架的配置。 | 对象 | 可缺省,缺省值为空。 |
|generateBuildHash |标识当前HAP/HSP是否由打包工具生成哈希值。如果存在,则在系统OTA升级但应用的[version下的code](./app-structure.md#version对象内部结构)保持不变时,可根据哈希值判断应用是否需要升级。**
注:该字段仅对预置应用生效。**|布尔值|该标签可缺省, 缺省值为false。|
+|libIsolation |用于区分同应用不同hap下的so文件,以防止so冲突。
- true:当前hap的so会储存在libs目录中以Module名命名的路径下。
- false:当前hap的so会直接储存在libs目录中。|布尔值|该标签可缺省, 缺省值为false。|
module示例:
diff --git a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md
index 648a68b075820e6959991f119c481be24c1ff8da..ac6dfc795a1f34ed7bf4a47d4e86754910d4c548 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-ability-ability.md
@@ -15,7 +15,14 @@ import ability from '@ohos.ability.ability';
## 属性
-**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityBase
+**系统能力**:
+DataAbilityHelper:SystemCapability.Ability.AbilityRuntime.FAModel
+PacMap:SystemCapability.Ability.AbilityRuntime.FAModel
+DataAbilityOperation:SystemCapability.Ability.AbilityRuntime.FAModel
+DataAbilityResult:SystemCapability.Ability.AbilityRuntime.FAModel
+AbilityResult:SystemCapability.Ability.AbilityBase
+ConnectOptions:SystemCapability.Ability.AbilityRuntime.Core
+StartAbilityParameter:SystemCapability.Ability.AbilityRuntime.FAModel
| 名称 | 类型 | 描述 |
| ----------- | -------------------- | ------------------------------------------------------------ |
diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-actionExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-actionExtensionAbility.md
new file mode 100644
index 0000000000000000000000000000000000000000..714835a8486aedc304100c4584ab270b179b85ae
--- /dev/null
+++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-actionExtensionAbility.md
@@ -0,0 +1,165 @@
+# @ohos.app.ability.ActionExtensionAbility (自定义服务扩展能力)
+
+ActionExtensionAbility是为开发者提供的自定义操作业务模板,继承自[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md)。ActionExtension主要用于查看宿主应用中的内容以及对其进行对应处理。例如,添加一个书签、将选中的文本翻译成其他语言、在当前页面编辑图像等。
+
+> **说明:**
+>
+> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
+> 本模块接口仅可在Stage模型下使用。
+
+## 场景介绍
+
+以翻译文本为例。首先需要创建请求发起方,再创建出ActionExtension,请求发起方需要将翻译的文本发送给ActionExtension,ActionExtension接收到文本后,需要将接收的文本进行翻译,翻译后的文本再发送给请求发起方。
+
+## 导入模块
+
+```ts
+import ActionExtensionAbility from '@ohos.app.ability.ActionExtensionAbility';
+```
+
+## 属性
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+| 名称 | 类型 | 可读 | 可写 | 说明 |
+| -------- | -------- | -------- | -------- | -------- |
+| context | [UIExtensionContext](js-apis-inner-application-uiExtensionContext.md) | 是 | 否 | 上下文。 |
+
+## ActionExtensionAbility.onCreate
+
+onCreate(): void
+
+ActionExtensionAbility创建时回调,执行初始化业务逻辑操作。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## ActionExtensionAbility.onSessionCreate
+
+onSessionCreate(want: Want, session: UIExtensionContentSession): void
+
+当ActionExtensionAbility界面内容对象创建后调用。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-app-ability-want.md) | 是 | 当前ActionExtensionAbility的Want类型信息,包括ability名称、bundle名称等。 |
+| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | ActionExtensionAbility界面内容相关信息。 |
+
+## ActionExtensionAbility.onSessionDestroy
+
+onSessionDestroy(session: UIExtensionContentSession): void
+
+当ActionExtensionAbility界面内容对象销毁后调用。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | -------- | -------- | -------- |
+| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | ActionExtensionAbility界面内容相关信息。 |
+
+## ActionExtensionAbility.onForeground
+
+onForeground(): void;
+
+ActionExtensionAbility生命周期回调,当ActionExtensionAbility从后台转到前台时触发。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## ActionExtensionAbility.onBackground
+
+onBackground(): void;
+
+ActionExtensionAbility生命周期回调,当ActionExtensionAbility从前台转到后台时触发。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## ActionExtensionAbility.onDestroy
+
+onDestroy(): void | Promise<void>;
+
+ActionExtensionAbility生命周期回调,在销毁时回调,执行资源清理等操作。
+在执行完onDestroy生命周期回调后,应用可能会退出,从而可能导致onDestroy中的异步函数未能正确执行,比如异步写入数据库。可以使用异步生命周期,以确保异步onDestroy完成后再继续后续的生命周期。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## 创建ActionExtensionAbility
+
+在DevEco Studio工程中手动新建一个ActionExtensionAbility,具体步骤如下:
+
+1. 在工程Module对应的ets目录下,右键选择“New > Directory”,新建一个目录并命名为ActionExtAbility。
+
+2. 在ActionExtAbility目录,右键选择“New > TypeScript File”,新建一个TypeScript文件并命名为ActionExtAbility.ts。
+
+ ```
+ ├── ets
+ │ ├── ActionExtAbility
+ │ │ ├── ActionExtAbility.ts
+ └
+ ```
+
+3. ActionExtAbility.ts文件中,增加导入ActionExtensionAbility的依赖包,自定义类继承ActionExtensionAbility并实现生命周期回调。
+
+ ```ts
+ import ActionExtensionAbility from '@ohos.app.ability.ActionExtensionAbility';
+ const TAG: string = "[ActionExtAbility]";
+
+ export default class ActionExtAbility extends ActionExtensionAbility {
+ storage: LocalStorage;
+ message: string;
+ onCreate() {
+ console.info(TAG, `onCreate`);
+ }
+
+ onForeground() {
+ console.info(TAG, `ononForeground`);
+ }
+
+ onBackground() {
+ console.info(TAG, `onBackground`);
+ }
+
+ onSessionCreate(want, session) {
+ console.info(TAG, `onSessionCreate, want: ${want.abilityName}`);
+ this.message = want.parameters.shareMessages;
+ this.storage = new LocalStorage(
+ {
+ 'session': session,
+ 'messages': this.message
+ });
+ session.loadContent('pages/Index', this.storage);
+ }
+
+ onSessionDestroy(session) {
+ console.info(TAG, `onSessionDestroy`);
+ }
+
+ onDestroy() {
+ console.info(TAG, `onDestroy`);
+ }
+ }
+ ```
+
+4. 在工程Module对应的[module.json5配置文件](../../quick-start/module-configuration-file.md)中注册ActionExtensionAbility,type标签需要设置为“action”,srcEntry标签表示当前ExtensionAbility组件所对应的代码路径。
+
+ ```json
+ {
+ "module": {
+ ...
+ "extensionAbilities": [
+ {
+ "name": "ActionExtAbility",
+ "icon": "$media:icon",
+ "description": "action",
+ "type": "action",
+ "exported": true,
+ "srcEntry": "./ets/ActionExtAbility/ActionExtAbility.ts"
+ }
+ ]
+ }
+ }
+ ```
diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md
index 5a2f72d2684e110b1d351e14f32f4a2cbce6f40f..880d3e02b81c105c2cdeec1bb74f3e61da5eb7c7 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-common.md
@@ -16,6 +16,8 @@ import common from '@ohos.app.ability.common';
**系统能力**:以下各项对应的系统能力均为SystemCapability.Ability.AbilityRuntime.Core
+**系统API**:该接口为系统接口,三方应用不支持调用。
+
| 名称 | 类型 | 说明 |
| ----------- | -------------------- | ------------------------------------------------------------ |
| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | UIAbilityContext二级模块。 |
diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md
index 7b01e5e25d1e8938c40cc268a9c671fc44ee30f1..05be616d309b30dc17842f01ae51e98c51d3c3ff 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md
@@ -309,12 +309,6 @@ revokeQuickFix(bundleName: string): Promise\;
在撤销补丁过程中发生的错误,其错误码及错误信息通过公共事件[COMMON_EVENT_QUICK_FIX_REVOKE_RESULT](./common_event/commonEvent-ability.md#common_event_quick_fix_revoke_result10)的参数返回给应用开发者。这部分错误码及错误信息如下:
-| 错误码ID | 错误信息 |
-| ------- | -------- |
-| 18500004 | Switch hqf failed. |
-| 18500005 | Delete hqf failed. |
-| 18500007 | Unload patch failed. |
-
**示例:**
```ts
diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-ability-shareExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-app-ability-shareExtensionAbility.md
new file mode 100644
index 0000000000000000000000000000000000000000..fdeddbadb84b2d5f99b393c26178c35de9a12ec4
--- /dev/null
+++ b/zh-cn/application-dev/reference/apis/js-apis-app-ability-shareExtensionAbility.md
@@ -0,0 +1,163 @@
+# @ohos.app.ability.ShareExtensionAbility (分享模板服务扩展能力)
+
+ShareExtensionAbility是为开发者提供分享操作业务模板,继承自[UIExtensionAbility](js-apis-app-ability-uiExtensionAbility.md)。ShareExtension为人们提供了一种通过应用程序、社交媒体帐户和其他服务共享当前上下文信息的便捷方式。
+
+> **说明:**
+>
+> 本模块首批接口从API version 10 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
+> 本模块接口仅可在Stage模型下使用。
+
+## 场景介绍
+
+以分享文本为例。用户选择一段文本,拉起要分享应用,此时被分享拉起的应用会根据分享信息将分享模板拉起,并将数据按分享模板内容显示。
+
+## 导入模块
+
+```ts
+import ShareExtensionAbility from '@ohos.app.ability.ShareExtensionAbility';
+```
+
+## 属性
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+| 名称 | 类型 | 可读 | 可写 | 说明 |
+| -------- | -------- | -------- | -------- | -------- |
+| context | [UIExtensionContext](js-apis-inner-application-uiExtensionContext.md) | 是 | 否 | 上下文。 |
+
+## ShareExtensionAbility.onCreate
+
+onCreate(): void
+
+ShareExtensionAbility创建时回调,执行初始化业务逻辑操作。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## ShareExtensionAbility.onSessionCreate
+
+onSessionCreate(want: Want, session: UIExtensionContentSession): void
+
+当ShareExtensionAbility界面内容对象创建后调用。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | -------- | -------- | -------- |
+| want | [Want](js-apis-app-ability-want.md) | 是 | 当前ShareExtensionAbility的Want类型信息,包括ability名称、bundle名称等。 |
+| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | ShareExtensionAbility界面内容相关信息。 |
+
+## ShareExtensionAbility.onSessionDestroy
+
+onSessionDestroy(session: UIExtensionContentSession): void
+
+当ShareExtensionAbility界面内容对象销毁后调用。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | -------- | -------- | -------- |
+| session | [UIExtensionContentSession](js-apis-app-ability-uiExtensionContentSession.md) | 是 | ShareExtensionAbility界面内容相关信息。 |
+
+## ShareExtensionAbility.onForeground
+
+onForeground(): void;
+
+ShareExtensionAbility生命周期回调,当ShareExtensionAbility从后台转到前台时触发。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## ShareExtensionAbility.onBackground
+
+onBackground(): void;
+
+ShareExtensionAbility生命周期回调,当ShareExtensionAbility从前台转到后台时触发。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## ShareExtensionAbility.onDestroy
+
+onDestroy(): void | Promise<void>;
+
+ShareExtensionAbility生命周期回调,在销毁时回调,执行资源清理等操作。
+在执行完onDestroy生命周期回调后,应用可能会退出,从而可能导致onDestroy中的异步函数未能正确执行,比如异步写入数据库。可以使用异步生命周期,以确保异步onDestroy完成后再继续后续的生命周期。
+
+**系统能力**:SystemCapability.Ability.AbilityRuntime.AbilityCore
+
+## 创建ShareExtensionAbility
+
+在DevEco Studio工程中手动新建一个ShareExtensionAbility,具体步骤如下:
+
+1. 在工程Module对应的ets目录下,右键选择“New > Directory”,新建一个目录并命名为ShareExtAbility。
+
+2. 在ShareExtAbility目录,右键选择“New > TypeScript File”,新建一个TypeScript文件并命名为ShareExtAbility.ts。
+
+ ```
+ ├── ets
+ │ ├── ShareExtAbility
+ │ │ ├── ShareExtAbility.ts
+ └
+ ```
+
+3. ShareExtAbility.ts文件中,增加导入ShareExtensionAbility的依赖包,自定义类继承ShareExtensionAbility并实现生命周期回调。
+
+ ```ts
+ import ShareExtensionAbility from '@ohos.app.ability.ShareExtensionAbility';
+ const TAG: string = "[ShareExtAbility]";
+
+ export default class ShareExtAbility extends ShareExtensionAbility {
+ onCreate() {
+ console.info(TAG, `onCreate`);
+ }
+
+ onForeground() {
+ console.info(TAG, `ononForeground`);
+ }
+
+ onBackground() {
+ console.info(TAG, `onBackground`);
+ }
+
+ onSessionCreate(want, session) {
+ console.info(TAG, `onSessionCreate, want: ${want.abilityName}`);
+ this.message = want.parameters.shareMessages;
+ this.storage = new LocalStorage(
+ {
+ 'session': session,
+ 'messages': this.message
+ });
+ session.loadContent('pages/Index', this.storage);
+ }
+
+ onSessionDestroy(session) {
+ console.info(TAG, `onSessionDestroy`);
+ }
+
+ onDestroy() {
+ console.info(TAG, `onDestroy`);
+ }
+ }
+ ```
+
+4. 在工程Module对应的[module.json5配置文件](../../quick-start/module-configuration-file.md)中注册ShareExtensionAbility,type标签需要设置为“share”,srcEntry标签表示当前ExtensionAbility组件所对应的代码路径。
+
+ ```json
+ {
+ "module": {
+ ...
+ "extensionAbilities": [
+ {
+ "name": "ShareExtAbility",
+ "icon": "$media:icon",
+ "description": "share",
+ "type": "share",
+ "exported": true,
+ "srcEntry": "./ets/ShareExtAbility/ShareExtAbility.ts"
+ }
+ ]
+ }
+ }
+ ```
\ No newline at end of file
diff --git a/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md b/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md
index 7a3ed1f4cd871af1563f3c97d046cd1ad8d49f10..68d25e0d80fc0997eadadad73642a07ef382587d 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-app-form-formObserver.md
@@ -43,7 +43,7 @@ formObserver.on('formAdd', callback);
## on('formAdd')
- on(type: 'formAdd', bundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void
+ on(type: 'formAdd', hostBundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void
订阅卡片新增事件。使用callback异步回调,返回指定卡片使用方应用新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。
@@ -74,7 +74,7 @@ formObserver.on('formAdd', bundleName, callback);
## off('formAdd')
- off(type: "formAdd", bundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void
+ off(type: "formAdd", hostBundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void
取消订阅卡片新增事件。使用callback异步回调,返回当前新增卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。
@@ -138,7 +138,7 @@ formObserver.on('formRemove', callback);
## on('formRemove')
- on(type: 'formRemove', bundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void
+ on(type: 'formRemove', hostBundleName: string, observerCallback: Callback<formInfo.RunningFormInfo>): void
订阅卡片删除事件。使用callback异步回调,返回指定卡片使用方应用被删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。
@@ -169,7 +169,7 @@ formObserver.on('formRemove', bundleName, callback);
## off('formRemove')
-off(type: "formRemove", bundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void
+off(type: "formRemove", hostBundleName?: string, observerCallback?: Callback<formInfo.RunningFormInfo>): void
取消订阅卡片删除事件。使用callback异步回调,返回当前删除卡片的[RunningFormInfo](js-apis-app-form-formInfo.md)。
@@ -234,7 +234,7 @@ formObserver.on('notifyVisible', callback);
## on('notifyVisible')
- on(type: 'notifyVisible', bundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+ on(type: 'notifyVisible', hostBundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
订阅通知卡片可见的事件。
@@ -267,7 +267,7 @@ formObserver.on('notifyVisible', bundleName, callback);
## off('notifyVisible')
- off(type: "notifyVisible", bundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+ off(type: "notifyVisible", hostBundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
取消订阅通知卡片可见的事件。
@@ -335,7 +335,7 @@ formObserver.on('notifyInvisible', callback);
## on('notifyInvisible')
- on(type: 'notifyInvisible', bundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+ on(type: 'notifyInvisible', hostBundleName: string, observerCallback: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
订阅通知卡片不可见的事件。
@@ -367,7 +367,7 @@ formObserver.on('notifyInvisible', bundleName, callback);
## off('notifyInvisible')
- off(type: "notifyInvisible", bundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
+ off(type: "notifyInvisible", hostBundleName?: string, observerCallback?: Callback<Array<[formInfo.RunningFormInfo](js-apis-app-form-formInfo.md)>>): void
取消订阅通知卡片不可见事件。
diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md
index 60225153f733d87d8d485c0b86513b686ce034e4..aa6381e87eb13d41de8d53e19afd1663d67e0e8f 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md
@@ -64,8 +64,10 @@ createAccount(name: string, callback: AsyncCallback<void>): void;
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.createAccount('WangWu', (err) => {
+ appAccountManager.createAccount('WangWu', (err: BusinessError) => {
console.log('createAccount err: ' + JSON.stringify(err));
});
} catch (err) {
@@ -101,13 +103,15 @@ createAccount(name: string, options: CreateAccountOptions, callback: AsyncCallba
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let options = {
customData: {
'age': '10'
}
}
try {
- appAccountManager.createAccount('LiSi', options, (err) => {
+ appAccountManager.createAccount('LiSi', options, (err: BusinessError) => {
if (err) {
console.log('createAccount failed, error: ' + JSON.stringify(err));
} else {
@@ -152,6 +156,8 @@ createAccount(name: string, options?: CreateAccountOptions): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let options = {
customData: {
'age': '10'
@@ -160,7 +166,7 @@ createAccount(name: string, options?: CreateAccountOptions): Promise<void>
try {
appAccountManager.createAccount('LiSi', options).then(() => {
console.log('createAccount successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('createAccount failed, error: ' + JSON.stringify(err));
});
} catch(err) {
@@ -197,12 +203,15 @@ createAccountImplicitly(owner: string, callback: AuthCallback): void
**示例:**
```js
- function onResultCallback(code, result) {
+ import { BusinessError } from '@ohos.base';
+ import Want from '@ohos.app.ability.Want';
+
+ function onResultCallback(code: number, result: account_appAccount.AuthResult) {
console.log('resultCode: ' + code);
console.log('result: ' + JSON.stringify(result));
}
- function onRequestRedirectedCallback(request) {
+ function onRequestRedirectedCallback(request: Want) {
let wantInfo = {
deviceId: '',
bundleName: 'com.example.accountjsdemo',
@@ -211,7 +220,7 @@ createAccountImplicitly(owner: string, callback: AuthCallback): void
}
this.context.startAbility(wantInfo).then(() => {
console.log('startAbility successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('startAbility err: ' + JSON.stringify(err));
})
}
@@ -256,12 +265,15 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions,
**示例:**
```js
- function onResultCallback(code, result) {
+ import { BusinessError } from '@ohos.base';
+ import Want from '@ohos.app.ability.Want';
+
+ function onResultCallback(code: number, result: account_appAccount.AuthResult) {
console.log('resultCode: ' + code);
console.log('result: ' + JSON.stringify(result));
}
- function onRequestRedirectedCallback(request) {
+ function onRequestRedirectedCallback(request: Want) {
let wantInfo = {
deviceId: '',
bundleName: 'com.example.accountjsdemo',
@@ -270,7 +282,7 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions,
}
this.context.startAbility(wantInfo).then(() => {
console.log('startAbility successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('startAbility err: ' + JSON.stringify(err));
})
}
@@ -315,8 +327,10 @@ removeAccount(name: string, callback: AsyncCallback<void>): void
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.removeAccount('ZhaoLiu', (err) => {
+ appAccountManager.removeAccount('ZhaoLiu', (err: BusinessError) => {
if (err) {
console.log('removeAccount failed, error: ' + JSON.stringify(err));
} else {
@@ -359,10 +373,12 @@ removeAccount(name: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager.removeAccount('Lisi').then(() => {
console.log('removeAccount successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('removeAccount failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -399,8 +415,10 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean, callback:
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true, (err) => {
+ appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true, (err: BusinessError) => {
if (err) {
console.log('setAppAccess failed: ' + JSON.stringify(err));
} else {
@@ -446,10 +464,12 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise&l
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager.setAppAccess('ZhangSan', 'com.example.accountjsdemo', true).then(() => {
console.log('setAppAccess successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setAppAccess failed: ' + JSON.stringify(err));
});
} catch (err) {
@@ -484,14 +504,17 @@ checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<bool
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo', (err, isAccessible) => {
- if (err) {
- console.log('checkAppAccess failed, error: ' + JSON.stringify(err));
- } else {
- console.log('checkAppAccess successfully');
- }
- });
+ appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo',
+ (err: BusinessError, isAccessible: boolean) => {
+ if (err) {
+ console.log('checkAppAccess failed, error: ' + JSON.stringify(err));
+ } else {
+ console.log('checkAppAccess successfully');
+ }
+ });
} catch (err) {
console.log('checkAppAccess exception: ' + JSON.stringify(err));
}
@@ -529,10 +552,12 @@ checkAppAccess(name: string, bundleName: string): Promise<boolean>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo').then((isAccessible) => {
+ appAccountManager.checkAppAccess('ZhangSan', 'com.example.accountjsdemo').then((isAccessible: boolean) => {
console.log('checkAppAccess successfully, isAccessible: ' + isAccessible);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('checkAppAccess failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -569,8 +594,10 @@ setDataSyncEnabled(name: string, isEnabled: boolean, callback: AsyncCallback<
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.setDataSyncEnabled('ZhangSan', true, (err) => {
+ appAccountManager.setDataSyncEnabled('ZhangSan', true, (err: BusinessError) => {
console.log('setDataSyncEnabled err: ' + JSON.stringify(err));
});
} catch (err) {
@@ -612,10 +639,12 @@ setDataSyncEnabled(name: string, isEnabled: boolean): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager .setDataSyncEnabled('ZhangSan', true).then(() => {
console.log('setDataSyncEnabled Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setDataSyncEnabled err: ' + JSON.stringify(err));
});
} catch (err) {
@@ -651,8 +680,10 @@ checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.checkDataSyncEnabled('ZhangSan', (err, isEnabled) => {
+ appAccountManager.checkDataSyncEnabled('ZhangSan', (err: BusinessError, isEnabled: boolean) => {
if (err) {
console.log('checkDataSyncEnabled failed, err: ' + JSON.stringify(err));
} else {
@@ -697,10 +728,12 @@ checkDataSyncEnabled(name: string): Promise<boolean>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.checkDataSyncEnabled('ZhangSan').then((isEnabled) => {
+ appAccountManager.checkDataSyncEnabled('ZhangSan').then((isEnabled: boolean) => {
console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('checkDataSyncEnabled failed, err: ' + JSON.stringify(err));
});
} catch (err) {
@@ -736,8 +769,10 @@ setCredential(name: string, credentialType: string, credential: string,callback:
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx', (err) => {
+ appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx', (err: BusinessError) => {
if (err) {
console.log('setCredential failed, error: ' + JSON.stringify(err));
} else {
@@ -782,10 +817,12 @@ setCredential(name: string, credentialType: string, credential: string): Promise
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager.setCredential('ZhangSan', 'PIN_SIX', 'xxxxxx').then(() => {
console.log('setCredential successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setCredential failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -821,8 +858,10 @@ getCredential(name: string, credentialType: string, callback: AsyncCallback<s
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getCredential('ZhangSan', 'PIN_SIX', (err, result) => {
+ appAccountManager.getCredential('ZhangSan', 'PIN_SIX', (err: BusinessError, result: string) => {
if (err) {
console.log('getCredential failed, error: ' + JSON.stringify(err));
} else {
@@ -867,10 +906,12 @@ getCredential(name: string, credentialType: string): Promise<string>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getCredential('ZhangSan', 'PIN_SIX').then((credential) => {
+ appAccountManager.getCredential('ZhangSan', 'PIN_SIX').then((credential: string) => {
console.log('getCredential successfully, credential: ' + credential);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getCredential failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -907,8 +948,10 @@ setCustomData(name: string, key: string, value: string, callback: AsyncCallback&
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.setCustomData('ZhangSan', 'age', '12', (err) => {
+ appAccountManager.setCustomData('ZhangSan', 'age', '12', (err: BusinessError) => {
if (err) {
console.log('setCustomData failed, error: ' + JSON.stringify(err));
} else {
@@ -954,10 +997,12 @@ setCustomData(name: string, key: string, value: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager.setCustomData('ZhangSan', 'age', '12').then(() => {
console.log('setCustomData successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setCustomData failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -993,8 +1038,10 @@ getCustomData(name: string, key: string, callback: AsyncCallback<string>):
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getCustomData('ZhangSan', 'age', (err, data) => {
+ appAccountManager.getCustomData('ZhangSan', 'age', (err: BusinessError, data: string) => {
if (err) {
console.log('getCustomData failed, error: ' + err);
} else {
@@ -1039,10 +1086,12 @@ getCustomData(name: string, key: string): Promise<string>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getCustomData('ZhangSan', 'age').then((data) => {
+ appAccountManager.getCustomData('ZhangSan', 'age').then((data: string) => {
console.log('getCustomData successfully, data: ' + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getCustomData failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -1114,8 +1163,10 @@ getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAllAccounts((err, data) => {
+ appAccountManager.getAllAccounts((err: BusinessError, data: account_appAccount.AppAccountInfo[]) => {
if (err) {
console.debug('getAllAccounts failed, error: ' + JSON.stringify(err));
} else {
@@ -1150,10 +1201,12 @@ getAllAccounts(): Promise<Array<AppAccountInfo>>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAllAccounts().then((data) => {
+ appAccountManager.getAllAccounts().then((data: account_appAccount.AppAccountInfo[]) => {
console.debug('getAllAccounts successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.debug('getAllAccounts failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -1187,14 +1240,17 @@ getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccount
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAccountsByOwner('com.example.accountjsdemo2', (err, data) => {
- if (err) {
- console.debug('getAccountsByOwner failed, error:' + JSON.stringify(err));
- } else {
- console.debug('getAccountsByOwner successfully, data:' + JSON.stringify(data));
- }
- });
+ appAccountManager.getAccountsByOwner('com.example.accountjsdemo2',
+ (err: BusinessError, data: account_appAccount.AppAccountInfo[]) => {
+ if (err) {
+ console.debug('getAccountsByOwner failed, error:' + JSON.stringify(err));
+ } else {
+ console.debug('getAccountsByOwner successfully, data:' + JSON.stringify(data));
+ }
+ });
} catch (err) {
console.debug('getAccountsByOwner exception:' + JSON.stringify(err));
}
@@ -1231,10 +1287,13 @@ getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAccountsByOwner('com.example.accountjsdemo2').then((data) => {
+ appAccountManager.getAccountsByOwner('com.example.accountjsdemo2').then((
+ data: account_appAccount.AppAccountInfo[]) => {
console.debug('getAccountsByOwner successfully, data: ' + JSON.stringify(data));
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.debug('getAccountsByOwner failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -1269,7 +1328,7 @@ on(type: 'accountChange', owners: Array<string>, callback: Callback<Arr
**示例:**
```js
- function changeOnCallback(data){
+ function changeOnCallback(data: account_appAccount.AppAccountInfo[]){
console.log('receive change data:' + JSON.stringify(data));
}
try{
@@ -1304,7 +1363,7 @@ off(type: 'accountChange', callback?: Callback<Array<AppAccountInfo>>
**示例:**
```js
- function changeOnCallback(data) {
+ function changeOnCallback(data: account_appAccount.AppAccountInfo[]) {
console.log('receive change data:' + JSON.stringify(data));
}
try{
@@ -1351,14 +1410,15 @@ auth(name: string, owner: string, authType: string, callback: AuthCallback): voi
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+ import Want from '@ohos.app.ability.Want';
-
- function onResultCallback(code, authResult) {
+ function onResultCallback(code: number, authResult: account_appAccount.AuthResult) {
console.log('resultCode: ' + code);
console.log('authResult: ' + JSON.stringify(authResult));
}
- function onRequestRedirectedCallback(request) {
+ function onRequestRedirectedCallback(request: Want) {
let wantInfo = {
deviceId: '',
bundleName: 'com.example.accountjsdemo',
@@ -1367,7 +1427,7 @@ auth(name: string, owner: string, authType: string, callback: AuthCallback): voi
}
this.context.startAbility(wantInfo).then(() => {
console.log('startAbility successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('startAbility err: ' + JSON.stringify(err));
})
}
@@ -1414,14 +1474,15 @@ auth(name: string, owner: string, authType: string, options: {[key: string]: Obj
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+ import Want from '@ohos.app.ability.Want';
-
- function onResultCallback(code, authResult) {
+ function onResultCallback(code: number, authResult: account_appAccount.AuthResult) {
console.log('resultCode: ' + code);
console.log('authResult: ' + JSON.stringify(authResult));
}
- function onRequestRedirectedCallback(request) {
+ function onRequestRedirectedCallback(request: Want) {
let wantInfo = {
deviceId: '',
bundleName: 'com.example.accountjsdemo',
@@ -1430,7 +1491,7 @@ auth(name: string, owner: string, authType: string, options: {[key: string]: Obj
}
this.context.startAbility(wantInfo).then(() => {
console.log('startAbility successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('startAbility err: ' + JSON.stringify(err));
})
}
@@ -1477,14 +1538,17 @@ getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallb
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', (err, token) => {
- if (err) {
- console.log('getAuthToken failed, error: ' + JSON.stringify(err));
- } else {
- console.log('getAuthToken successfully, token: ' + token);
- }
- });
+ appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData',
+ (err: BusinessError, token: string) => {
+ if (err) {
+ console.log('getAuthToken failed, error: ' + JSON.stringify(err));
+ } else {
+ console.log('getAuthToken successfully, token: ' + token);
+ }
+ });
} catch (err) {
console.log('getAuthToken exception: ' + JSON.stringify(err));
}
@@ -1524,10 +1588,12 @@ getAuthToken(name: string, owner: string, authType: string): Promise<string&g
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((token) => {
+ appAccountManager.getAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((token: string) => {
console.log('getAuthToken successfully, token: ' + token);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAuthToken failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -1564,8 +1630,10 @@ setAuthToken(name: string, authType: string, token: string, callback: AsyncCallb
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx', (err) => {
+ appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx', (err: BusinessError) => {
if (err) {
console.log('setAuthToken failed, error: ' + JSON.stringify(err));
} else {
@@ -1573,7 +1641,7 @@ setAuthToken(name: string, authType: string, token: string, callback: AsyncCallb
}
});
} catch (err) {
- console.log('setAuthToken exception: ' + JSON.stringify(err));
+ console.log('setAuthToken exception: ' + JSON.stringify(err));
}
```
@@ -1611,10 +1679,12 @@ setAuthToken(name: string, authType: string, token: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager.setAuthToken('LiSi', 'getSocialData', 'xxxx').then(() => {
console.log('setAuthToken successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setAuthToken failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -1652,8 +1722,11 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string, ca
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', (err) => {
+ appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx',
+ (err: BusinessError) => {
if (err) {
console.log('deleteAuthToken failed, error: ' + JSON.stringify(err));
} else {
@@ -1661,7 +1734,7 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string, ca
}
});
} catch (err) {
- console.log('deleteAuthToken exception: ' + JSON.stringify(err));
+ console.log('deleteAuthToken exception: ' + JSON.stringify(err));
}
```
@@ -1700,10 +1773,12 @@ deleteAuthToken(name: string, owner: string, authType: string, token: string): P
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager.deleteAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx').then(() => {
console.log('deleteAuthToken successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('deleteAuthToken failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -1743,8 +1818,11 @@ setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVis
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, (err) => {
+ appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true,
+ (err: BusinessError) => {
if (err) {
console.log('setAuthTokenVisibility failed, error: ' + JSON.stringify(err));
} else {
@@ -1793,10 +1871,12 @@ setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVis
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager.setAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true).then(() => {
console.log('setAuthTokenVisibility successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setAuthTokenVisibility failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -1833,14 +1913,17 @@ checkAuthTokenVisibility(name: string, authType: string, bundleName: string, cal
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', (err, isVisible) => {
- if (err) {
- console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err));
- } else {
- console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible);
- }
- });
+ appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo',
+ (err: BusinessError, isVisible: boolean) => {
+ if (err) {
+ console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err));
+ } else {
+ console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible);
+ }
+ });
} catch (err) {
console.log('checkAuthTokenVisibility exception: ' + JSON.stringify(err));
}
@@ -1880,10 +1963,13 @@ checkAuthTokenVisibility(name: string, authType: string, bundleName: string): Pr
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then((isVisible) => {
+ appAccountManager.checkAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then((
+ isVisible: boolean) => {
console.log('checkAuthTokenVisibility successfully, isVisible: ' + isVisible);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('checkAuthTokenVisibility failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -1918,14 +2004,17 @@ getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array&l
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo', (err, tokenArr) => {
- if (err) {
- console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err));
- } else {
- console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr);
- }
- });
+ appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo',
+ (err: BusinessError, tokenArr: account_appAccount.AuthTokenInfo[]) => {
+ if (err) {
+ console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err));
+ } else {
+ console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr);
+ }
+ });
} catch (err) {
console.log('getAllAuthTokens exception: ' + JSON.stringify(err));
}
@@ -1963,11 +2052,14 @@ getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo').then((tokenArr) => {
- console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr));
- }).catch((err) => {
- console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err));
+ appAccountManager.getAllAuthTokens('LiSi', 'com.example.accountjsdemo').then((
+ tokenArr: account_appAccount.AuthTokenInfo[]) => {
+ console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr));
+ }).catch((err: BusinessError) => {
+ console.log('getAllAuthTokens failed, error: ' + JSON.stringify(err));
});
} catch (err) {
console.log('getAllAuthTokens exception: ' + JSON.stringify(err));
@@ -2002,8 +2094,10 @@ getAuthList(name: string, authType: string, callback: AsyncCallback<Array<
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAuthList('LiSi', 'getSocialData', (err, authList) => {
+ appAccountManager.getAuthList('LiSi', 'getSocialData', (err: BusinessError, authList: string[]) => {
if (err) {
console.log('getAuthList failed, error: ' + JSON.stringify(err));
} else {
@@ -2048,10 +2142,12 @@ getAuthList(name: string, authType: string): Promise<Array<string>>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.getAuthList('LiSi', 'getSocialData').then((authList) => {
+ appAccountManager.getAuthList('LiSi', 'getSocialData').then((authList: string[]) => {
console.log('getAuthList successfully, authList: ' + authList);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAuthList failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -2085,18 +2181,21 @@ getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>):
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
import UIAbility from '@ohos.app.ability.UIAbility';
+ import Want from '@ohos.app.ability.Want';
+ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
export default class EntryAbility extends UIAbility {
- onCreate(want, param) {
- var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
+ onCreate(want: Want, param: AbilityConstant.LaunchParam) {
+ let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
try {
- appAccountManager.getAuthCallback(sessionId, (err, callback) => {
+ appAccountManager.getAuthCallback(sessionId, (err: BusinessError, callback: account_appAccount.AuthCallback) => {
if (err != null) {
console.log('getAuthCallback err: ' + JSON.stringify(err));
return;
}
- var result = {
+ let result = {
accountInfo: {
name: 'Lisi',
owner: 'com.example.accountjsdemo',
@@ -2146,14 +2245,17 @@ getAuthCallback(sessionId: string): Promise<AuthCallback>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
import UIAbility from '@ohos.app.ability.UIAbility';
+ import Want from '@ohos.app.ability.Want';
+ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
export default class EntryAbility extends UIAbility {
- onCreate(want, param) {
- var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
+ onCreate(want: Want, param: AbilityConstant.LaunchParam) {
+ let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
try {
- appAccountManager.getAuthCallback(sessionId).then((callback) => {
- var result = {
+ appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => {
+ let result = {
accountInfo: {
name: 'Lisi',
owner: 'com.example.accountjsdemo',
@@ -2164,7 +2266,7 @@ getAuthCallback(sessionId: string): Promise<AuthCallback>
}
};
callback.onResult(0, result);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAuthCallback err: ' + JSON.stringify(err));
});
} catch (err) {
@@ -2200,14 +2302,17 @@ queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorIn
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo', (err, info) => {
- if (err) {
- console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err));
- } else {
- console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info));
- }
- });
+ appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo',
+ (err: BusinessError, info: account_appAccount.AuthenticatorInfo) => {
+ if (err) {
+ console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err));
+ } else {
+ console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info));
+ }
+ });
} catch (err) {
console.log('queryAuthenticatorInfo exception: ' + JSON.stringify(err));
}
@@ -2244,11 +2349,14 @@ queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo').then((info) => {
- console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info));
- }).catch((err) => {
- console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err));
+ appAccountManager.queryAuthenticatorInfo('com.example.accountjsdemo').then((
+ info: account_appAccount.AuthenticatorInfo) => {
+ console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info));
+ }).catch((err: BusinessError) => {
+ console.log('queryAuthenticatorInfo failed, error: ' + JSON.stringify(err));
});
} catch (err) {
console.log('queryAuthenticatorInfo exception: ' + JSON.stringify(err));
@@ -2286,15 +2394,18 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>, cal
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let labels = ['student'];
try {
- appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels, (err, hasAllLabels) => {
- if (err) {
- console.log('checkAccountLabels failed, error: ' + JSON.stringify(err));
- } else {
- console.log('checkAccountLabels successfully, hasAllLabels: ' + hasAllLabels);
- }
- });
+ appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels1,
+ (err: BusinessError, hasAllLabels: boolean) => {
+ if (err) {
+ console.log('checkAccountLabels failed, error: ' + JSON.stringify(err));
+ } else {
+ console.log('checkAccountLabels successfully, hasAllLabels: ' + hasAllLabels);
+ }
+ });
} catch (err) {
console.log('checkAccountLabels exception: ' + JSON.stringify(err));
}
@@ -2336,11 +2447,14 @@ checkAccountLabels(name: string, owner: string, labels: Array<string>): Pr
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let labels = ['student'];
try {
- appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels).then((hasAllLabels) => {
+ appAccountManager.checkAccountLabels('zhangsan', 'com.example.accountjsdemo', labels).then((
+ hasAllLabels: boolean) => {
console.log('checkAccountLabels successfully: ' + hasAllLabels);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('checkAccountLabels failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -2376,8 +2490,10 @@ deleteCredential(name: string, credentialType: string, callback: AsyncCallback&l
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
- appAccountManager.deleteCredential('zhangsan', 'PIN_SIX', (err) => {
+ appAccountManager.deleteCredential('zhangsan', 'PIN_SIX', (err: BusinessError) => {
if (err) {
console.log('deleteCredential failed, error: ' + JSON.stringify(err));
} else {
@@ -2422,10 +2538,12 @@ deleteCredential(name: string, credentialType: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
try {
appAccountManager.deleteCredential('zhangsan', 'PIN_SIX').then(() => {
console.log('deleteCredential successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('deleteCredential failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -2460,18 +2578,21 @@ selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback&
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let options = {
allowedOwners: [ 'com.example.accountjsdemo' ],
requiredLabels: [ 'student' ]
};
try {
- appAccountManager.selectAccountsByOptions(options, (err, accountArr) => {
- if (err) {
- console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err));
- } else {
- console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr));
- }
- });
+ appAccountManager.selectAccountsByOptions(options5,
+ (err: BusinessError, accountArr: account_appAccount.AppAccountInfo[]) => {
+ if (err) {
+ console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err));
+ } else {
+ console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr));
+ }
+ });
} catch (err) {
console.log('selectAccountsByOptions exception: ' + JSON.stringify(err));
}
@@ -2509,13 +2630,15 @@ selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<App
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let options = {
allowedOwners: ['com.example.accountjsdemo']
};
try {
- appAccountManager.selectAccountsByOptions(options).then((accountArr) => {
+ appAccountManager.selectAccountsByOptions(options).then((accountArr: account_appAccount.AppAccountInfo[]) => {
console.log('selectAccountsByOptions successfully, accountArr: ' + JSON.stringify(accountArr));
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('selectAccountsByOptions failed, error: ' + JSON.stringify(err));
});
} catch (err) {
@@ -2553,13 +2676,15 @@ verifyCredential(name: string, owner: string, callback: AuthCallback): void;
**示例:**
```js
+ import Want from '@ohos.app.ability.Want';
+
try {
appAccountManager.verifyCredential('zhangsan', 'com.example.accountjsdemo', {
- onResult: (resultCode, result) => {
+ onResult: (resultCode: number, result: account_appAccount.AuthResult) => {
console.log('verifyCredential onResult, resultCode: ' + JSON.stringify(resultCode));
console.log('verifyCredential onResult, result: ' + JSON.stringify(result));
},
- onRequestRedirected: (request) => {
+ onRequestRedirected: (request: Want) => {
console.log('verifyCredential onRequestRedirected, request: ' + JSON.stringify(request));
}
});
@@ -2599,17 +2724,19 @@ verifyCredential(name: string, owner: string, options: VerifyCredentialOptions,
**示例:**
```js
+ import Want from '@ohos.app.ability.Want';
+
let options = {
credentialType: 'pin',
credential: '123456'
};
try {
appAccountManager.verifyCredential('zhangsan', 'com.example.accountjsdemo', options, {
- onResult: (resultCode, result) => {
+ onResult: (resultCode: number, result: account_appAccount.AuthResult) => {
console.log('verifyCredential onResult, resultCode: ' + JSON.stringify(resultCode));
console.log('verifyCredential onResult, result: ' + JSON.stringify(result));
},
- onRequestRedirected: (request) => {
+ onRequestRedirected: (request: Want) => {
console.log('verifyCredential onRequestRedirected, request: ' + JSON.stringify(request));
}
});
@@ -2646,13 +2773,15 @@ setAuthenticatorProperties(owner: string, callback: AuthCallback): void;
**示例:**
```js
+ import Want from '@ohos.app.ability.Want';
+
try {
appAccountManager.setAuthenticatorProperties('com.example.accountjsdemo', {
- onResult: (resultCode, result) => {
+ onResult: (resultCode: number, result: account_appAccount.AuthResult) => {
console.log('setAuthenticatorProperties onResult, resultCode: ' + JSON.stringify(resultCode));
console.log('setAuthenticatorProperties onResult, result: ' + JSON.stringify(result));
},
- onRequestRedirected: (request) => {
+ onRequestRedirected: (request: Want) => {
console.log('setAuthenticatorProperties onRequestRedirected, request: ' + JSON.stringify(request));
}
});
@@ -2690,16 +2819,18 @@ setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callbac
**示例:**
```js
+ import Want from '@ohos.app.ability.Want';
+
let options = {
properties: {'prop1': 'value1'}
};
try {
appAccountManager.setAuthenticatorProperties('com.example.accountjsdemo', options, {
- onResult: (resultCode, result) => {
+ onResult: (resultCode: number, result: account_appAccount.AuthResult) => {
console.log('setAuthenticatorProperties onResult, resultCode: ' + JSON.stringify(resultCode));
console.log('setAuthenticatorProperties onResult, result: ' + JSON.stringify(result));
},
- onRequestRedirected: (request) => {
+ onRequestRedirected: (request: Want) => {
console.log('setAuthenticatorProperties onRequestRedirected, request: ' + JSON.stringify(request));
}
});
@@ -2732,7 +2863,9 @@ addAccount(name: string, callback: AsyncCallback<void>): void
**示例:**
```js
- appAccountManager.addAccount('WangWu', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.addAccount('WangWu', (err: BusinessError) => {
console.log('addAccount err: ' + JSON.stringify(err));
});
```
@@ -2759,7 +2892,9 @@ addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>)
**示例:**
```js
- appAccountManager.addAccount('LiSi', 'token101', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.addAccount('LiSi', 'token101', (err: BusinessError) => {
console.log('addAccount err: ' + JSON.stringify(err));
});
```
@@ -2791,9 +2926,11 @@ addAccount(name: string, extraInfo?: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.addAccount('LiSi', 'token101').then(()=> {
console.log('addAccount Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('addAccount err: ' + JSON.stringify(err));
});
```
@@ -2822,14 +2959,15 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+ import Want from '@ohos.app.ability.Want';
-
- function onResultCallback(code, result) {
+ function onResultCallback(code: number, result: { [key: string]: any }) {
console.log('resultCode: ' + code);
console.log('result: ' + JSON.stringify(result));
}
- function onRequestRedirectedCallback(request) {
+ function onRequestRedirectedCallback(request: Want) {
let wantInfo = {
deviceId: '',
bundleName: 'com.example.accountjsdemo',
@@ -2838,7 +2976,7 @@ addAccountImplicitly(owner: string, authType: string, options: {[key: string]: a
}
this.context.startAbility(wantInfo).then(() => {
console.log('startAbility successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('startAbility err: ' + JSON.stringify(err));
})
}
@@ -2871,7 +3009,9 @@ deleteAccount(name: string, callback: AsyncCallback<void>): void
**示例:**
```js
- appAccountManager.deleteAccount('ZhaoLiu', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.deleteAccount('ZhaoLiu', (err: BusinessError) => {
console.log('deleteAccount err: ' + JSON.stringify(err));
});
```
@@ -2903,9 +3043,11 @@ deleteAccount(name: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.deleteAccount('ZhaoLiu').then(() => {
console.log('deleteAccount Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('deleteAccount err: ' + JSON.stringify(err));
});
```
@@ -2932,7 +3074,9 @@ disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<vo
**示例:**
```js
- appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err: BusinessError) => {
console.log('disableAppAccess err: ' + JSON.stringify(err));
});
```
@@ -2965,9 +3109,11 @@ disableAppAccess(name: string, bundleName: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.disableAppAccess('ZhangSan', 'com.example.accountjsdemo').then(() => {
console.log('disableAppAccess Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('disableAppAccess err: ' + JSON.stringify(err));
});
```
@@ -2995,7 +3141,9 @@ enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<voi
**示例:**
```js
- appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo', (err: BusinessError) => {
console.log('enableAppAccess: ' + JSON.stringify(err));
});
```
@@ -3028,9 +3176,11 @@ enableAppAccess(name: string, bundleName: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.enableAppAccess('ZhangSan', 'com.example.accountjsdemo').then(() => {
console.log('enableAppAccess Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('enableAppAccess err: ' + JSON.stringify(err));
});
```
@@ -3059,7 +3209,9 @@ checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>):
**示例:**
```js
- appAccountManager.checkAppAccountSyncEnable('ZhangSan', (err, result) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.checkAppAccountSyncEnable('ZhangSan', (err: BusinessError, result: boolean) => {
console.log('checkAppAccountSyncEnable err: ' + JSON.stringify(err));
console.log('checkAppAccountSyncEnable result: ' + result);
});
@@ -3094,9 +3246,11 @@ checkAppAccountSyncEnable(name: string): Promise<boolean>
**示例:**
```js
- appAccountManager.checkAppAccountSyncEnable('ZhangSan').then((data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.checkAppAccountSyncEnable('ZhangSan').then((data: boolean) => {
console.log('checkAppAccountSyncEnable, result: ' + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('checkAppAccountSyncEnable err: ' + JSON.stringify(err));
});
```
@@ -3125,7 +3279,9 @@ setAccountCredential(name: string, credentialType: string, credential: string,ca
**示例:**
```js
- appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001', (err: BusinessError) => {
console.log('setAccountCredential err: ' + JSON.stringify(err));
});
```
@@ -3159,9 +3315,11 @@ setAccountCredential(name: string, credentialType: string, credential: string):
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.setAccountCredential('ZhangSan', 'credentialType001', 'credential001').then(() => {
console.log('setAccountCredential Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setAccountCredential err: ' + JSON.stringify(err));
});
```
@@ -3190,7 +3348,9 @@ setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<
**示例:**
```js
- appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002', (err: BusinessError) => {
console.log('setAccountExtraInfo err: ' + JSON.stringify(err));
});
```
@@ -3224,9 +3384,11 @@ setAccountExtraInfo(name: string, extraInfo: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.setAccountExtraInfo('ZhangSan', 'Tk002').then(() => {
console.log('setAccountExtraInfo Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setAccountExtraInfo err: ' + JSON.stringify(err));
});
```
@@ -3256,7 +3418,9 @@ setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback
**示例:**
```js
- appAccountManager.setAppAccountSyncEnable('ZhangSan', true, (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.setAppAccountSyncEnable('ZhangSan', true, (err: BusinessError) => {
console.log('setAppAccountSyncEnable err: ' + JSON.stringify(err));
});
```
@@ -3291,9 +3455,11 @@ setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager .setAppAccountSyncEnable('ZhangSan', true).then(() => {
console.log('setAppAccountSyncEnable Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setAppAccountSyncEnable err: ' + JSON.stringify(err));
});
```
@@ -3323,7 +3489,9 @@ setAssociatedData(name: string, key: string, value: string, callback: AsyncCallb
**示例:**
```js
- appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001', (err: BusinessError) => {
console.log('setAssociatedData err: ' + JSON.stringify(err));
});
```
@@ -3358,9 +3526,11 @@ setAssociatedData(name: string, key: string, value: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.setAssociatedData('ZhangSan', 'k001', 'v001').then(() => {
console.log('setAssociatedData Success');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setAssociatedData err: ' + JSON.stringify(err));
});
```
@@ -3388,7 +3558,9 @@ getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>&
**示例:**
```js
- appAccountManager.getAllAccessibleAccounts((err, data)=>{
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAllAccessibleAccounts((err: BusinessError, data: account_appAccount.AppAccountInfo[])=>{
console.debug('getAllAccessibleAccounts err: ' + JSON.stringify(err));
console.debug('getAllAccessibleAccounts data: ' + JSON.stringify(data));
});
@@ -3417,9 +3589,11 @@ getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>>
**示例:**
```js
- appAccountManager.getAllAccessibleAccounts().then((data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAllAccessibleAccounts().then((data: account_appAccount.AppAccountInfo[]) => {
console.log('getAllAccessibleAccounts: ' + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAllAccessibleAccounts err: ' + JSON.stringify(err));
});
```
@@ -3448,8 +3622,10 @@ getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
const selfBundle = 'com.example.actsgetallaaccounts';
- appAccountManager.getAllAccounts(selfBundle, (err, data)=>{
+ appAccountManager.getAllAccounts(selfBundle, (err: BusinessError, data: account_appAccount.AppAccountInfo[])=>{
console.debug('getAllAccounts err: ' + JSON.stringify(err));
console.debug('getAllAccounts data:' + JSON.stringify(data));
});
@@ -3484,10 +3660,12 @@ getAllAccounts(owner: string): Promise<Array<AppAccountInfo>>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
const selfBundle = 'com.example.actsgetallaaccounts';
- appAccountManager.getAllAccounts(selfBundle).then((data) => {
+ appAccountManager.getAllAccounts(selfBundle).then((data: account_appAccount.AppAccountInfo[]) => {
console.log('getAllAccounts: ' + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAllAccounts err: ' + JSON.stringify(err));
});
```
@@ -3515,7 +3693,9 @@ getAccountCredential(name: string, credentialType: string, callback: AsyncCallba
**示例:**
```js
- appAccountManager.getAccountCredential('ZhangSan', 'credentialType001', (err, result) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAccountCredential('ZhangSan', 'credentialType001', (err: BusinessError, result: string) => {
console.log('getAccountCredential err: ' + JSON.stringify(err));
console.log('getAccountCredential result: ' + result);
});
@@ -3549,9 +3729,11 @@ getAccountCredential(name: string, credentialType: string): Promise<string>
**示例:**
```js
- appAccountManager.getAccountCredential('ZhangSan', 'credentialType001').then((data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAccountCredential('ZhangSan', 'credentialType001').then((data: string) => {
console.log('getAccountCredential, result: ' + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAccountCredential err: ' + JSON.stringify(err));
});
```
@@ -3578,7 +3760,9 @@ getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void
**示例:**
```js
- appAccountManager.getAccountExtraInfo('ZhangSan', (err, result) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAccountExtraInfo('ZhangSan', (err: BusinessError, result: string) => {
console.log('getAccountExtraInfo err: ' + JSON.stringify(err));
console.log('getAccountExtraInfo result: ' + result);
});
@@ -3611,9 +3795,11 @@ getAccountExtraInfo(name: string): Promise<string>
**示例:**
```js
- appAccountManager.getAccountExtraInfo('ZhangSan').then((data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAccountExtraInfo('ZhangSan').then((data: string) => {
console.log('getAccountExtraInfo, result: ' + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAccountExtraInfo err: ' + JSON.stringify(err));
});
```
@@ -3641,7 +3827,9 @@ getAssociatedData(name: string, key: string, callback: AsyncCallback<string&g
**示例:**
```js
- appAccountManager.getAssociatedData('ZhangSan', 'k001', (err, result) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAssociatedData('ZhangSan', 'k001', (err: BusinessError, result: string) => {
console.log('getAssociatedData err: ' + JSON.stringify(err));
console.log('getAssociatedData result: ' + result);
});
@@ -3675,9 +3863,11 @@ getAssociatedData(name: string, key: string): Promise<string>
**示例:**
```js
- appAccountManager.getAssociatedData('ZhangSan', 'k001').then((data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAssociatedData('ZhangSan', 'k001').then((data: string) => {
console.log('getAssociatedData: ' + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAssociatedData err: ' + JSON.stringify(err));
});
```
@@ -3705,7 +3895,7 @@ on(type: 'change', owners: Array<string>, callback: Callback<Array<A
**示例:**
```js
- function changeOnCallback(data){
+ function changeOnCallback(data: account_appAccount.AppAccountInfo[]){
console.debug('receive change data:' + JSON.stringify(data));
}
try{
@@ -3738,9 +3928,9 @@ off(type: 'change', callback?: Callback<Array<AppAccountInfo>>): voi
**示例:**
```js
- function changeOnCallback(data){
+ function changeOnCallback(data: account_appAccount.AppAccountInfo[]){
console.debug('receive change data: ' + JSON.stringify(data));
- appAccountManager.off('change', function(){
+ appAccountManager.off('change', () => {
console.debug('off finish');
})
}
@@ -3777,12 +3967,15 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri
**示例:**
```js
- function onResultCallback(code, result) {
+ import { BusinessError } from '@ohos.base';
+ import Want from '@ohos.app.ability.Want';
+
+ function onResultCallback(code: number, result: { [key: string]: Object }) {
console.log('resultCode: ' + code);
console.log('result: ' + JSON.stringify(result));
}
- function onRequestRedirectedCallback(request) {
+ function onRequestRedirectedCallback(request: Want) {
let wantInfo = {
deviceId: '',
bundleName: 'com.example.accountjsdemo',
@@ -3791,7 +3984,7 @@ authenticate(name: string, owner: string, authType: string, options: {[key: stri
}
this.context.startAbility(wantInfo).then(() => {
console.log('startAbility successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('startAbility err: ' + JSON.stringify(err));
})
}
@@ -3826,10 +4019,13 @@ getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCall
**示例:**
```js
- appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', (err, data) => {
- console.log('getOAuthToken err: ' + JSON.stringify(err));
- console.log('getOAuthToken token: ' + data);
- });
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData',
+ (err: BusinessError, data: string) => {
+ console.log('getOAuthToken err: ' + JSON.stringify(err));
+ console.log('getOAuthToken token: ' + data);
+ });
```
### getOAuthToken(deprecated)
@@ -3861,9 +4057,11 @@ getOAuthToken(name: string, owner: string, authType: string): Promise<string&
**示例:**
```js
- appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData').then((data: string) => {
console.log('getOAuthToken token: ' + data);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getOAuthToken err: ' + JSON.stringify(err));
});
```
@@ -3892,7 +4090,9 @@ setOAuthToken(name: string, authType: string, token: string, callback: AsyncCall
**示例:**
```js
- appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx', (err) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx', (err: BusinessError) => {
console.log('setOAuthToken err: ' + JSON.stringify(err));
});
```
@@ -3926,9 +4126,11 @@ setOAuthToken(name: string, authType: string, token: string): Promise<void>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.setOAuthToken('LiSi', 'getSocialData', 'xxxx').then(() => {
console.log('setOAuthToken successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setOAuthToken err: ' + JSON.stringify(err));
});
```
@@ -3958,9 +4160,12 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string, c
**示例:**
```js
- appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx', (err) => {
- console.log('deleteOAuthToken err: ' + JSON.stringify(err));
- });
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx',
+ (err: BusinessError) => {
+ console.log('deleteOAuthToken err: ' + JSON.stringify(err));
+ });
```
### deleteOAuthToken(deprecated)
@@ -3993,9 +4198,11 @@ deleteOAuthToken(name: string, owner: string, authType: string, token: string):
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.deleteOAuthToken('LiSi', 'com.example.accountjsdemo', 'getSocialData', 'xxxxx').then(() => {
console.log('deleteOAuthToken successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('deleteOAuthToken err: ' + JSON.stringify(err));
});
```
@@ -4025,9 +4232,12 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi
**示例:**
```js
- appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true, (err) => {
- console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err));
- });
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true,
+ (err: BusinessError) => {
+ console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err));
+ });
```
### setOAuthTokenVisibility(deprecated)
@@ -4060,9 +4270,11 @@ setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVi
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
appAccountManager.setOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', true).then(() => {
console.log('setOAuthTokenVisibility successfully');
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err));
});
```
@@ -4091,10 +4303,13 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, ca
**示例:**
```js
- appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo', (err, data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo',
+ (err: BusinessError, data: boolean) => {
console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err));
console.log('checkOAuthTokenVisibility isVisible: ' + data);
- });
+ });
```
### checkOAuthTokenVisibility(deprecated)
@@ -4126,10 +4341,13 @@ checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): P
**示例:**
```js
- appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then((data) => {
- console.log('checkOAuthTokenVisibility isVisible: ' + data);
- }).catch((err) => {
- console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err));
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.checkOAuthTokenVisibility('LiSi', 'getSocialData', 'com.example.accountjsdemo').then((
+ data: boolean) => {
+ console.log('checkOAuthTokenVisibility isVisible: ' + data);
+ }).catch((err: BusinessError) => {
+ console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err));
});
```
@@ -4156,10 +4374,13 @@ getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array&
**示例:**
```js
- appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo', (err, data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo',
+ (err: BusinessError, data: account_appAccount.OAuthTokenInfo[]) => {
console.log('getAllOAuthTokens err: ' + JSON.stringify(err));
console.log('getAllOAuthTokens data: ' + JSON.stringify(data));
- });
+ });
```
### getAllOAuthTokens(deprecated)
@@ -4190,10 +4411,13 @@ getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenIn
**示例:**
```js
- appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo').then((data) => {
- console.log('getAllOAuthTokens data: ' + JSON.stringify(data));
- }).catch((err) => {
- console.log('getAllOAuthTokens err: ' + JSON.stringify(err));
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAllOAuthTokens('LiSi', 'com.example.accountjsdemo').then((
+ data: account_appAccount.OAuthTokenInfo[]) => {
+ console.log('getAllOAuthTokens data: ' + JSON.stringify(data));
+ }).catch((err: BusinessError) => {
+ console.log('getAllOAuthTokens err: ' + JSON.stringify(err));
});
```
@@ -4220,7 +4444,9 @@ getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<
**示例:**
```js
- appAccountManager.getOAuthList('LiSi', 'getSocialData', (err, data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getOAuthList('LiSi', 'getSocialData', (err: BusinessError, data: string[]) => {
console.log('getOAuthList err: ' + JSON.stringify(err));
console.log('getOAuthList data: ' + JSON.stringify(data));
});
@@ -4254,9 +4480,11 @@ getOAuthList(name: string, authType: string): Promise<Array<string>>
**示例:**
```js
- appAccountManager.getOAuthList('LiSi', 'getSocialData').then((data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getOAuthList('LiSi', 'getSocialData').then((data: string[]) => {
console.log('getOAuthList data: ' + JSON.stringify(data));
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getOAuthList err: ' + JSON.stringify(err));
});
```
@@ -4283,22 +4511,26 @@ getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<Authentic
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
import UIAbility from '@ohos.app.ability.UIAbility';
+ import Want from '@ohos.app.ability.Want';
+ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
export default class EntryAbility extends UIAbility {
- onCreate(want, param) {
- var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
- appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => {
- if (err.code != account_appAccount.ResultCode.SUCCESS) {
- console.log('getAuthenticatorCallback err: ' + JSON.stringify(err));
- return;
- }
- var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi',
- [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo',
- [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData',
- [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'};
- callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
- });
+ onCreate(want: Want, param: AbilityConstant.LaunchParam) {
+ let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
+ appAccountManager.getAuthenticatorCallback(sessionId,
+ (err: BusinessError, callback: account_appAccount.AuthenticatorCallback) => {
+ if (err.code != account_appAccount.ResultCode.SUCCESS) {
+ console.log('getAuthenticatorCallback err: ' + JSON.stringify(err));
+ return;
+ }
+ let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi',
+ [account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo',
+ [account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData',
+ [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'};
+ callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
+ });
}
}
```
@@ -4330,18 +4562,22 @@ getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback>
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
import UIAbility from '@ohos.app.ability.UIAbility';
+ import Want from '@ohos.app.ability.Want';
+ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
export default class EntryAbility extends UIAbility {
- onCreate(want, param) {
- var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
- appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => {
- var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi',
+ onCreate(want: Want, param: AbilityConstant.LaunchParam) {
+ let sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID];
+ appAccountManager.getAuthenticatorCallback(sessionId).then((
+ callback: account_appAccount.AuthenticatorCallback) => {
+ let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi',
[account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo',
[account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData',
[account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAuthenticatorCallback err: ' + JSON.stringify(err));
});
}
@@ -4370,10 +4606,13 @@ getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo
**示例:**
```js
- appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo', (err, data) => {
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo',
+ (err: BusinessError, data: account_appAccount.AuthenticatorInfo) => {
console.log('getAuthenticatorInfo err: ' + JSON.stringify(err));
console.log('getAuthenticatorInfo data: ' + JSON.stringify(data));
- });
+ });
```
### getAuthenticatorInfo(deprecated)
@@ -4403,10 +4642,13 @@ getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo>
**示例:**
```js
- appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo').then((data) => {
- console.log('getAuthenticatorInfo: ' + JSON.stringify(data));
- }).catch((err) => {
- console.log('getAuthenticatorInfo err: ' + JSON.stringify(err));
+ import { BusinessError } from '@ohos.base';
+
+ appAccountManager.getAuthenticatorInfo('com.example.accountjsdemo').then((
+ data: account_appAccount.AuthenticatorInfo) => {
+ console.log('getAuthenticatorInfo: ' + JSON.stringify(data));
+ }).catch((err: BusinessError) => {
+ console.log('getAuthenticatorInfo err: ' + JSON.stringify(err));
});
```
@@ -4608,10 +4850,12 @@ onResult: (code: number, result?: AuthResult) => void
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let appAccountManager = account_appAccount.createAppAccountManager();
- var sessionId = '1234';
- appAccountManager.getAuthCallback(sessionId).then((callback) => {
- var result = {
+ let sessionId = '1234';
+ appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => {
+ let result = {
accountInfo: {
name: 'Lisi',
owner: 'com.example.accountjsdemo',
@@ -4622,7 +4866,7 @@ onResult: (code: number, result?: AuthResult) => void
}
};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAuthCallback err: ' + JSON.stringify(err));
});
```
@@ -4645,15 +4889,17 @@ onRequestRedirected: (request: Want) => void
```js
class MyAuthenticator extends account_appAccount.Authenticator {
- createAccountImplicitly(options, callback) {
+ createAccountImplicitly(
+ options: account_appAccount.CreateAccountImplicitlyOptions, callback: account_appAccount.AuthCallback) {
callback.onRequestRedirected({
bundleName: 'com.example.accountjsdemo',
abilityName: 'com.example.accountjsdemo.LoginAbility',
});
}
- auth(name, authType, options, callback) {
- var result = {
+ auth(name: string, authType: string,
+ options: { [key: string]: Object }, callback: account_appAccount.AuthCallback) {
+ let result = {
accountInfo: {
name: 'Lisi',
owner: 'com.example.accountjsdemo',
@@ -4679,11 +4925,13 @@ onRequestContinued?: () => void
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let appAccountManager = account_appAccount.createAppAccountManager();
- var sessionId = '1234';
- appAccountManager.getAuthCallback(sessionId).then((callback) => {
+ let sessionId = '1234';
+ appAccountManager.getAuthCallback(sessionId).then((callback: account_appAccount.AuthCallback) => {
callback.onRequestContinued();
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAuthCallback err: ' + JSON.stringify(err));
});
```
@@ -4714,15 +4962,17 @@ onResult: (code: number, result: {[key: string]: any}) => void
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let appAccountManager = account_appAccount.createAppAccountManager();
- var sessionId = '1234';
- appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => {
- var result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi',
+ let sessionId = '1234';
+ appAccountManager.getAuthenticatorCallback(sessionId).then((callback: account_appAccount.AuthenticatorCallback) => {
+ let result = {[account_appAccount.Constants.KEY_NAME]: 'LiSi',
[account_appAccount.Constants.KEY_OWNER]: 'com.example.accountjsdemo',
[account_appAccount.Constants.KEY_AUTH_TYPE]: 'getSocialData',
[account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAuthenticatorCallback err: ' + JSON.stringify(err));
});
```
@@ -4745,15 +4995,17 @@ onRequestRedirected: (request: Want) => void
```js
class MyAuthenticator extends account_appAccount.Authenticator {
- addAccountImplicitly(authType, callerBundleName, options, callback) {
+ addAccountImplicitly(authType: string, callerBundleName: string,
+ options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) {
callback.onRequestRedirected({
bundleName: 'com.example.accountjsdemo',
abilityName: 'com.example.accountjsdemo.LoginAbility',
});
}
- authenticate(name, authType, callerBundleName, options, callback) {
- var result = {[account_appAccount.Constants.KEY_NAME]: name,
+ authenticate(name: string, authType: string, callerBundleName: string,
+ options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) {
+ let result = {[account_appAccount.Constants.KEY_NAME]: name,
[account_appAccount.Constants.KEY_AUTH_TYPE]: authType,
[account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
@@ -4772,11 +5024,13 @@ onRequestContinued?: () => void
**示例:**
```js
+ import { BusinessError } from '@ohos.base';
+
let appAccountManager = account_appAccount.createAppAccountManager();
- var sessionId = '1234';
- appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => {
+ let sessionId = '1234';
+ appAccountManager.getAuthenticatorCallback(sessionId).then((callback: account_appAccount.AuthenticatorCallback) => {
callback.onRequestContinued();
- }).catch((err) => {
+ }).catch((err: BusinessError) => {
console.log('getAuthenticatorCallback err: ' + JSON.stringify(err));
});
```
@@ -4934,48 +5188,53 @@ getRemoteObject(): rpc.RemoteObject;
**示例:**
```js
+ import rpc from '@ohos.rpc';
+
class MyAuthenticator extends account_appAccount.Authenticator {
- addAccountImplicitly(authType, callerBundleName, options, callback) {
- callback.onRequestRedirected({
- bundleName: 'com.example.accountjsdemo',
- abilityName: 'com.example.accountjsdemo.LoginAbility',
- });
+ addAccountImplicitly(authType: string, callerBundleName: string,
+ options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) {
+ callback.onRequestRedirected({
+ bundleName: 'com.example.accountjsdemo',
+ abilityName: 'com.example.accountjsdemo.LoginAbility',
+ });
}
- authenticate(name, authType, callerBundleName, options, callback) {
- var result = {[account_appAccount.Constants.KEY_NAME]: name,
- [account_appAccount.Constants.KEY_AUTH_TYPE]: authType,
- [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'};
- callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
+ authenticate(name: string, authType: string, callerBundleName: string,
+ options: { [key: string]: Object }, callback: account_appAccount.AuthenticatorCallback) {
+ let result = {[account_appAccount.Constants.KEY_NAME]: name,
+ [account_appAccount.Constants.KEY_AUTH_TYPE]: authType,
+ [account_appAccount.Constants.KEY_TOKEN]: 'xxxxxx'};
+ callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}
- verifyCredential(name, options, callback) {
- callback.onRequestRedirected({
- bundleName: 'com.example.accountjsdemo',
- abilityName: 'com.example.accountjsdemo.VerifyAbility',
- parameters: {
- name: name
- }
- });
+ verifyCredential(name: string,
+ options: account_appAccount.VerifyCredentialOptions, callback: account_appAccount.AuthCallback) {
+ callback.onRequestRedirected({
+ bundleName: 'com.example.accountjsdemo',
+ abilityName: 'com.example.accountjsdemo.VerifyAbility',
+ parameters: {
+ name: name
+ }
+ });
}
- setProperties(options, callback) {
+ setProperties(options: account_appAccount.SetPropertiesOptions, callback: account_appAccount.AuthCallback) {
callback.onResult(account_appAccount.ResultCode.SUCCESS, {});
}
- checkAccountLabels(name, labels, callback) {
- var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false};
+ checkAccountLabels(name: string, labels: string[], callback: account_appAccount.AuthCallback) {
+ let result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}
- checkAccountRemovable(name, callback) {
- var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true};
+ checkAccountRemovable(name: string, callback: account_appAccount.AuthCallback) {
+ let result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true};
callback.onResult(account_appAccount.ResultCode.SUCCESS, result);
}
}
- var authenticator = null;
+ let authenticator = null;
export default {
- onConnect(want) {
+ onConnect(want): rpc.RemoteObject {
authenticator = new MyAuthenticator();
return authenticator.getRemoteObject();
}
diff --git a/zh-cn/application-dev/reference/apis/js-apis-appControl.md b/zh-cn/application-dev/reference/apis/js-apis-appControl.md
index 03286aaa8a0cabe11779d0755aefe5802dbf2eb3..a0a7b55af9f4fd4e745d57d6d11bb97942db3ecb 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-appControl.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-appControl.md
@@ -81,9 +81,9 @@ setDisposedStatus(appId: string, disposedWant: Want, callback: AsyncCallback\ appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
+| appId | string | 是 | 需要设置处置的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
| disposedWant | Want | 是 | 对应用的处置意图。 |
-| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功,err为undefined,否则为错误对象。 |
+| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功,err为null,否则为错误对象。 |
**错误码:**
@@ -112,6 +112,49 @@ try {
}
```
+## appControl.setDisposedStatusSync
+
+setDisposedStatusSync(appId: string, disposedWant: Want): void;
+
+以同步方法设置应用的处置状态。成功返回null,失败抛出对应异常。
+
+**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl
+
+**系统API:** 此接口为系统接口。
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ----------- | ------------------------------- | ---- | --------------------------------------- |
+| appId | string | 是 | 需要设置处置的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
+| disposedWant | Want | 是 | 对应用的处置意图。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| ------ | -------------------------------------- |
+| 17700005 | The specified app ID is empty string. |
+
+**示例:**
+
+```ts
+import appControl from '@ohos.bundle.appControl';
+import Want from '@ohos.app.ability.Want';
+
+let appId: string = "com.example.myapplication_xxxxx";
+let want: Want = {bundleName: 'com.example.myapplication'};
+
+try {
+ appControl.setDisposedStatusSync(appId, want);
+} catch (error) {
+ console.error('setDisposedStatusSync failed ' + error.message);
+}
+```
+
## appControl.getDisposedStatus
getDisposedStatus(appId: string): Promise\;
@@ -128,7 +171,7 @@ getDisposedStatus(appId: string): Promise\;
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------- |
-| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
+| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
**返回值:**
@@ -177,8 +220,8 @@ getDisposedStatus(appId: string, callback: AsyncCallback\): void;
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------- |
-| appId | string | 是 | 要查询的应用的appId
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
-| callback | AsyncCallback\ | 是 | 回调函数。当获取应用的处置状态成功时,err为undefined,data为获取到的处置状态;否则为错误对象。 |
+| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
+| callback | AsyncCallback\ | 是 | 回调函数。当获取应用的处置状态成功时,err为null,data为获取到的处置状态;否则为错误对象。 |
**错误码:**
@@ -206,6 +249,54 @@ try {
}
```
+## appControl.getDisposedStatusSync
+
+getDisposedStatusSync(appId: string): Want;
+
+以同步方法获取指定应用已设置的处置状态。成功返回应用的处置状态,失败抛出对应异常。
+
+**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl
+
+**系统API:** 此接口为系统接口。
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ----------- | ------ | ---- | --------------------------------------- |
+| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ------------------------- | ------------------ |
+| Want | 返回应用的处置状态。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| ------ | -------------------------------------- |
+| 17700005 | The specified app ID is empty string. |
+
+**示例:**
+
+```ts
+import appControl from '@ohos.bundle.appControl';
+import Want from '@ohos.app.ability.Want';
+
+let appId: string = "com.example.myapplication_xxxxx";
+let want: Want;
+
+try {
+ want = appControl.getDisposedStatusSync(appId);
+} catch (error) {
+ console.error('getDisposedStatusSync failed ' + error.message);
+}
+```
+
## appControl.deleteDisposedStatus
deleteDisposedStatus(appId: string): Promise\
@@ -222,7 +313,7 @@ deleteDisposedStatus(appId: string): Promise\
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------- |
-| appId | string | 是 | 要删除处置状态的应用的appId
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
+| appId | string | 是 | 要删除处置状态的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
**返回值:**
@@ -272,7 +363,7 @@ deleteDisposedStatus(appId: string, callback: AsyncCallback\) : void
| 参数名 | 类型 | 必填 | 说明 |
| ----------- | ------ | ---- | --------------------------------------- |
| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
-| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功时,err返回undefined。否则回调函数返回具体错误对象。 |
+| callback | AsyncCallback\ | 是 | 回调函数,当设置处置状态成功时,err返回null。否则回调函数返回具体错误对象。 |
**错误码:**
@@ -299,6 +390,46 @@ try {
}
```
+## appControl.deleteDisposedStatusSync
+
+deleteDisposedStatusSync(appId: string) : void
+
+以同步方法删除应用的处置状态。成功返回null,失败抛出对应异常。
+
+**需要权限:** ohos.permission.MANAGE_DISPOSED_APP_STATUS
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.AppControl
+
+**系统API:** 此接口为系统接口。
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ----------- | ------ | ---- | --------------------------------------- |
+| appId | string | 是 | 要查询的应用的appId。
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,获取方法参见[获取应用的appId](#获取应用的appid)。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| ------ | -------------------------------------- |
+| 17700005 | The specified app ID is empty string. |
+
+**示例:**
+
+```ts
+import appControl from '@ohos.bundle.appControl';
+
+let appId: string = "com.example.myapplication_xxxxx";
+
+try {
+ appControl.deleteDisposedStatusSync(appId);
+} catch (error) {
+ console.error('deleteDisposedStatusSync failed ' + error.message);
+}
+```
+
## 获取应用的appId
appId是应用的唯一标识,由应用Bundle名称和签名信息决定,可以通过[getBundleInfo](js-apis-bundleManager.md#bundlemanagergetbundleinfo)接口获取。
diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
index 15bc8eed451e45318577a284976516647700288e..d988832ce62ba906765916f4141f5fa46bfe5f51 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-application-dataShareExtensionAbility.md
@@ -50,17 +50,17 @@ let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- onCreate(want, callback) {
+ onCreate(want: Want, callback: Function) {
rdb.getRdbStore(this.context, {
name: DB_NAME,
securityLevel: rdb.SecurityLevel.S1
- }, function (err, data) {
+ }, (err, data) => {
console.info(`getRdbStore done, data : ${data}`);
rdbStore = data;
- rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
+ rdbStore.executeSql(DDL_TBL_CREATE, [], (err) => {
console.error(`executeSql done, error message : ${err}`);
});
if (callback) {
@@ -91,21 +91,22 @@ insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<numbe
```ts
import rdb from '@ohos.data.relationalStore';
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- insert(uri, valueBucket, callback) {
+ insert(uri: string, valueBucket: ValuesBucket, callback: Function) {
if (valueBucket === null) {
console.error('invalid valueBuckets');
return;
}
- rdbStore.insert(TBL_NAME, valueBucket, function (err, ret) {
+ rdbStore.insert(TBL_NAME, valueBucket, (err, ret) => {
console.info(`callback ret: ${ret}`);
if (callback !== undefined) {
callback(err, ret);
@@ -136,20 +137,22 @@ update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueB
```ts
import rdb from '@ohos.data.relationalStore';
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- update(uri, predicates, valueBucket, callback) {
+ update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
- rdbStore.update(TBL_NAME, valueBucket, predicates, function (err, ret) {
+ rdbStore.update(TBL_NAME, valueBucket, predicates, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
@@ -178,20 +181,21 @@ delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callba
```ts
import rdb from '@ohos.data.relationalStore';
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- delete(uri, predicates, callback) {
+ delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
- rdbStore.delete(TBL_NAME, predicates, function (err, ret) {
+ rdbStore.delete(TBL_NAME, predicates, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
@@ -221,20 +225,21 @@ query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns
```ts
import rdb from '@ohos.data.relationalStore';
+import dataSharePredicates from '@ohos.data.dataSharePredicates';
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- query(uri, predicates, columns, callback) {
+ query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array, callback: Function) {
if (predicates === null || predicates === undefined) {
return;
}
- rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) {
+ rdbStore.query(TBL_NAME, predicates, columns, (err, resultSet) => {
if (resultSet !== undefined) {
console.info(`resultSet.rowCount: ${resultSet.rowCount}`);
}
@@ -266,21 +271,22 @@ batchInsert?(uri: string, valueBuckets: Array<ValuesBucket>, callback: Asy
```ts
import rdb from '@ohos.data.relationalStore';
+import { ValuesBucket } from '@ohos.data.ValuesBucket'
let DB_NAME = 'DB00.db';
let TBL_NAME = 'TBL00';
let DDL_TBL_CREATE = 'CREATE TABLE IF NOT EXISTS '
+ TBL_NAME
+ ' (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)';
-let rdbStore;
+let rdbStore: relationalStore.RdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
- batchInsert(uri, valueBuckets, callback) {
+ batchInsert(uri: string, valueBuckets: Array, callback: Function) {
if (valueBuckets === null || valueBuckets.length === undefined) {
console.error('invalid valueBuckets');
return;
}
- rdbStore.batchInsert(TBL_NAME, valueBuckets, function (err, ret) {
+ rdbStore.batchInsert(TBL_NAME, valueBuckets, (err, ret) => {
if (callback !== undefined) {
callback(err, ret);
}
@@ -308,11 +314,17 @@ normalizeUri?(uri: string, callback: AsyncCallback<string>): void
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
- normalizeUri(uri, callback) {
- let err = {'code':0};
- let ret = `normalize: ${uri}`;
- callback(err, ret);
- }
+ normalizeUri(uri: string, callback: Function) {
+ let key = 'code';
+ let value = 0;
+ let err: BusinessError = {
+ code: value,
+ name: key,
+ message: key
+ };
+ let ret: string = `normalize: ${uri}`;
+ callback(err, ret);
+ }
};
```
@@ -335,10 +347,16 @@ denormalizeUri?(uri: string, callback: AsyncCallback<string>): void
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
- denormalizeUri(uri, callback) {
- let err = {'code':0};
- let ret = `denormalize ${uri}`;
- callback(err, ret);
- }
+ denormalizeUri(uri: string, callback: Function) {
+ let key = 'code';
+ let value = 0;
+ let err: BusinessError = {
+ code: value,
+ name: key,
+ message: key
+ };
+ let ret = `denormalize ${uri}`;
+ callback(err, ret);
+ }
};
```
diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md
index f483bde4cbcf7d38e91f6a05814d31db24dd3690..fe1b4d6237abab97c9259bef1cd5cae8f85f8030 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-UIContext.md
@@ -214,7 +214,7 @@ struct AnimateToExample {
### showAlertDialog
-showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons): void
+showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButtons | AlertDialogParamWithOptions): void
显示警告弹窗组件,可设置文本内容与响应回调。
@@ -224,7 +224,8 @@ showAlertDialog(options: AlertDialogParamWithConfirm | AlertDialogParamWithButto
| 参数名 | 类型 | 必填 | 说明 |
| ---- | --------------- | -------- | -------- |
-| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons对象说明) | 是 | 定义并显示AlertDialog组件。 |
+| options | [AlertDialogParamWithConfirm](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithconfirm对象说明) \| [AlertDialogParamWithButtons](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithbuttons对象说明) \| [AlertDialogParamWithOptions](../arkui-ts/ts-methods-alert-dialog-box.md#alertdialogparamwithoptions10对象说明) | 是 | 定义并显示AlertDialog组件。 |
+
**示例:**
@@ -1201,7 +1202,7 @@ try {
### pushNamedRoute
-pushNamedRoute(options: router.NamedRouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void
+pushNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode, callback: AsyncCallback<void>): void
跳转到指定的命名路由页面。
@@ -1361,7 +1362,7 @@ replaceNamedRoute(options: router.NamedRouterOptions, mode: router.RouterMode):
| 错误码ID | 错误信息 |
| --------- | ------- |
-| 100001 | if UI execution context not found, only throw in standard system. |
+| 100001 | if can not get the delegate, only throw in standard system. |
| 100004 | if the named route is not exist. |
**示例:**
@@ -1425,7 +1426,7 @@ router.replaceNamedRoute({
### back
-back(options: router.RouterOptions ): void
+back(options?: router.RouterOptions ): void
返回上一页面或指定的页面。
@@ -1435,7 +1436,7 @@ back(options: router.RouterOptions ): void
| 参数名 | 类型 | 必填 | 说明 |
| ------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ |
-| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 是 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 |
+| options | [router.RouterOptions](js-apis-router.md#routeroptions) | 否 | 返回页面描述信息,其中参数url指路由跳转时会返回到指定url的界面,如果页面栈上没有url页面,则不响应该情况。如果url未设置,则返回上一页,页面不会重新构建,页面栈里面的page不会回收,出栈后会被回收。 |
**示例:**
@@ -1618,7 +1619,7 @@ try {
### showDialog
-showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse<): void
+showDialog(options: promptAction.ShowDialogOptions, callback: AsyncCallback<promptAction.ShowDialogSuccessResponse>): void
创建并显示对话框,对话框响应结果异步返回。
diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md
index 60fe7f95f7041db90977a63690fb4575c0701a6c..471fc303f6ad40f975d9f8a56f0dfe2af3a93015 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-dragController.md
@@ -175,7 +175,7 @@ struct DragControllerPage {
发起拖拽所需要的属性和拖拽时携带的信息。
-| 名称 | 类型 | 必填 | 描述 |
+| 名称 | 类型 | 必填 | 说明 |
| ----------- | ------------------------------------------------------ | ---- | ---------------------------------------- |
| pointerId | number | 是 | 设置启动拖拽时屏幕上触摸点的Id。 |
| data | [UDMF.UnifiedData](./js-apis-data-udmf.md#unifieddata) | 否 | 设置拖拽过程中携带的数据。 |
diff --git a/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md b/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md
index 67a8d3a70bd12d37bb4f71785814f741d3f18815..ed1e4495a6798ce533d8f1a9966ff3d8ae786a3c 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-arkui-drawableDescriptor.md
@@ -141,7 +141,7 @@ getBackground(): DrawableDescriptor;
**示例:**
```ts
let resManager = getContext().resourceManager
-drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon')
+let drawable: DrawableDescriptor = ( (resManager.getDrawableDescriptor($r('app.media.icon')
.id))).getBackground();
```
diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md
index ed2c521ace2e1f25f7ac493fade668b8a8c1c637..01ec48911898f3ae2be5b72eb17152cce9a69ba3 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-audio.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md
@@ -4461,6 +4461,156 @@ off(type: 'preferredOutputDeviceChangeForRendererInfo', callback?: Callback10+
+
+getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo, callback: AsyncCallback<AudioDeviceDescriptors>): void
+
+根据音频信息,返回优先级最高的输入设备,使用callback方式异步返回结果。
+
+**系统能力:** SystemCapability.Multimedia.Audio.Device
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- |
+| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 表示采集器信息。 |
+| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 是 | 回调,返回优先级最高的输入设备信息。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。
+
+| 错误码ID | 错误信息 |
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error |
+| 6800301 | System error |
+
+**示例:**
+```js
+let capturerInfo = {
+ source: audio.SourceType.SOURCE_TYPE_MIC,
+ capturerFlags: 0
+}
+
+audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo, (err, desc) => {
+ if (err) {
+ console.error(`Result ERROR: ${err}`);
+ } else {
+ console.info(`device descriptor: ${desc}`);
+ }
+});
+```
+
+### getPreferredInputDeviceForCapturerInfo10+
+
+getPreferredInputDeviceForCapturerInfo(capturerInfo: AudioCapturerInfo): Promise<AudioDeviceDescriptors>
+
+根据音频信息,返回优先级最高的输入设备,使用promise方式异步返回结果。
+
+**系统能力:** SystemCapability.Multimedia.Audio.Device
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- |
+| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 表示采集器信息。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| --------------------- | --------------------------- |
+| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise返回优先级最高的输入设备信息。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。
+
+| 错误码ID | 错误信息 |
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error |
+| 6800301 | System error |
+
+**示例:**
+
+```js
+let capturerInfo = {
+ source: audio.SourceType.SOURCE_TYPE_MIC,
+ capturerFlags: 0
+}
+
+audioRoutingManager.getPreferredInputDeviceForCapturerInfo(capturerInfo).then((desc) => {
+ console.info(`device descriptor: ${desc}`);
+}).catch((err) => {
+ console.error(`Result ERROR: ${err}`);
+})
+```
+
+### on('preferredInputDeviceChangeForCapturerInfo')10+
+
+on(type: 'preferredInputDeviceChangeForCapturerInfo', capturerInfo: AudioCapturerInfo, callback: Callback): void
+
+订阅最高优先级输入设备变化事件,使用callback获取最高优先级输入设备。
+
+**系统能力:** SystemCapability.Multimedia.Audio.Device
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- |
+| type | string | 是 | 订阅的事件的类型。支持事件:'preferredInputDeviceChangeForCapturerInfo' |
+| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | 是 | 表示采集器信息。 |
+| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)\> | 是 | 获取优先级最高的输入设备信息。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。
+
+| 错误码ID | 错误信息 |
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error |
+
+**示例:**
+
+```js
+let capturerInfo = {
+ source: audio.SourceType.SOURCE_TYPE_MIC,
+ capturerFlags: 0
+}
+
+audioRoutingManager.on('preferredInputDeviceChangeForCapturerInfo', capturerInfo, (desc) => {
+ console.info(`device descriptor: ${desc}`);
+});
+```
+
+### off('preferredInputDeviceChangeForCapturerInfo')10+
+
+off(type: 'preferredInputDeviceChangeForCapturerInfo', callback?: Callback): void
+
+取消订阅最高优先级输入音频设备变化事件。
+
+**系统能力:** SystemCapability.Multimedia.Audio.Device
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | --------------------------------------------------- | ---- | ------------------------------------------ |
+| type | string | 是 | 订阅的事件的类型。支持事件:'preferredInputDeviceChangeForCapturerInfo' |
+| callback | Callback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | 否 | 监听方法的回调函数。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[音频错误码](../errorcodes/errorcode-audio.md)。
+
+| 错误码ID | 错误信息 |
+| ------- | --------------------------------------------|
+| 6800101 | if input parameter value error |
+
+**示例:**
+
+```js
+audioRoutingManager.off('preferredInputDeviceChangeForCapturerInfo');
+```
+
## AudioRendererChangeInfoArray9+
数组类型,AudioRenderChangeInfo数组,只读。
diff --git a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md
index a9875e133df4292bd4d7108ebc632e75f1151744..c6b4f0f9e15754c5b2de3142425322e5ea5dffdd 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-bluetooth-ble.md
@@ -983,6 +983,66 @@ gattServer.off('connectionStateChange');
```
+### on('BLEMtuChange')
+
+on(type: 'BLEMtuChange', callback: Callback<number>): void
+
+server端订阅MTU状态变化事件。
+
+**需要权限**:ohos.permission.ACCESS_BLUETOOTH
+
+**系统能力**:SystemCapability.Communication.Bluetooth.Core。
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
+| type | string | 是 | 必须填写"BLEMtuChange"字符串,表示MTU状态变化事件。填写不正确将导致回调无法注册。 |
+| callback | Callback<number> | 是 | 返回MTU字节数的值,通过注册回调函数获取。 |
+
+**示例:**
+
+```js
+try {
+ let gattServer = ble.createGattServer();
+ gattServer.on('BLEMtuChange', (mtu) => {
+ console.info('BLEMtuChange, mtu: ' + mtu);
+ });
+} catch (err) {
+ console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
+}
+```
+
+
+### off('BLEMtuChange')
+
+off(type: 'BLEMtuChange', callback?: Callback<number>): void
+
+server端取消订阅MTU状态变化事件。
+
+**需要权限**:ohos.permission.ACCESS_BLUETOOTH
+
+**系统能力**:SystemCapability.Communication.Bluetooth.Core。
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
+| type | string | 是 | 必须填写"BLEMtuChange"字符串,表示MTU状态变化事件。填写不正确将导致回调无法注册。 |
+| callback | Callback<number> | 否 | 返回MTU字节数的值,通过注册回调函数获取。不填该参数则取消订阅该type对应的所有回调。 |
+
+**示例:**
+
+```js
+try {
+ let gattServer = ble.createGattServer();
+ gattServer.off('BLEMtuChange');
+} catch (err) {
+ console.error('errCode: ' + err.code + ', errMessage: ' + err.message);
+}
+```
+
+
## GattClientDevice
client端类,使用client端方法之前需要创建该类的实例进行操作,通过createGattClientDevice(deviceId: string)方法构造此实例。
@@ -2179,7 +2239,7 @@ try {
on(type: 'BLEMtuChange', callback: Callback<number>): void
-订阅Mtu状态变化事件。
+client端订阅MTU状态变化事件。
**需要权限**:ohos.permission.ACCESS_BLUETOOTH
@@ -2189,8 +2249,8 @@ on(type: 'BLEMtuChange', callback: Callback<number>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
-| type | string | 是 | 填写"BLEMtuChange"字符串,表示Mtu状态变化事件。 |
-| callback | Callback<number> | 是 | 表示Mtu状态,已连接或是断开。 |
+| type | string | 是 | 必须填写"BLEMtuChange"字符串,表示MTU状态变化事件。填写不正确将导致回调无法注册。 |
+| callback | Callback<number> | 是 | 返回MTU字节数的值,通过注册回调函数获取。 |
**示例:**
@@ -2210,7 +2270,7 @@ try {
off(type: 'BLEMtuChange', callback?: Callback<number>): void
-取消订阅Mtu状态变化事件。
+client端取消订阅MTU状态变化事件。
**需要权限**:ohos.permission.ACCESS_BLUETOOTH
@@ -2220,8 +2280,8 @@ off(type: 'BLEMtuChange', callback?: Callback<number>): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
-| type | string | 是 | 填写"BLEMtuChange"字符串,表示Mtu状态变化事件。 |
-| callback | Callback<number> | 否 | 表示取消订阅Mtu状态变化事件。不填该参数则取消订阅该type对应的所有回调。 |
+| type | string | 是 | 必须填写"BLEMtuChange"字符串,表示MTU状态变化事件。填写不正确将导致回调无法注册。 |
+| callback | Callback<number> | 否 | 返回MTU字节数的值,通过注册回调函数获取。不填该参数则取消订阅该type对应的所有回调。 |
**示例:**
diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md
index ae5328800429e186efd37c03c9f8431cbac566e0..8f0261ed7ae4afddae29b768bf3192a3c7befe4f 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager.md
@@ -113,8 +113,10 @@ Ability组件信息标志,指示需要获取的Ability组件信息的内容。
| THUMBNAIL | 13 | ThumbnailExtensionAbility:文件缩略图扩展能力,用于为文件提供图标缩略图的能力。预留能力,当前暂未支持。 |
| PREVIEW | 14 | PreviewExtensionAbility:文件预览扩展能力,提供文件预览的能力,其他应用可以直接在应用中嵌入显示。预留能力,当前暂未支持。 |
| PRINT10+ | 15 | PrintExtensionAbility:文件打印扩展能力,提供应用打印照片、文档等办公场景。当前支持图片打印,文档类型暂未支持。 |
+| SHARE10+ | 16 | [ShareExtensionAbility](js-apis-app-ability-shareExtensionAbility.md):提供分享业务能力,为开发者提供基于UIExtension的分享业务模板。 |
| PUSH10+ | 17 | PushExtensionAbility:推送扩展能力,提供推送场景化消息能力。预留能力,当前暂未支持。 |
| DRIVER10+ | 18 | DriverExtensionAbility:驱动扩展能力,提供外设驱动扩展能力,当前暂未支持。 |
+| ACTION10+ | 19 | [ActionExtensionAbility](js-apis-app-ability-actionExtensionAbility.md):自定义服务扩展能力,为开发者提供基于UIExtension的自定义操作业务模板。 |
| UNSPECIFIED | 255 | 不指定类型,配合queryExtensionAbilityInfo接口可以查询所有类型的ExtensionAbility。 |
@@ -1141,6 +1143,82 @@ try {
}
```
+### bundleManager.queryAbilityInfoSync
+
+queryAbilityInfoSync(want: Want, abilityFlags: [number](#abilityflag), userId?: number): Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)>;
+
+以同步方法根据给定的want、abilityFlags和userId获取一个或多个AbilityInfo。
+
+**系统接口:** 此接口为系统接口。
+
+**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ------------ | ------ | ---- | ------------------------------------------------------- |
+| want | Want | 是 | 表示包含要查询的应用Bundle名称的Want。 |
+| abilityFlags | [number](#abilityflag) | 是 | 表示指定返回的AbilityInfo所包含的信息。 |
+| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ------------------------------------------------------------ | ------------------------------------ |
+| Array\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Array\信息。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | ------------------------------------- |
+| 17700001 | The specified bundleName is not found. |
+| 17700003 | The specified ability is not found. |
+| 17700004 | The specified userId is invalid. |
+| 17700026 | The specified bundle is disabled. |
+| 17700029 | The specified ability is disabled. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT;
+let userId = 100;
+let want = {
+ bundleName : "com.example.myapplication",
+ abilityName : "EntryAbility"
+};
+
+try {
+
+ let infos = bundleManager.queryAbilityInfoSync(want, abilityFlags, userId);
+ hilog.info(0x0000, 'testTag', 'queryAbilityInfoSync successfully. Data: %{public}s', JSON.stringify(infos));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'queryAbilityInfoSync failed. Cause: %{public}s', err.message);
+}
+```
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT;
+let want = {
+ bundleName : "com.example.myapplication",
+ abilityName : "EntryAbility"
+};
+
+try {
+ let infos = bundleManager.queryAbilityInfoSync(want, abilityFlags);
+ hilog.info(0x0000, 'testTag', 'queryAbilityInfoSync successfully. Data: %{public}s', JSON.stringify(infos));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'queryAbilityInfoSync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.queryExtensionAbilityInfo
queryExtensionAbilityInfo(want: Want, extensionAbilityType: [ExtensionAbilityType](#extensionabilitytype), extensionAbilityFlags: [number](#extensionabilityflag), userId: number, callback: AsyncCallback>): void;
@@ -1340,6 +1418,84 @@ try {
}
```
+### bundleManager.queryExtensionAbilityInfoSync
+
+queryExtensionAbilityInfoSync(want: Want, extensionAbilityType: [ExtensionAbilityType](#extensionabilitytype), extensionAbilityFlags: [number](#extensionabilityflag), userId?: number): Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)>;
+
+以同步方法根据给定的want、extensionAbilityType、extensionAbilityFlags和userId获取ExtensionAbilityInfo。
+
+**系统接口:** 此接口为系统接口。
+
+**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| --------------------- | --------------------------------------------- | ---- | --------------------------------------------------------- |
+| want | Want | 是 | 表示包含要查询的应用Bundle名称的Want。 |
+| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | 是 | 标识extensionAbility的类型。 |
+| extensionAbilityFlags | [number](#extensionabilityflag) | 是 | 表示用于指定将返回的ExtensionInfo对象中包含的信息的标志。 |
+| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ------------------------------------------------------------ | --------------------------------------------- |
+| Array\<[ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md)> | Array\信息。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | --------------------------------------|
+| 17700001 | The specified bundleName is not found. |
+| 17700003 | The specified extensionAbility is not found. |
+| 17700004 | The specified userId is invalid. |
+| 17700026 | The specified bundle is disabled. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+
+let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM;
+let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT;
+let userId = 100;
+let want = {
+ bundleName : "com.example.myapplication",
+ abilityName : "EntryAbility"
+};
+
+try {
+ let extenInfos = bundleManager.queryExtensionAbilityInfoSync(want, extensionAbilityType, extensionFlags, userId);
+ hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfoSync successfully. Data: %{public}s', JSON.stringify(extenInfos));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfoSync failed. Cause: %{public}s', err.message);
+}
+```
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM;
+let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT;
+let want = {
+ bundleName : "com.example.myapplication",
+ abilityName : "EntryAbility"
+};
+
+try {
+ let extenInfos = bundleManager.queryExtensionAbilityInfoSync(want, extensionAbilityType, extensionFlags);
+ hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfoSync successfully. Data: %{public}s', JSON.stringify(extenInfos));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfoSync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.getBundleNameByUid
getBundleNameByUid(uid: number, callback: AsyncCallback\): void;
@@ -1435,6 +1591,52 @@ try {
}
```
+### bundleManager.getBundleNameByUidSync10+
+
+getBundleNameByUidSync(uid: number): string;
+
+以同步方法根据给定的uid获取对应的bundleName。
+
+**系统接口:** 此接口为系统接口。
+
+**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ---- | ------ | ---- | ------------------ |
+| uid | number | 是 | 表示应用程序的UID。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ---------------- | --------------------------- |
+| string | 返回获取到的bundleName。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | ---------------------|
+| 17700021 | The uid is not found. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let uid = 20010005;
+try {
+ let data = bundleManager.getBundleNameByUidSync(uid);
+ hilog.info(0x0000, 'testTag', 'getBundleNameByUidSync successfully. Data: %{public}s', JSON.stringify(data));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getBundleNameByUidSync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.getBundleArchiveInfo
getBundleArchiveInfo(hapFilePath: string, bundleFlags: [number](#bundleflag), callback: AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)>): void;
@@ -1536,6 +1738,55 @@ try {
}
```
+### bundleManager.getBundleArchiveInfoSync10+
+
+getBundleArchiveInfoSync(hapFilePath: string, bundleFlags: number): BundleInfo;
+
+以同步方法根据给定的hapFilePath和bundleFlags获取BundleInfo对象。
+
+**系统接口:** 此接口为系统接口。
+
+**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ----------- | ------ | ---- | ------------------------------------------------------------ |
+| hapFilePath | string | 是 | 表示存储HAP的路径,路径应该是当前应用程序数据目录的相对路径。 |
+| bundleFlags | [number](#bundleflag) | 是 | 表示用于指定要返回的BundleInfo对象中包含的信息的标志。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ----------------------------------------------------------- | --------------------------- |
+| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | 返回BundleInfo对象。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | -------------------------- |
+| 17700022 | The hapFilePath is invalid. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let hapFilePath = "/data/xxx/test.hap";
+let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT;
+
+try {
+ let data = bundleManager.getBundleArchiveInfoSync(hapFilePath, bundleFlags)
+ hilog.info(0x0000, 'testTag', 'getBundleArchiveInfoSync successfully. Data: %{public}s', JSON.stringify(data));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getBundleArchiveInfoSync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.cleanBundleCacheFiles
cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback\): void;
@@ -2438,6 +2689,72 @@ try {
}
```
+
+### bundleManager.getLaunchWantForBundleSync
+
+getLaunchWantForBundleSync(bundleName: string, userId?: number): Want;
+
+以同步方法根据给定的bundleName和userId获取用于启动应用程序的Want参数。
+
+**系统接口:** 此接口为系统接口。
+
+**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ---------- | ------ | ---- | ------------------------- |
+| bundleName | string | 是 | 表示应用程序的bundleName。 |
+| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| -------------- | ------------------------- |
+| Want | Want对象。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | --------------------------------------|
+| 17700001 | The specified bundleName is not found. |
+| 17700004 | The specified user ID is not found. |
+| 17700026 | The specified bundle is disabled. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let bundleName = 'com.example.myapplication';
+let userId = 100;
+
+try {
+ let want = bundleManager.getLaunchWantForBundleSync(bundleName, userId);
+ hilog.info(0x0000, 'testTag', 'getLaunchWantForBundleSync successfully. Data: %{public}s', JSON.stringify(want));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getLaunchWantForBundleSync failed. Cause: %{public}s', err.message);
+}
+```
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let bundleName = 'com.example.myapplication';
+let userId = 100;
+
+try {
+ let want = bundleManager.getLaunchWantForBundleSync(bundleName);
+ hilog.info(0x0000, 'testTag', 'getLaunchWantForBundleSync successfully. Data: %{public}s', JSON.stringify(want));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getLaunchWantForBundleSync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.getProfileByAbility
getProfileByAbility(moduleName: string, abilityName: string, metadataName: string, callback: AsyncCallback\\>): void;
@@ -2559,6 +2876,70 @@ try {
}
```
+### bundleManager.getProfileByAbilitySync10+
+
+getProfileByAbilitySync(moduleName: string, abilityName: string, metadataName?: string): Array\;
+
+以同步方法根据给定的moduleName、abilityName和metadataName获取相应配置文件的json格式字符串,返回对象为string数组。
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ------------ | ------ | ---- | -------------------------- |
+| moduleName | string | 是 | 表示应用程序的moduleName。 |
+| abilityName | string | 是 | 表示应用程序的abilityName。 |
+| metadataName | string | 否 | 表示应用程序的metadataName,默认值为空。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ----------------------- | ------------------------------- |
+| Array\ | 数组对象,返回Array\。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | ------------------------------------------------------------ |
+| 17700002 | The specified moduleName is not existed. |
+| 17700003 | The specified abilityName is not existed. |
+| 17700024 | Failed to get the profile because there is no profile in the HAP. |
+| 17700026 | The specified bundle is disabled. |
+| 17700029 | The specified ability is disabled. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let moduleName = 'entry';
+let abilityName = 'EntryAbility';
+
+try {
+ let data = bundleManager.getProfileByAbilitySync(moduleName, abilityName);
+ hilog.info(0x0000, 'testTag', 'getProfileByAbilitySync successfully. Data: %{public}s', JSON.stringify(data));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getProfileByAbilitySync failed. Cause: %{public}s', err.message);
+}
+```
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let moduleName: string = 'entry';
+let abilityName: string = 'EntryAbility';
+let metadataName: string = 'com.example.myapplication.metadata';
+try {
+ let data = bundleManager.getProfileByAbilitySync(moduleName, abilityName, metadataName);
+ hilog.info(0x0000, 'testTag', 'getProfileByAbilitySync successfully. Data: %{public}s', JSON.stringify(data));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getProfileByAbilitySync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.getProfileByExtensionAbility
getProfileByExtensionAbility(moduleName: string, extensionAbilityName: string, metadataName: string, callback: AsyncCallback\\>): void;
@@ -2672,6 +3053,63 @@ try {
}
```
+### bundleManager.getProfileByExtensionAbilitySync10+
+
+getProfileByExtensionAbilitySync(moduleName: string, extensionAbilityName: string, metadataName?: string): Array\;
+
+以同步方法根据给定的moduleName、extensionAbilityName和metadataName获取相应配置文件的json格式字符串,返回对象为string数组。
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------------------- | ------ | ---- | ---------------------------------- |
+| moduleName | string | 是 | 表示应用程序的moduleName。 |
+| extensionAbilityName | string | 是 | 表示应用程序的extensionAbilityName。 |
+| metadataName | string | 否 | 表示应用程序的metadataName,默认值为空。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ----------------------- | ----------------------------------- |
+| Array\ | 返回Array\对象。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | ------------------------------------------------------------ |
+| 17700002 | The specified moduleName is not existed. |
+| 17700003 | The specified extensionAbilityName not existed. |
+| 17700024 | Failed to get the profile because there is no profile in the HAP. |
+| 17700026 | The specified bundle is disabled. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let moduleName = 'entry';
+let extensionAbilityName = 'com.example.myapplication.extension';
+let metadataName = 'com.example.myapplication.metadata';
+
+try {
+ let data = bundleManager.getProfileByExtensionAbilitySync(moduleName, extensionAbilityName);
+ hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbilitySync successfully. Data: %{public}s', JSON.stringify(data));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbilitySync failed. Cause: %{public}s', err.message);
+}
+
+try {
+ let data = bundleManager.getProfileByExtensionAbilitySync(moduleName, extensionAbilityName, metadataName);
+ hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbilitySync successfully. Data: %{public}s', JSON.stringify(data));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbilitySync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.getPermissionDef
getPermissionDef(permissionName: string, callback: AsyncCallback\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>): void;
@@ -2767,6 +3205,52 @@ try {
}
```
+### bundleManager.getPermissionDefSync
+
+getPermissionDefSync(permissionName: string): [PermissionDef](js-apis-bundleManager-permissionDef.md);
+
+以同步方法根据给定的permissionName获取权限定义结构体PermissionDef信息。
+
+**系统接口:** 此接口为系统接口。
+
+**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------------- | ------ | ---- | -------------- |
+| permissionName | string | 是 | 表示权限参数名。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ------------------------------------------------------------ | ------------------------------------------ |
+|[PermissionDef](js-apis-bundleManager-permissionDef.md) | PermissionDef对象。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | ------------------------------------- |
+| 17700006 | The specified permission is not found. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let permissionName = "ohos.permission.GET_BUNDLE_INFO";
+try {
+ let PermissionDef = bundleManager.getPermissionDefSync(permission);
+ hilog.info(0x0000, 'testTag', 'getPermissionDefSync successfully. Data: %{public}s', JSON.stringify(PermissionDef));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getPermissionDefSync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.getAbilityLabel
getAbilityLabel(bundleName: string, moduleName: string, abilityName: string, callback: AsyncCallback\): void;
@@ -2880,6 +3364,60 @@ try {
}
```
+### bundleManager.getAbilityLabelSync
+
+getAbilityLabelSync(bundleName: string, moduleName: string, abilityName: string): string;
+
+以同步的方法获取指定bundleName、moduleName和abilityName的label。
+
+**系统接口:** 此接口为系统接口。
+
+**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Resource
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| ----------- | ------ | ---- | ------------------------- |
+| bundleName | string | 是 | 表示应用程序的bundleName。 |
+| moduleName | string | 是 | 表示应用程序的moduleName。 |
+| abilityName | string | 是 | 表示应用程序的abilityName。 |
+
+**返回值:**
+
+| 类型 | 说明 |
+| ---------------- | ----------------------------------- |
+| string | 指定组件的Lablel值。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | --------------------------------------- |
+| 17700001 | The specified bundleName is not found. |
+| 17700002 | The specified moduleName is not found. |
+| 17700003 | The specified abilityName is not found. |
+| 17700026 | The specified bundle is disabled. |
+| 17700029 | The specified ability is disabled. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let bundleName = 'com.example.myapplication';
+let moduleName = 'entry';
+let abilityName = 'EntryAbility';
+
+try {
+ let abilityLabel = bundleManager.getAbilityLabelSync(bundleName, moduleName, abilityName);
+ hilog.info(0x0000, 'testTag', 'getAbilityLabelSync successfully. Data: %{public}s', abilityLabel);
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getAbilityLabelSync failed. Cause: %{public}s', err.message);
+}
+```
### bundleManager.getApplicationInfoSync
@@ -3423,6 +3961,64 @@ try {
}
```
+### bundleManager.getAppProvisionInfoSync10+
+
+getAppProvisionInfoSync(bundleName: string, userId?: number): AppProvisionInfo;
+
+以同步方法根据bundleName和userId获取应用的provision配置文件信息并返回结果。
+
+**系统接口:** 此接口为系统接口
+
+**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED
+
+**系统能力:** SystemCapability.BundleManager.BundleFramework.Core
+
+**参数:**
+
+| 参数名 | 类型 | 必填 | 说明 |
+| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
+| bundleName | string | 是 | 指定的bundleName。 |
+| userId | number | 否 | 表示用户ID,默认值:调用方所在用户,取值范围:大于等于0,可以通过接口[getOsAccountLocalId](js-apis-osAccount.md#getosaccountlocalid9)获取当前设备上的用户ID。 |
+
+
+**返回值:**
+
+| 类型 | 说明 |
+| ------------------------------------------------------------ | ----------------------------------- |
+| [AppProvisionInfo](js-apis-bundleManager-AppProvisionInfo.md) | AppProvisionInfo对象,返回应用的provision配置文件信息。 |
+
+**错误码:**
+
+以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errorcode-bundle.md)。
+
+| 错误码ID | 错误信息 |
+| -------- | -------------------------------------- |
+| 17700001 | The specified bundleName is not found. |
+| 17700004 | The specified user ID is not found. |
+
+**示例:**
+
+```ts
+import bundleManager from '@ohos.bundle.bundleManager';
+import hilog from '@ohos.hilog';
+let bundleName = "com.ohos.myapplication";
+let userId = 100;
+
+try {
+ let data = bundleManager.getAppProvisionInfoSync(bundleName);
+ hilog.info(0x0000, 'testTag', 'getAppProvisionInfoSync successfully. Data: %{public}s', JSON.stringify(data));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getAppProvisionInfoSync failed. Cause: %{public}s', err.message);
+}
+
+try {
+ let data = bundleManager.getAppProvisionInfoSync(bundleName, userId);
+ hilog.info(0x0000, 'testTag', 'getAppProvisionInfoSync successfully. Data: %{public}s', JSON.stringify(data));
+} catch (err) {
+ hilog.error(0x0000, 'testTag', 'getAppProvisionInfoSync failed. Cause: %{public}s', err.message);
+}
+```
+
### bundleManager.getSpecifiedDistributionType10+
getSpecifiedDistributionType(bundleName: string): string;
diff --git a/zh-cn/application-dev/reference/apis/js-apis-call.md b/zh-cn/application-dev/reference/apis/js-apis-call.md
index a0b3c7d0e44d160275cef852b1276dc895058957..61010d4eeb9553e1ebcd9435739422c27a9eb7ac 100644
--- a/zh-cn/application-dev/reference/apis/js-apis-call.md
+++ b/zh-cn/application-dev/reference/apis/js-apis-call.md
@@ -2821,7 +2821,7 @@ call.off('mmiCodeResult', data => {
## call.on('audioDeviceChange')10+
-on\(type: 'audioDeviceChange', callback: Callback\\): void
+on\(type: 'audioDeviceChange', callback: Callback\\): void
订阅通话音频设备切换事件。使用callback异步回调。
@@ -2836,7 +2836,7 @@ on\(type: 'audioDeviceChange', callback: Callback\\): void
| 参数名 | 类型 | 必填 | 说明 |
| -------- | ----------------------------------------------- | ---- | --------------------------------------------------- |
| type | string | 是 | 通话音频设备发生变化,参数固定为'audioDeviceChange'。 |
-| callback | Callback<[AudioDeviceInfo](#audiodeviceinfo10)> | 是 | 回调函数。 |
+| callback | Callback<[AudioDeviceCallbackInfo](#audiodevicecallbackinfo10)> | 是 | 回调函数。 |
**错误码:**
@@ -2863,7 +2863,7 @@ call.on('audioDeviceChange', data => {
## call.off('audioDeviceChange')10+
-off\(type: 'audioDeviceChange', callback?: Callback\\): void
+off\(type: 'audioDeviceChange', callback?: Callback\