提交 c12924b0 编写于 作者: M marui

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

Signed-off-by: Nmarui <marui83@huawei.com>
...@@ -241,7 +241,7 @@ zh-cn/application-dev/reference/apis/js-apis-data-preferences.md @feng-aiwen @ge ...@@ -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-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-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-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-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-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 zh-cn/application-dev/reference/apis/js-apis-data-ValuesBucket.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
......
...@@ -54,7 +54,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and ...@@ -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)| | 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)| | 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.<br>- **true**: The widget supports the update-through-proxy feature.<br>- **false**: The widget does not support the update-through-proxy feature.<br>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**)| | dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.<br>- **true**: The widget supports the update-through-proxy feature.<br>- **false**: The widget does not support the update-through-proxy feature.<br>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.<br>- **true**: The widget is a dynamic widget.<br>- **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.<br>- **true**: The widget is a dynamic widget.<br>- **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 **Table 2** Internal structure of the window object
......
...@@ -26,7 +26,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol ...@@ -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. - 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). - 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. - 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. - 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 ...@@ -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: 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 - 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 ...@@ -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: 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 - Using **startAbilityByCall()** to start the UIAbility component
![component-startup-rules](figures/component-startup-inter-stage.png) ![component-startup-rules](figures/component-startup-inter-stage.png)
...@@ -8,6 +8,10 @@ This topic describes how the two application components of the stage model start ...@@ -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. 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 ```ts
import UIAbility from '@ohos.app.ability.UIAbility'; import UIAbility from '@ohos.app.ability.UIAbility';
...@@ -25,7 +29,7 @@ export default class EntryAbility extends UIAbility { ...@@ -25,7 +29,7 @@ export default class EntryAbility extends UIAbility {
}); });
let want = { let want = {
bundleName: "com.ohos.fa", bundleName: "com.ohos.fa",
abilityName: "EntryAbility", abilityName: "com.ohos.fa.EntryAbility",
}; };
this.context.startAbility(want).then(() => { this.context.startAbility(want).then(() => {
console.info('Start Ability successfully.'); console.info('Start Ability successfully.');
......
...@@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility'; ...@@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility';
let parameter = { let parameter = {
"want": { "want": {
bundleName: "com.ohos.stage", bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.EntryAbility" abilityName: "EntryAbility"
} }
}; };
featureAbility.startAbility(parameter).then((code) => { featureAbility.startAbility(parameter).then((code) => {
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
## Types of Want ## 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. 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 @@ ...@@ -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. 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 @@ ...@@ -47,6 +47,7 @@
> - An application component that meets the conditions is matched. That application component is started. > - 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. > - 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.
# HTTP Data Request # 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**. 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 ...@@ -18,7 +18,7 @@ The following table provides only a simple description of the related APIs. For
| ----------------------------------------- | ----------------------------------- | | ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. | | createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. | | request() | Initiates an HTTP request to a given URL. |
| request2()<sup>10+</sup> | Initiates an HTTP network request based on the URL and returns a streaming response.| | requestInStream()<sup>10+</sup> | Initiates an HTTP network request to a given URL and returns a streaming response.|
| destroy() | Destroys an HTTP request. | | destroy() | Destroys an HTTP request. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. | | on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the 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 ...@@ -27,8 +27,8 @@ The following table provides only a simple description of the related APIs. For
| off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. | | off\('dataReceive'\)<sup>10+</sup> | Unregisters the observer for events indicating receiving of HTTP streaming responses. |
| on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. | | on\('dataEnd'\)<sup>10+</sup> | Registers an observer for events indicating completion of receiving HTTP streaming responses. |
| off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.| | off\('dataEnd'\)<sup>10+</sup> | Unregisters the observer for events indicating completion of receiving HTTP streaming responses.|
| on\('dataProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. | | on\('dataReceiveProgress'\)<sup>10+</sup> | Registers an observer for events indicating progress of receiving HTTP streaming responses. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.| | off\('dataReceiveProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop request APIs ## How to Develop request APIs
...@@ -53,6 +53,7 @@ httpRequest.on('headersReceive', (header) => { ...@@ -53,6 +53,7 @@ httpRequest.on('headersReceive', (header) => {
}); });
httpRequest.request( httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL. // 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. method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements. // You can add header fields based on service requirements.
...@@ -81,7 +82,7 @@ httpRequest.request( ...@@ -81,7 +82,7 @@ httpRequest.request(
// Call the destroy() method to release resources after HttpRequest is complete. // Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy(); httpRequest.destroy();
} else { } else {
console.info('error:' + JSON.stringify(err)); console.error('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events. // Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive'); httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete. // Call the destroy() method to release resources after HttpRequest is complete.
...@@ -91,12 +92,12 @@ httpRequest.request( ...@@ -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**. 1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object. 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. 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. 5. Parse the returned response code as needed.
6. Call **off()** of the **HttpRequest** object to unsubscribe from the related events. 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. 7. Call **httpRequest.destroy()** to release resources after the request is processed.
...@@ -122,11 +123,11 @@ httpRequest.on('dataEnd', () => { ...@@ -122,11 +123,11 @@ httpRequest.on('dataEnd', () => {
console.info('No more data in response, data receive end'); console.info('No more data in response, data receive end');
}); });
// Subscribe to events indicating progress of receiving HTTP streaming responses. // Subscribe to events indicating progress of receiving HTTP streaming responses.
httpRequest.on('dataProgress', (data) => { httpRequest.on('dataReceiveProgress', (data) => {
console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize); 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. // Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL", "EXAMPLE_URL",
{ {
...@@ -146,14 +147,14 @@ httpRequest.request2( ...@@ -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. 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. usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => { }, (err, data) => {
console.info('error:' + JSON.stringify(err)); console.error('error:' + JSON.stringify(err));
console.info('ResponseCode :' + JSON.stringify(data)); console.info('ResponseCode :' + JSON.stringify(data));
// Unsubscribe from HTTP Response Header events. // Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive'); httpRequest.off('headersReceive');
// Unregister the observer for events indicating receiving of HTTP streaming responses. // Unregister the observer for events indicating receiving of HTTP streaming responses.
httpRequest.off('dataReceive'); httpRequest.off('dataReceive');
// Unregister the observer for events indicating progress of receiving HTTP streaming responses. // 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. // Unregister the observer for events indicating completion of receiving HTTP streaming responses.
httpRequest.off('dataEnd'); httpRequest.off('dataEnd');
// Call the destroy() method to release resources after HttpRequest is complete. // Call the destroy() method to release resources after HttpRequest is complete.
...@@ -161,10 +162,3 @@ httpRequest.request2( ...@@ -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)
# IPC & RPC Development Guidelines # 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. 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.
......
# Network Connection Management # 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. 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** > **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). > 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 ## Basic Concepts
......
# Ethernet Connection # 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. 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** > **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). > 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** ## **Constraints**
......
# MDNS Management # MDNS Management
## Introduction ## Overview
Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN. 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. - Local service: a service provider on a LAN, for example, a printer or scanner.
......
# Network Sharing # 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. 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** > **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). > 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 ## Basic Concepts
......
# Traffic Management # 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). 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: ...@@ -11,6 +11,7 @@ Its functions include:
- Subscribing to traffic change events by NIC or UID - Subscribing to traffic change events by NIC or UID
> **NOTE** > **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). > 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. The following describes the development procedure specific to each application scenario.
......
...@@ -5,6 +5,7 @@ ...@@ -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. 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** > **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). > 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. The following describes the development procedure specific to each application scenario.
......
# Socket Connection # 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. The Socket Connection module allows an application to transmit data over a socket connection through the TCP, UDP, or TLS protocol.
......
# Subscribing to State Changes of a Remote Object # 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. 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 ## When to Use
......
# WebSocket Connection # 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. 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.
......
# DFX # DFX
- [Development of Application Event Logging](hiappevent-guidelines.md) - [Development of Application Event Logging](hiappevent-guidelines.md)
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md) - [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- [HiLog Development (Native)](hilog-guidelines.md) - [HiLog Development (Native)](hilog-guidelines.md)
- Performance Tracing - Performance Tracing
......
# Application Freeze (appfreeze) Log Analysis # 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. 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.
......
# Application Recovery Development # 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. 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' ...@@ -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). - 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 ```ts
var registerId = -1; export let abilityWant : Want // file1
var callback = {
onUnhandledException(errMsg) { import * as G form "../file1"
let registerId = -1;
let callback: Callback = {
onUnhandledException(errMsg: string): void {
console.log(errMsg); console.log(errMsg);
appRecovery.saveAppState(); appRecovery.saveAppState();
appRecovery.restartApp(); appRecovery.restartApp();
...@@ -112,7 +115,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant' ...@@ -112,7 +115,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
// Main window is created, set main page for this ability // Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate") console.log("[Demo] MainAbility onWindowStageCreate")
globalThis.registerObserver = (() => { G.registerObserver = (() => {
registerId = errorManager.on('error', callback); registerId = errorManager.on('error', callback);
}) })
...@@ -138,13 +141,16 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state, ...@@ -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**. 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 ```ts
export let abilityWant : Want // file1
import * as GlobalWant form "../file1"
storage: LocalStorage storage: LocalStorage
onCreate(want, launchParam) { onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate") console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want; GlobalWant.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage(); this.storage = new LocalStorage();
let recoveryData = want.parameters["myData"]; let recoveryData: string = want.parameters["myData"];
this.storage.setOrCreate("myData", recoveryData); this.storage.setOrCreate("myData", recoveryData);
this.context.restoreWindowStage(this.storage); this.context.restoreWindowStage(this.storage);
} }
...@@ -154,12 +160,15 @@ onCreate(want, launchParam) { ...@@ -154,12 +160,15 @@ onCreate(want, launchParam) {
- Unregister the **ErrorObserver** callback. - Unregister the **ErrorObserver** callback.
```ts ```ts
export let abilityWant : Want // file1
import * as G form "../file1"
onWindowStageDestroy() { onWindowStageDestroy() {
// Main window is destroyed, release UI related resources // Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy") console.log("[Demo] MainAbility onWindowStageDestroy")
globalThis.unRegisterObserver = (() => { G.unRegisterObserver = (() => {
errorManager.off('error', registerId, (err) => { errorManager.off(type: 'error', registerId: number, (err:Error) => {
console.error("[Demo] err:", err); console.error("[Demo] err:", err);
}); });
}) })
...@@ -171,20 +180,22 @@ onWindowStageDestroy() { ...@@ -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. 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 ```ts
export let abilityWant : Want // file1
import * as GlobalWant form "../file1"
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
storage: LocalStorage onCreate(want: Want, launchParam:AbilityConstant.LaunchParam):void {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate") console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want; GlobalWant.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) { if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage(); this.storage = new LocalStorage();
let recoveryData = want.parameters["myData"]; let recoveryData: string = want.parameters["myData"];
this.storage.setOrCreate("myData", recoveryData); this.storage.setOrCreate<string>("myData", recoveryData);
this.context.restoreWindowStage(this.storage); 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 // Ability has called to save app data
console.log("[Demo] MainAbility onSaveState") console.log("[Demo] MainAbility onSaveState")
wantParams["myData"] = "my1234567"; wantParams["myData"] = "my1234567";
......
# Process Crash (cppcrash) Log Analysis # 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. 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.
......
# Development of Error Manager # 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. 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.
......
# Development of Application Event Logging # 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. 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.
......
# HiLog Development (Native) # 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. 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.
......
# Development of Distributed Call Chain Tracing # 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. 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.
......
# Development of Performance Tracing (ArkTS) # 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. 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 ...@@ -21,7 +21,7 @@ hiTraceMeter provides APIs for system performance tracing. You can call the APIs
## Available 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** **APIs for performance tracing**
...@@ -35,60 +35,16 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de ...@@ -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. 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: 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:
```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:
```ts ```ts
import hitrace from '@ohos.hiTraceMeter'; import hitrace from '@ohos.hiTraceMeter';
@Entry @Entry
@Component @Component
struct Index { struct Index {
@State message: string = 'Hello World'; @State message: string = 'Hello World';
build() { build() {
Row() { Row() {
Column() { Column() {
...@@ -97,7 +53,7 @@ In this example, distributed call chain tracing begins when the application star ...@@ -97,7 +53,7 @@ In this example, distributed call chain tracing begins when the application star
.fontWeight(FontWeight.Bold) .fontWeight(FontWeight.Bold)
.onClick(() => { .onClick(() => {
this.message = 'Hello ArkUI'; this.message = 'Hello ArkUI';
// Start trace tasks with the same name concurrently. // Start trace tasks with the same name concurrently.
hitrace.startTrace("HITRACE_TAG_APP", 1001); hitrace.startTrace("HITRACE_TAG_APP", 1001);
// Keep the service process running. // Keep the service process running.
...@@ -107,7 +63,7 @@ In this example, distributed call chain tracing begins when the application star ...@@ -107,7 +63,7 @@ In this example, distributed call chain tracing begins when the application star
hitrace.startTrace("HITRACE_TAG_APP", 1002); hitrace.startTrace("HITRACE_TAG_APP", 1002);
// Keep the service process running. // Keep the service process running.
console.log(`HITRACE_TAG_APP running`); console.log(`HITRACE_TAG_APP running`);
hitrace.finishTrace("HITRACE_TAG_APP", 1001); hitrace.finishTrace("HITRACE_TAG_APP", 1001);
hitrace.finishTrace("HITRACE_TAG_APP", 1002); hitrace.finishTrace("HITRACE_TAG_APP", 1002);
...@@ -143,7 +99,7 @@ In this example, distributed call chain tracing begins when the application star ...@@ -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: 3. Click the run button on the application page. Then, run the following commands in sequence in shell:
```shell ```shell
hdc shell hdc shell
hitrace --trace_begin app hitrace --trace_begin app
......
# Development of Performance Tracing (Native) # 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. 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** > **NOTE**
......
...@@ -21,42 +21,6 @@ try { ...@@ -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? ## How do I obtain the window width and height?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model) Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model)
......
...@@ -20,11 +20,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ...@@ -20,11 +20,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts ```ts
import media from '@ohos.multimedia.media'; import media from '@ohos.multimedia.media';
let avRecorder = undefined; let avRecorder: media.AVRecorder;
media.createAVRecorder().then((recorder) => { media.createAVRecorder().then((recorder: media.AVRecorder) => {
avRecorder = recorder; avRecorder = recorder;
}, (err) => { }, (error: Error) => {
console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`); console.error(`createAVRecorder failed`);
}) })
``` ```
...@@ -37,13 +37,13 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ...@@ -37,13 +37,13 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts ```ts
// Callback function for state changes. // 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}`); console.log(`current state is ${state}`);
// You can add the action to be performed after the state is switched. // You can add the action to be performed after the state is switched.
}) })
// Callback function for errors. // 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}`); 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 ...@@ -62,21 +62,21 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts ```ts
let avProfile = { let avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // Audio bit rate. audioBitrate: 100000, // Audio bit rate.
audioChannels: 2, // Number of audio channels. audioChannels: 2, // Number of audio channels.
audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported.
audioSampleRate: 48000, // Audio sampling rate. audioSampleRate: 48000, // Audio sampling rate.
fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. 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. audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used.
profile: avProfile, 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. 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(() => { avRecorder.prepare(avConfig).then(() => {
console.log('Invoke prepare succeeded.'); console.log('Invoke prepare succeeded.');
}, (err) => { }, (err: BusinessError) => {
console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -100,17 +100,17 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts ```ts
import media from '@ohos.multimedia.media'; import media from '@ohos.multimedia.media';
import { BusinessError } from '@ohos.base';
export class AudioRecorderDemo { export class AudioRecorderDemo {
private avRecorder; private avRecorder: media.AVRecorder;
private avProfile = { private avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // Audio bit rate. audioBitrate: 100000, // Audio bit rate.
audioChannels: 2, // Number of audio channels. audioChannels: 2, // Number of audio channels.
audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported. audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported.
audioSampleRate: 48000, // Audio sampling rate. audioSampleRate: 48000, // Audio sampling rate.
fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported. 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. audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used.
profile: this.avProfile, profile: this.avProfile,
url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. 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 { ...@@ -119,11 +119,11 @@ export class AudioRecorderDemo {
// Set AVRecorder callback functions. // Set AVRecorder callback functions.
setAudioRecorderCallback() { setAudioRecorderCallback() {
// Callback function for state changes. // 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}`); console.log(`AudioRecorder current state is ${state}`);
}) })
// Callback function for errors. // 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}`); console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`);
}) })
} }
......
...@@ -24,10 +24,10 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ...@@ -24,10 +24,10 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts ```ts
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
let avRecorder let avRecorder: media.AVRecorder;
media.createAVRecorder().then((recorder) => { media.createAVRecorder().then((recorder: media.AVRecorder) => {
avRecorder = recorder avRecorder = recorder
}, (error) => { }, (error: Error) => {
console.error('createAVRecorder failed') console.error('createAVRecorder failed')
}) })
``` ```
...@@ -40,11 +40,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ...@@ -40,11 +40,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts ```ts
// Callback function for state changes. // 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); console.info('current state is: ' + state);
}) })
// Callback function for errors. // Callback function for errors.
avRecorder.on('error', (err) => { avRecorder.on('error', (err: BusinessError) => {
console.error('error happened, error message is ' + err); 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 ...@@ -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). > - 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 ```ts
let avProfile = { let avProfile: media.AVRecorderProfile = {
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
videoBitrate: 200000, // Video bit rate. videoBitrate: 200000, // Video bit rate.
videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported. 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 ...@@ -70,15 +70,15 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
videoFrameHeight: 480, // Video frame height. videoFrameHeight: 480, // Video frame height.
videoFrameRate: 30 // Video frame rate. 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. 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. 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. 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(() => { avRecorder.prepare(avConfig).then(() => {
console.info('avRecorder prepare success') console.info('avRecorder prepare success')
}, (error) => { }, (error: Error) => {
console.error('avRecorder prepare failed') console.error('avRecorder prepare failed')
}) })
``` ```
...@@ -90,9 +90,9 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re ...@@ -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. 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 ```ts
avRecorder.getInputSurface().then((surfaceId) => { avRecorder.getInputSurface().then((surfaceId: string) => {
console.info('avRecorder getInputSurface success') console.info('avRecorder getInputSurface success')
}, (error) => { }, (error: Error) => {
console.error('avRecorder getInputSurface failed') console.error('avRecorder getInputSurface failed')
}) })
``` ```
...@@ -123,19 +123,20 @@ Refer to the sample code below to complete the process of starting, pausing, res ...@@ -123,19 +123,20 @@ Refer to the sample code below to complete the process of starting, pausing, res
```ts ```ts
import media from '@ohos.multimedia.media' import media from '@ohos.multimedia.media'
import { BusinessError } from '@ohos.base';
const TAG = 'VideoRecorderDemo:' const TAG = 'VideoRecorderDemo:'
export class VideoRecorderDemo { export class VideoRecorderDemo {
private avRecorder; private avRecorder: media.AVRecorder;
private videoOutSurfaceId; private videoOutSurfaceId: string;
private avProfile = { private avProfile: media.AVRecorderProfile = {
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported. 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. videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported.
videoFrameWidth: 640, // Video frame width. videoFrameWidth: 640, // Video frame width.
videoFrameHeight: 480, // Video frame height. videoFrameHeight: 480, // Video frame height.
videoFrameRate: 30 // Video frame rate. 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. videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
profile : this.avProfile, profile : this.avProfile,
url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management. 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 { ...@@ -145,11 +146,11 @@ export class VideoRecorderDemo {
// Set AVRecorder callback functions. // Set AVRecorder callback functions.
setAvRecorderCallback() { setAvRecorderCallback() {
// Callback function for state changes. // 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); console.info(TAG + 'current state is: ' + state);
}) })
// Callback function for errors. // Callback function for errors.
this.avRecorder.on('error', (err) => { this.avRecorder.on('error', (err: BusinessError) => {
console.error(TAG + 'error ocConstantSourceNode, error message is ' + err); console.error(TAG + 'error ocConstantSourceNode, error message is ' + err);
}) })
} }
...@@ -188,7 +189,7 @@ export class VideoRecorderDemo { ...@@ -188,7 +189,7 @@ export class VideoRecorderDemo {
// 5. Start the camera stream output. // 5. Start the camera stream output.
await this.startCameraOutput(); await this.startCameraOutput();
// 6. Start recording. // 6. Start recording.
await this.videoRecorder.start(); await this.avRecorder.start();
} }
// Process of pausing recording. // Process of pausing recording.
......
# 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 ## When to Use
...@@ -19,8 +19,7 @@ The environment requirements for the Neural Network Runtime are as follows: ...@@ -19,8 +19,7 @@ The environment requirements for the Neural Network Runtime are as follows:
- Development environment: Ubuntu 18.04 or later. - 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. - 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 ### Environment Setup
...@@ -33,7 +32,6 @@ unzip native-linux-{version number}.zip ...@@ -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. 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 ```text
native/ native/
─ ─ build // Cross-compilation toolchain ─ ─ build // Cross-compilation toolchain
...@@ -488,4 +486,4 @@ The development process of the Neural Network Runtime consists of three phases: ...@@ -488,4 +486,4 @@ The development process of the Neural Network Runtime consists of three phases:
```shell ```shell
rm /data/local/tmp/*nncache rm /data/local/tmp/*nncache
``` ```
\ No newline at end of file
...@@ -23,8 +23,7 @@ Selected state attributes of AppStorage can be synced with different data source ...@@ -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. 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. 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 { ...@@ -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<ViewData> = [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 ```ts
...@@ -294,10 +369,9 @@ export struct TapImage { ...@@ -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 // xxx.ets
class ViewData { class ViewData {
title: string; title: string;
...@@ -338,22 +412,11 @@ struct Gallery2 { ...@@ -338,22 +412,11 @@ struct Gallery2 {
@Component @Component
export struct TapImage { export struct TapImage {
@StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1; @StorageLink('tapIndex') tapIndex: number = -1;
@State tapColor: Color = Color.Black; @State tapColor: Color = Color.Black;
private index: number; private index: number;
private uri: Resource; 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() { build() {
Column() { Column() {
Image(this.uri) Image(this.uri)
...@@ -361,14 +424,18 @@ export struct TapImage { ...@@ -361,14 +424,18 @@ export struct TapImage {
.onClick(() => { .onClick(() => {
this.tapIndex = this.index; 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 ## Restrictions
When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) and [Environment](arkts-environment.md), pay attention to the following: 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) ...@@ -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. - 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).
<!--no_check--> <!--no_check-->
...@@ -21,14 +21,14 @@ Syntax: ...@@ -21,14 +21,14 @@ Syntax:
```ts ```ts
@Builder myBuilderFunction({ ... }) @Builder MyBuilderFunction({ ... })
``` ```
Usage: Usage:
```ts ```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. - 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 ...@@ -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. - 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. - The \@Builder function body follows the same [syntax rules](arkts-create-custom-components.md#build-function) as the **build** function.
......
...@@ -15,12 +15,11 @@ Environment is a singleton object created by the ArkUI framework at application ...@@ -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. - Use **Environment.EnvProp** to save the environment variables of the device to AppStorage.
```ts ```ts
// Save the language code of the device to AppStorage. The default value is en. // Save languageCode to AppStorage. The default value is en.
// Whenever its value changes in the device environment, it will update its value in AppStorage.
Environment.EnvProp('languageCode', '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 ```ts
@StorageProp('languageCode') lang : string = 'en'; @StorageProp('languageCode') lang : string = 'en';
...@@ -29,6 +28,7 @@ Environment is a singleton object created by the ArkUI framework at application ...@@ -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. The chain of updates is as follows: Environment > AppStorage > Component.
> **NOTE** > **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. > 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') { ...@@ -69,3 +69,29 @@ if (lang.get() === 'en') {
console.info('Hello!'); 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');
})
})
}
}
```
...@@ -162,6 +162,26 @@ class ClassB { ...@@ -162,6 +162,26 @@ class ClassB {
this.a = a; 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 { ...@@ -169,60 +189,64 @@ class ClassB {
```ts ```ts
@Component @Component
struct ViewA { struct ViewC {
label: string = 'ViewA1'; label: string = 'ViewC1';
@ObjectLink a: ClassA; @ObjectLink c: ClassC;
build() { build() {
Row() { Row() {
Button(`ViewA [${this.label}] this.a.c=${this.a.c} +1`) Column() {
.onClick(() => { Text(`ViewC [${this.label}] this.a.c = ${this.c.c}`)
this.a.c += 1; .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 @Entry
@Component @Component
struct ViewB { struct ViewB {
@State b: ClassB = new ClassB(new ClassA(0)); @State b: ClassB = new ClassB(new ClassA(0));
@State child : ClassD = new ClassD(new ClassC(0));
build() { build() {
Column() { Column() {
ViewA({ label: 'ViewA #1', a: this.b.a }) ViewC({ label: 'ViewC #3', c: this.child.c})
ViewA({ label: 'ViewA #2', a: this.b.a }) Button(`ViewC: this.child.c.c add 10`)
.backgroundColor('#ff7fcf58')
Button(`ViewB: this.b.a.c+= 1`)
.onClick(() => {
this.b.a.c += 1;
})
Button(`ViewB: this.b.a = new ClassA(0)`)
.onClick(() => { .onClick(() => {
this.b.a = new ClassA(0); this.child.c.c += 10
}) console.log('this.child.c.c:' + this.child.c.c)
Button(`ViewB: this.b = new ClassB(ClassA(0))`)
.onClick(() => {
this.b = new ClassB(new ClassA(0));
}) })
} }
} }
} }
``` ```
The @Observed decorated **ClassC** class can observe changes in attributes inherited from the base class.
Event handlers in **ViewB**: 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. - 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 { ...@@ -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. 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. - 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. 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. - 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.
......
...@@ -24,7 +24,7 @@ Persistence of data is a relatively slow operation. Applications should avoid th ...@@ -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. 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 ## Application Scenarios
......
...@@ -3,6 +3,9 @@ ...@@ -3,6 +3,9 @@
**ForEach** enables repeated content based on array-type data. **ForEach** enables repeated content based on array-type data.
> **NOTE**
>
> Since API version 9, this API is supported in ArkTS widgets.
## API Description ## API Description
...@@ -19,15 +22,15 @@ ForEach( ...@@ -19,15 +22,15 @@ ForEach(
| Name | Type | Mandatory | Description | | 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**.| | 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:&nbsp;any,&nbsp;index?:&nbsp;number)&nbsp;=&gt;&nbsp;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.<br>**NOTE**<br>- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\<LitemItem>** child component is allowed only when the parent container component of **ForEach** is **\<List>**.<br>- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.<br>- The optional **index** parameter should only be specified in the function signature if used in its body.| | itemGenerator | (item: any, index?: number) =&gt; 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.<br>**NOTE**<br>- The type of the child component must be the one allowed inside the parent container component of **ForEach**. For example, a **\<ListItem>** child component is allowed only when the parent container component of **ForEach** is **\<List>**.<br>- The child build function is allowed to return an **if** or another **ForEach**. **ForEach** can be placed inside **if**.<br>- The optional **index** parameter should only be specified in the function signature if used in its body.|
| keyGenerator | (item:&nbsp;any,&nbsp;index?:&nbsp;number)&nbsp;=&gt;&nbsp;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**.<br>**NOTE**<br>- Two items inside the same array must never work out the same ID.<br>- 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.<br>- 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.<br>- When **index** is used in the build function, it should also be used in the ID generation function.<br>- The ID generation function is not allowed to mutate any component state.| | keyGenerator | (item: any, index?: number) =&gt; 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**.<br>**NOTE**<br>- Two items inside the same array must never work out the same ID.<br>- 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.<br>- 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.<br>- When **index** is used in the build function, it should also be used in the ID generation function.<br>- The ID generation function is not allowed to mutate any component state.|
## Restrictions ## Restrictions
- **ForEach** must be used in container components. - **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**. - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**.
......
# @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks) # @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)
The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling. 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.
When developing an application, you can override the APIs of this module and add your own task logic to the APIs.
> **NOTE** > **NOTE**
> >
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - The APIs of this module can be used only in the stage model. > - The APIs of this module can be used only in the stage model.
## Modules to Import ## Modules to Import
```ts ```ts
...@@ -36,7 +34,7 @@ Called when the system starts scheduling the deferred task. ...@@ -36,7 +34,7 @@ Called when the system starts scheduling the deferred task.
| Name | Type | Mandatory | Description | | 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** **Example**
...@@ -60,7 +58,7 @@ Called when the system stops scheduling the deferred task. ...@@ -60,7 +58,7 @@ Called when the system stops scheduling the deferred task.
| Name | Type | Mandatory | Description | | 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** **Example**
......
...@@ -12,6 +12,8 @@ The **CommonEvent** module provides common event capabilities, including the cap ...@@ -12,6 +12,8 @@ The **CommonEvent** module provides common event capabilities, including the cap
```ts ```ts
import CommonEvent from '@ohos.commonEvent'; import CommonEvent from '@ohos.commonEvent';
import CommonEventManager from '@ohos.commonEventManager';
import Base from '@ohos.base';
``` ```
## Support ## Support
...@@ -43,7 +45,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r ...@@ -43,7 +45,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r
```ts ```ts
// Callback for common event publication // Callback for common event publication
function publishCB(err) { function publishCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`publish failed, code is ${err.code}`); console.error(`publish failed, code is ${err.code}`);
} else { } else {
...@@ -80,14 +82,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca ...@@ -80,14 +82,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca
```ts ```ts
// Attributes of a common event. // Attributes of a common event.
let options = { let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event. 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. isOrdered: true // The common event is an ordered one.
} }
// Callback for common event publication // Callback for common event publication
function publishCB(err) { function publishCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`publish failed, code is ${err.code}`); console.error(`publish failed, code is ${err.code}`);
} else { } else {
...@@ -125,7 +127,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ...@@ -125,7 +127,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb
```ts ```ts
// Callback for common event publication // Callback for common event publication
function publishCB(err) { function publishCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`publishAsUser failed, code is ${err.code}`); console.error(`publishAsUser failed, code is ${err.code}`);
} else { } else {
...@@ -168,13 +170,13 @@ Publishes a common event with given attributes to a specific user. This API uses ...@@ -168,13 +170,13 @@ Publishes a common event with given attributes to a specific user. This API uses
```ts ```ts
// Attributes of a common event. // Attributes of a common event.
let options = { let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event. 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.
} }
// Callback for common event publication // Callback for common event publication
function publishCB(err) { function publishCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`publishAsUser failed, code is ${err.code}`); console.error(`publishAsUser failed, code is ${err.code}`);
} else { } else {
...@@ -212,15 +214,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul ...@@ -212,15 +214,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul
```ts ```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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Callback for subscriber creation. // Callback for subscriber creation.
function createCB(err, commonEventSubscriber) { function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) { if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`); console.error(`createSubscriber failed, code is ${err.code}`);
} else { } else {
...@@ -259,18 +261,18 @@ Creates a subscriber. This API uses a promise to return the result. ...@@ -259,18 +261,18 @@ Creates a subscriber. This API uses a promise to return the result.
**Example** **Example**
```ts ```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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Create a subscriber. // Create a subscriber.
CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => {
console.info("createSubscriber"); console.info("createSubscriber");
subscriber = commonEventSubscriber; subscriber = commonEventSubscriber;
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`createSubscriber failed, code is ${err.code}`); 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 ...@@ -297,15 +299,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th
**Example** **Example**
```ts ```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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Callback for common event subscription. // Callback for common event subscription.
function subscribeCB(err, data) { function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err.code) { if (err.code) {
console.error(`subscribe failed, code is ${err.code}`); console.error(`subscribe failed, code is ${err.code}`);
} else { } else {
...@@ -314,7 +316,7 @@ function subscribeCB(err, data) { ...@@ -314,7 +316,7 @@ function subscribeCB(err, data) {
} }
// Callback for subscriber creation. // Callback for subscriber creation.
function createCB(err, commonEventSubscriber) { function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) { if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`); console.error(`createSubscriber failed, code is ${err.code}`);
} else { } else {
...@@ -351,15 +353,15 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur ...@@ -351,15 +353,15 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur
**Example** **Example**
```ts ```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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Callback for common event subscription. // Callback for common event subscription.
function subscribeCB(err, data) { function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err.code) { if (err.code) {
console.error(`subscribe failed, code is ${err.code}`); console.error(`subscribe failed, code is ${err.code}`);
} else { } else {
...@@ -368,7 +370,7 @@ function subscribeCB(err, data) { ...@@ -368,7 +370,7 @@ function subscribeCB(err, data) {
} }
// Callback for subscriber creation. // Callback for subscriber creation.
function createCB(err, commonEventSubscriber) { function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) { if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`); console.error(`createSubscriber failed, code is ${err.code}`);
} else { } else {
...@@ -380,7 +382,7 @@ function createCB(err, commonEventSubscriber) { ...@@ -380,7 +382,7 @@ function createCB(err, commonEventSubscriber) {
} }
// Callback for common event unsubscription. // Callback for common event unsubscription.
function unsubscribeCB(err) { function unsubscribeCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`unsubscribe failed, code is ${err.code}`); console.error(`unsubscribe failed, code is ${err.code}`);
} else { } else {
......
...@@ -10,6 +10,7 @@ The **CommonEventManager** module provides common event capabilities, including ...@@ -10,6 +10,7 @@ The **CommonEventManager** module provides common event capabilities, including
```ts ```ts
import CommonEventManager from '@ohos.commonEventManager'; import CommonEventManager from '@ohos.commonEventManager';
import Base from '@ohos.base';
``` ```
## Support ## Support
...@@ -48,7 +49,7 @@ Publishes a common event and executes an asynchronous callback after the event i ...@@ -48,7 +49,7 @@ Publishes a common event and executes an asynchronous callback after the event i
```ts ```ts
// Callback for common event publication // Callback for common event publication
function publishCB(err) { function publishCB(err:Base.BusinessError) {
if (err) { if (err) {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`); console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -95,14 +96,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca ...@@ -95,14 +96,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca
```ts ```ts
// Attributes of a common event. // Attributes of a common event.
let options = { let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event. 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. isOrdered: true // The common event is an ordered one.
} }
// Callback for common event publication // Callback for common event publication
function publishCB(err) { function publishCB(err:Base.BusinessError) {
if (err) { if (err) {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`); console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -151,7 +152,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ...@@ -151,7 +152,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb
```ts ```ts
// Callback for common event publication // Callback for common event publication
function publishCB(err) { function publishCB(err:Base.BusinessError) {
if (err) { if (err) {
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -205,13 +206,13 @@ Publishes a common event with given attributes to a specific user. This API uses ...@@ -205,13 +206,13 @@ Publishes a common event with given attributes to a specific user. This API uses
```ts ```ts
// Attributes of a common event. // Attributes of a common event.
let options = { let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event. 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.
} }
// Callback for common event publication. // Callback for common event publication.
function publishCB(err) { function publishCB(err:Base.BusinessError) {
if (err) { if (err) {
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`); console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -248,15 +249,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul ...@@ -248,15 +249,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul
**Example** **Example**
```ts ```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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Callback for subscriber creation. // Callback for subscriber creation.
function createCB(err, commonEventSubscriber) { function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if(!err) { if(!err) {
console.info("createSubscriber"); console.info("createSubscriber");
subscriber = commonEventSubscriber; subscriber = commonEventSubscriber;
...@@ -295,18 +296,18 @@ Creates a subscriber. This API uses a promise to return the result. ...@@ -295,18 +296,18 @@ Creates a subscriber. This API uses a promise to return the result.
**Example** **Example**
```ts ```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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Create a subscriber. // Create a subscriber.
CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => {
console.info("createSubscriber"); console.info("createSubscriber");
subscriber = commonEventSubscriber; subscriber = commonEventSubscriber;
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -341,15 +342,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th
```ts ```ts
// Subscriber information. // 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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Callback for common event subscription. // Callback for common event subscription.
function SubscribeCB(err, data) { function SubscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err) { if (err) {
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -358,7 +359,7 @@ function SubscribeCB(err, data) { ...@@ -358,7 +359,7 @@ function SubscribeCB(err, data) {
} }
// Callback for subscriber creation. // Callback for subscriber creation.
function createCB(err, commonEventSubscriber) { function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if(!err) { if(!err) {
console.info("createSubscriber"); console.info("createSubscriber");
subscriber = commonEventSubscriber; subscriber = commonEventSubscriber;
...@@ -409,13 +410,13 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur ...@@ -409,13 +410,13 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur
**Example** **Example**
```ts ```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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Callback for common event subscription. // Callback for common event subscription.
function subscribeCB(err, data) { function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err) { if (err) {
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`); console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -423,7 +424,7 @@ function subscribeCB(err, data) { ...@@ -423,7 +424,7 @@ function subscribeCB(err, data) {
} }
} }
// Callback for subscriber creation. // Callback for subscriber creation.
function createCB(err, commonEventSubscriber) { function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err) { if (err) {
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`); console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -438,7 +439,7 @@ function createCB(err, commonEventSubscriber) { ...@@ -438,7 +439,7 @@ function createCB(err, commonEventSubscriber) {
} }
} }
// Callback for common event unsubscription. // Callback for common event unsubscription.
function unsubscribeCB(err) { function unsubscribeCB(err:Base.BusinessError) {
if (err) { if (err) {
console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`); console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -493,7 +494,7 @@ Removes a sticky common event. This API uses an asynchronous callback to return ...@@ -493,7 +494,7 @@ Removes a sticky common event. This API uses an asynchronous callback to return
```ts ```ts
CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => { CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => {
if (err) { if (err) {
console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`); console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
return; return;
...@@ -542,7 +543,7 @@ Removes a sticky common event. This API uses a promise to return the result. ...@@ -542,7 +543,7 @@ Removes a sticky common event. This API uses a promise to return the result.
```ts ```ts
CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => { CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => {
console.info(`Remove sticky event AsyncCallback success`); 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}`); 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 ...@@ -577,7 +578,7 @@ Enables or disables static subscription for the current application. This API us
```ts ```ts
CommonEventManager.setStaticSubscriberState(true, (err) => { CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => {
if (!err) { if (!err) {
console.info(`Set static subscriber state callback failed, err is null.`); console.info(`Set static subscriber state callback failed, err is null.`);
return; return;
...@@ -627,7 +628,7 @@ Enables or disables static subscription for the current application. This API us ...@@ -627,7 +628,7 @@ Enables or disables static subscription for the current application. This API us
```ts ```ts
CommonEventManager.setStaticSubscriberState(false).then(() => { CommonEventManager.setStaticSubscriberState(false).then(() => {
console.info(`Set static subscriber state promise success`); 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}`); console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`);
}); });
``` ```
...@@ -4,9 +4,9 @@ The **cooperate** module implements screen hopping for two or more networked dev ...@@ -4,9 +4,9 @@ The **cooperate** module implements screen hopping for two or more networked dev
> **NOTE** > **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 ## Modules to Import
...@@ -26,7 +26,7 @@ Prepares for screen hopping. This API uses an asynchronous callback to return th ...@@ -26,7 +26,7 @@ Prepares for screen hopping. This API uses an asynchronous callback to return th
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------- | ---- | --------------------------- | | -------- | ------------------------- | ---- | --------------------------- |
| callback | AsyncCallback&lt;void&gt; | Yes|Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | Yes|Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
**Example** **Example**
...@@ -56,7 +56,7 @@ Prepares for screen hopping. This API uses a promise to return the result. ...@@ -56,7 +56,7 @@ Prepares for screen hopping. This API uses a promise to return the result.
| Parameters | Description | | Parameters | Description |
| ------------------- | ------------------------------- | | ------------------- | ------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise that returns no value.|
...@@ -75,7 +75,6 @@ try { ...@@ -75,7 +75,6 @@ try {
``` ```
## cooperate.unprepare ## cooperate.unprepare
unprepare(callback: AsyncCallback&lt;void&gt;): void; unprepare(callback: AsyncCallback&lt;void&gt;): void;
...@@ -86,7 +85,7 @@ Cancels the preparation for screen hopping. This API uses an asynchronous callba ...@@ -86,7 +85,7 @@ Cancels the preparation for screen hopping. This API uses an asynchronous callba
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ------------------------- | ---- | ------------------------------------------ | | -------- | ------------------------- | ---- | ------------------------------------------ |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -104,8 +103,6 @@ try { ...@@ -104,8 +103,6 @@ try {
} }
``` ```
## cooperate.unprepare ## cooperate.unprepare
unprepare(): Promise&lt;void&gt;; unprepare(): Promise&lt;void&gt;;
...@@ -118,7 +115,7 @@ Cancels the preparation for screen hopping. This API uses a promise to return th ...@@ -118,7 +115,7 @@ Cancels the preparation for screen hopping. This API uses a promise to return th
| Parameters | Description | | Parameters | Description |
| ------------------- | --------------------------------------------- | | ------------------- | --------------------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise that returns no value.|
```js ```js
try { try {
...@@ -133,7 +130,6 @@ try { ...@@ -133,7 +130,6 @@ try {
``` ```
## cooperate.activate ## cooperate.activate
activate(targetNetworkId: string, inputDeviceId: number, callback: AsyncCallback&lt;void&gt;): void; activate(targetNetworkId: string, inputDeviceId: number, callback: AsyncCallback&lt;void&gt;): void;
...@@ -148,7 +144,7 @@ Starts screen hopping. This API uses an asynchronous callback to return the resu ...@@ -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. | | targetNetworkId | string | Yes | Descriptor of the target device for screen hopping. |
| inputDeviceId | number | Yes | Identifier of the input device for screen hopping.| | inputDeviceId | number | Yes | Identifier of the input device for screen hopping.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -156,7 +152,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode ...@@ -156,7 +152,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
| ID| Error Message| | 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** **Example**
...@@ -197,7 +193,7 @@ Starts screen hopping. This API uses a promise to return the result. ...@@ -197,7 +193,7 @@ Starts screen hopping. This API uses a promise to return the result.
| Name | Description | | Name | Description |
| ---------------------- | ------------------------------- | | ---------------------- | ------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise that returns no value. |
**Error codes** **Error codes**
...@@ -205,7 +201,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode ...@@ -205,7 +201,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
| ID| Error Message| | 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** **Example**
...@@ -235,8 +231,8 @@ Stops screen hopping. This API uses an asynchronous callback to return the resul ...@@ -235,8 +231,8 @@ Stops screen hopping. This API uses an asynchronous callback to return the resul
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- | | -------- | ---------------------------- | ---- | ---------------------------- |
| isUnchained | boolean | Yes| Whether to disable the cross-device link.| | isUnchained | boolean | Yes| Whether to disable the cross-device link.<br> The value **true** means to disable the cross-device link, and the value **false** means the opposite.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. | | callback | AsyncCallback&lt;void&gt; | 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. ...@@ -268,7 +264,7 @@ Stops screen hopping. This API uses a promise to return the result.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ----------- | ------- | ---- | ------------------ | | ----------- | ------- | ---- | ------------------ |
| isUnchained | boolean | Yes | Whether to disable the cross-device link.| | isUnchained | boolean | Yes | Whether to disable the cross-device link.<br> 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. ...@@ -276,7 +272,7 @@ Stops screen hopping. This API uses a promise to return the result.
| Name | Description | | Name | Description |
| -------- | ---------------------------- | | -------- | ---------------------------- |
| Promise&lt;void&gt; | Promise used to return the result. | | Promise&lt;void&gt; | Promise that returns no value. |
...@@ -307,7 +303,7 @@ Obtains the screen hopping status of the target device. This API uses an asynchr ...@@ -307,7 +303,7 @@ Obtains the screen hopping status of the target device. This API uses an asynchr
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------- | ---- | ---------------------------- | | -------- | --------- | ---- | ---------------------------- |
| networkId | string | Yes | Descriptor of the target device for screen hopping. | | networkId | string | Yes | Descriptor of the target device for screen hopping. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.|
**Example** **Example**
...@@ -336,9 +332,9 @@ Obtains the screen hopping status of the target device. This API uses a promise ...@@ -336,9 +332,9 @@ Obtains the screen hopping status of the target device. This API uses a promise
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------- | ---- | ---------------------------- | | -------- | --------- | ---- | ---------------------------- |
| networkId | string | Yes | Descriptor of the target device for screen hopping. | | 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 ...@@ -346,7 +342,7 @@ Obtains the screen hopping status of the target device. This API uses a promise
| Parameters | Description | | Parameters | Description |
| ------------------- | ------------------------------- | | ------------------- | ------------------------------- |
| Promise&lt;boolean&gt; | Promise used to return the result.| | Promise&lt;boolean&gt; | Promise used to return the result. The value **true** indicates that screen hopping is enabled, and the value **false** indicates the opposite.|
......
# @ohos.distributedMissionManager (Distributed Mission Management) # @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** > **NOTE**
> >
...@@ -14,7 +14,6 @@ The **distributedMissionManager** module implements system mission management ac ...@@ -14,7 +14,6 @@ The **distributedMissionManager** module implements system mission management ac
import distributedMissionManager from '@ohos.distributedMissionManager' import distributedMissionManager from '@ohos.distributedMissionManager'
``` ```
## distributedMissionManager.registerMissionListener ## distributedMissionManager.registerMissionListener
registerMissionListener(parameter: MissionDeviceInfo, options: MissionCallback, callback: AsyncCallback&lt;void&gt;): void; registerMissionListener(parameter: MissionDeviceInfo, options: MissionCallback, callback: AsyncCallback&lt;void&gt;): void;
...@@ -30,8 +29,8 @@ Registers a mission status listener. This API uses an asynchronous callback to r ...@@ -30,8 +29,8 @@ Registers a mission status listener. This API uses an asynchronous callback to r
| Name | Type | Mandatory | Description | | 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](#missioncallback) | Yes | Callback to register. | | options | [MissionCallback](#missioncallback) | Yes | Callback to register.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the listener is registered, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -80,14 +79,14 @@ Registers a mission status listener. This API uses a promise to return the resul ...@@ -80,14 +79,14 @@ Registers a mission status listener. This API uses a promise to return the resul
| Name | Type | Mandatory | Description | | 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 | <a href="#missioncallback">MissionCallback</a> | Yes | Callback to register.| | options | <a href="#missioncallback">MissionCallback</a> | Yes | Callback to register.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | ---------------- | | ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise that returns no value.|
**Example** **Example**
...@@ -123,7 +122,6 @@ Registers a mission status listener. This API uses a promise to return the resul ...@@ -123,7 +122,6 @@ Registers a mission status listener. This API uses a promise to return the resul
} }
``` ```
## distributedMissionManager.unRegisterMissionListener ## distributedMissionManager.unRegisterMissionListener
unRegisterMissionListener(parameter: MissionDeviceInfo, callback: AsyncCallback&lt;void&gt;): void; unRegisterMissionListener(parameter: MissionDeviceInfo, callback: AsyncCallback&lt;void&gt;): void;
...@@ -138,8 +136,8 @@ Deregisters a mission status listener. This API uses an asynchronous callback to ...@@ -138,8 +136,8 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
| Name | Type | Mandatory | Description | | 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. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the listener is deregistered, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -159,7 +157,6 @@ Deregisters a mission status listener. This API uses an asynchronous callback to ...@@ -159,7 +157,6 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
} }
``` ```
## distributedMissionManager.unRegisterMissionListener ## distributedMissionManager.unRegisterMissionListener
unRegisterMissionListener(parameter: MissionDeviceInfo): Promise&lt;void&gt; unRegisterMissionListener(parameter: MissionDeviceInfo): Promise&lt;void&gt;
...@@ -180,7 +177,7 @@ Deregisters a mission status listener. This API uses a promise to return the res ...@@ -180,7 +177,7 @@ Deregisters a mission status listener. This API uses a promise to return the res
| Type | Description | | Type | Description |
| ------------------- | ---------------- | | ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; |Promise that returns no value.|
**Example** **Example**
...@@ -215,7 +212,7 @@ Starts to synchronize the remote mission list. This API uses an asynchronous cal ...@@ -215,7 +212,7 @@ Starts to synchronize the remote mission list. This API uses an asynchronous cal
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ------------------------------------- | ---- | --------- | | --------- | ------------------------------------- | ---- | --------- |
| parameter | [MissionParameter](#missionparameter) | Yes | Parameters required for synchronization. | | parameter | [MissionParameter](#missionparameter) | Yes | Parameters required for synchronization. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the synchronization is started, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -257,7 +254,7 @@ Starts to synchronize the remote mission list. This API uses a promise to return ...@@ -257,7 +254,7 @@ Starts to synchronize the remote mission list. This API uses a promise to return
| Type | Description | | Type | Description |
| ------------------- | ---------------- | | ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise that returns no value.|
**Example** **Example**
...@@ -294,7 +291,7 @@ Stops synchronizing the remote mission list. This API uses an asynchronous callb ...@@ -294,7 +291,7 @@ Stops synchronizing the remote mission list. This API uses an asynchronous callb
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | --------- | | --------- | --------------------------------------- | ---- | --------- |
| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Parameters required for synchronization. | | parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Parameters required for synchronization. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the synchronization is stopped, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -334,7 +331,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t ...@@ -334,7 +331,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t
| Type | Description | | Type | Description |
| ------------------- | ---------------- | | ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise that returns no value.|
**Example** **Example**
...@@ -358,7 +355,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t ...@@ -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&lt;void&gt;): void; continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callback: AsyncCallback&lt;void&gt;): 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 **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 ...@@ -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.| | 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.| | options | [ContinueCallback](js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the mission is continued, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -416,7 +413,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er ...@@ -416,7 +413,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promise&lt;void&gt; continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promise&lt;void&gt;
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 **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 ...@@ -433,7 +430,7 @@ Continues a mission on a remote device. This API uses a promise to return the re
| Type | Description | | Type | Description |
| ------------------- | ---------------- | | ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; |Promise that returns no value.|
**Error codes** **Error codes**
...@@ -490,7 +487,7 @@ Continues a mission on a remote device, with the bundle name specified. This API ...@@ -490,7 +487,7 @@ Continues a mission on a remote device, with the bundle name specified. This API
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- | | --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueMissionInfo](./js-apis-inner-application-continueMissionInfo.md) | Yes | Parameters required for mission continuation.| | parameter | [ContinueMissionInfo](./js-apis-inner-application-continueMissionInfo.md) | Yes | Parameters required for mission continuation.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback invoked when the mission continuation is complete.| | callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. If the mission is continued, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -546,7 +543,7 @@ Continues a mission on a remote device, with the bundle name specified. This API ...@@ -546,7 +543,7 @@ Continues a mission on a remote device, with the bundle name specified. This API
| Type | Description | | Type | Description |
| ------------------- | ---------------- | | ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise that returns no value.|
**Error codes** **Error codes**
...@@ -586,7 +583,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er ...@@ -586,7 +583,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
on(type: 'continueStateChange', callback: Callback&lt;{ state: ContinueState, info: ContinuableInfo }&gt;): void on(type: 'continueStateChange', callback: Callback&lt;{ state: ContinueState, info: ContinuableInfo }&gt;): 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 **Required permissions**: ohos.permission.MANAGE_MISSIONS
...@@ -596,8 +593,8 @@ Registers a listener for the mission continuation state of the current applicati ...@@ -596,8 +593,8 @@ Registers a listener for the mission continuation state of the current applicati
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- | | --------- | ---------------------------------------- | ---- | -------- |
| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. | | type | string | Yes | Event type. The value **'continueStateChange'** indicates the continuation state change event of the current mission. |
| callback | Callback&lt;{&nbsp;state:&nbsp;[ContinueState](#continuestate10),&nbsp;info:&nbsp;[ContinuableInfo](./js-apis-inner-application-continuableInfo.md)&nbsp;}&gt; | Yes | Callback used to return the mission continuation state and information. | | callback | Callback&lt;{&nbsp;state:&nbsp;[ContinueState](#continuestate10),&nbsp;info:&nbsp;[ContinuableInfo](./js-apis-inner-application-continuableInfo.md)&nbsp;}&gt; | Yes | Callback used to return the continuation state and information of the current mission. |
**Example** **Example**
...@@ -615,7 +612,7 @@ Registers a listener for the mission continuation state of the current applicati ...@@ -615,7 +612,7 @@ Registers a listener for the mission continuation state of the current applicati
off(type: 'continueStateChange', callback?: Callback&lt;{ state: ContinueState, info: ContinuableInfo }&gt;): void off(type: 'continueStateChange', callback?: Callback&lt;{ state: ContinueState, info: ContinuableInfo }&gt;): 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 **Required permissions**: ohos.permission.MANAGE_MISSIONS
...@@ -625,8 +622,8 @@ Deregisters a listener for the mission continuation state of the current applica ...@@ -625,8 +622,8 @@ Deregisters a listener for the mission continuation state of the current applica
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- | | --------- | ---------------------------------------- | ---- | -------- |
| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. | | type | string | Yes | Event type. The value **'continueStateChange'** indicates the continuation state change event of the current mission. |
| callback | Callback&lt;{&nbsp;state:&nbsp;[ContinueState](#continuestate10),&nbsp;info:&nbsp;[ContinuableInfo](./js-apis-inner-application-continuableInfo.md)&nbsp;}&gt; | No | Callback used for the listener to be deregistered. | | callback | Callback&lt;{&nbsp;state:&nbsp;[ContinueState](#continuestate10),&nbsp;info:&nbsp;[ContinuableInfo](./js-apis-inner-application-continuableInfo.md)&nbsp;}&gt; | No | Callback used to return the continuation state and information of the current mission.<br>If the callback is unspecified, all subscriptions to the specified event are canceled. |
**Example** **Example**
...@@ -688,5 +685,5 @@ Enumerates the mission continuation states. ...@@ -688,5 +685,5 @@ Enumerates the mission continuation states.
| Name | Value | Description | | Name | Value | Description |
| ------------- | --------- | ------------------------------------------------------------ | | ------------- | --------- | ------------------------------------------------------------ |
| ACTIVE | 0 | Mission continuation is activated for the current application. | | ACTIVE | 0 | Continuation is activated for the current mission. |
| INACTIVE | 1 | Mission continuation is not activated for the current application. | | INACTIVE | 1 | Continuation is not activated for the current mission. |
...@@ -4,7 +4,7 @@ The **hiAppEvent** module provides the application event logging functions, such ...@@ -4,7 +4,7 @@ The **hiAppEvent** module provides the application event logging functions, such
> **NOTE** > **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. > - 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 ...@@ -20,7 +20,7 @@ Before using application event logging, you need to understand the requirements
**Event Name** **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** **Event Type**
...@@ -30,8 +30,8 @@ An event type is an enumerated value of [EventType](#eventtype). ...@@ -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: 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 (\_). - 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 (_).
- The parameter value can be of the string, number, boolean, or array type. - 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 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 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. - 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. ...@@ -156,12 +156,12 @@ Provides the configuration items for application event logging.
| Name | Type | Mandatory| Description | | 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.| | 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 <strong>10M</strong>. 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 ## EventType
Enumerates event types. Enumerates the event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
......
...@@ -122,10 +122,10 @@ Defines parameters for an **AppEventInfo** object. ...@@ -122,10 +122,10 @@ Defines parameters for an **AppEventInfo** object.
| Name | Type | Mandatory| Description | | 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 (_).| | 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. 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 (_).| | 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. | | 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:<br>- 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 (_).<br>- 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.<br>- 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:<br>- 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 (_).<br>- 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.<br>- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded.|
## hiAppEvent.configure ## hiAppEvent.configure
...@@ -436,7 +436,7 @@ hiAppEvent.clearData(); ...@@ -436,7 +436,7 @@ hiAppEvent.clearData();
## EventType ## EventType
Enumerates event types. Enumerates the event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent **System capability**: SystemCapability.HiviewDFX.HiAppEvent
......
...@@ -86,7 +86,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req ...@@ -86,7 +86,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
| Type | Description | | 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** **Example**
...@@ -364,9 +364,9 @@ Destroys an HTTP request. ...@@ -364,9 +364,9 @@ Destroys an HTTP request.
httpRequest.destroy(); httpRequest.destroy();
``` ```
### request2<sup>10+</sup> ### requestInStream<sup>10+</sup>
request2(url: string, callback: AsyncCallback\<number\>): void requestInStream(url: string, callback: AsyncCallback\<number\>): 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. 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 ...@@ -424,18 +424,18 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example** **Example**
```js ```js
httpRequest.request2("EXAMPLE_URL", (err, data) => { httpRequest.requestInStream("EXAMPLE_URL", (err, data) => {
if (!err) { if (!err) {
console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else { } else {
console.info("request2 ERROR : err = " + JSON.stringify(err)); console.info("requestInStream ERROR : err = " + JSON.stringify(err));
} }
}) })
``` ```
### request2<sup>10+</sup> ### requestInStream<sup>10+</sup>
request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): 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. 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 ...@@ -494,7 +494,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example** **Example**
```js ```js
httpRequest.request2("EXAMPLE_URL", httpRequest.requestInStream("EXAMPLE_URL",
{ {
method: http.RequestMethod.GET, method: http.RequestMethod.GET,
header: { header: {
...@@ -504,16 +504,16 @@ httpRequest.request2("EXAMPLE_URL", ...@@ -504,16 +504,16 @@ httpRequest.request2("EXAMPLE_URL",
connectTimeout: 60000 connectTimeout: 60000
}, (err, data) => { }, (err, data) => {
if (!err) { if (!err) {
console.info("request2 OK! ResponseCode is " + JSON.stringify(data)); console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else { } else {
console.info("request2 ERROR : err = " + JSON.stringify(err)); console.info("requestInStream ERROR : err = " + JSON.stringify(err));
} }
}) })
``` ```
### request2<sup>10+</sup> ### requestInStream<sup>10+</sup>
request2(url: string, options? : HttpRequestOptions): Promise\<number\> requestInStream(url: string, options? : HttpRequestOptions): Promise\<number\>
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. 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 ...@@ -577,7 +577,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example** **Example**
```js ```js
let promise = httpRequest.request2("EXAMPLE_URL", { let promise = httpRequest.requestInStream("EXAMPLE_URL", {
method: http.RequestMethod.GET, method: http.RequestMethod.GET,
connectTimeout: 60000, connectTimeout: 60000,
readTimeout: 60000, readTimeout: 60000,
...@@ -586,9 +586,9 @@ let promise = httpRequest.request2("EXAMPLE_URL", { ...@@ -586,9 +586,9 @@ let promise = httpRequest.request2("EXAMPLE_URL", {
} }
}); });
promise.then((data) => { promise.then((data) => {
console.info("request2 OK!" + JSON.stringify(data)); console.info("requestInStream OK!" + JSON.stringify(data));
}).catch((err) => { }).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 ...@@ -815,9 +815,9 @@ Unregisters the observer for events indicating completion of receiving HTTP stre
httpRequest.off('dataEnd'); httpRequest.off('dataEnd');
``` ```
### on('dataProgress')<sup>10+</sup> ### on('dataReceiveProgress')<sup>10+</sup>
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. 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 ...@@ -830,20 +830,20 @@ Registers an observer for events indicating progress of receiving HTTP streaming
| Name | Type | Mandatory| Description | | 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.<br>- **receiveSize**: number of received bytes.<br>- **totalSize**: total number of bytes to be received.| | callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.<br>- **receiveSize**: number of received bytes.<br>- **totalSize**: total number of bytes to be received.|
**Example** **Example**
```js ```js
httpRequest.on('dataProgress', (data) => { httpRequest.on('dataReceiveProgress', (data) => {
console.info('dataProgress:' + JSON.stringify(data)); console.info('dataReceiveProgress:' + JSON.stringify(data));
}); });
``` ```
### off('dataProgress')<sup>10+</sup> ### off('dataReceiveProgress')<sup>10+</sup>
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. 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 ...@@ -856,13 +856,13 @@ Unregisters the observer for events indicating progress of receiving HTTP stream
| Name | Type | Mandatory| Description | | 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. | | callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. |
**Example** **Example**
```js ```js
httpRequest.off('dataProgress'); httpRequest.off('dataReceiveProgress');
``` ```
## HttpRequestOptions<sup>6+</sup> ## HttpRequestOptions<sup>6+</sup>
......
...@@ -10,15 +10,17 @@ Before using the **CommonEventSubscriber** module, you must obtain a **subscribe ...@@ -10,15 +10,17 @@ Before using the **CommonEventSubscriber** module, you must obtain a **subscribe
```ts ```ts
import CommonEvent from '@ohos.commonEvent'; 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. // Subscriber information.
let subscribeInfo = { let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"] events: ["event"]
}; };
// Callback for subscriber creation. // Callback for subscriber creation.
function createCB(err, commonEventSubscriber) { function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) { if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`); console.error(`createSubscriber failed, code is ${err.code}`);
} else { } else {
...@@ -49,7 +51,7 @@ Obtains the code of this common event. This API uses an asynchronous callback to ...@@ -49,7 +51,7 @@ Obtains the code of this common event. This API uses an asynchronous callback to
```ts ```ts
// Callback for result code obtaining of an ordered common event. // Callback for result code obtaining of an ordered common event.
function getCodeCB(err, code) { function getCodeCB(err:Base.BusinessError, code:number) {
if (err.code) { if (err.code) {
console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); console.error(`getCode failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -76,9 +78,9 @@ Obtains the code of this common event. This API uses a promise to return the res ...@@ -76,9 +78,9 @@ Obtains the code of this common event. This API uses a promise to return the res
**Example** **Example**
```ts ```ts
subscriber.getCode().then((code) => { subscriber.getCode().then((code:number) => {
console.info("getCode " + JSON.stringify(code)); console.info("getCode " + JSON.stringify(code));
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`getCode failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -102,7 +104,7 @@ Sets the code for this common event. This API uses an asynchronous callback to r
```ts ```ts
// Callback for result code setting of an ordered common event. // Callback for result code setting of an ordered common event.
function setCodeCB(err) { function setCodeCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -137,7 +139,7 @@ Sets the code for this common event. This API uses a promise to return the resul ...@@ -137,7 +139,7 @@ Sets the code for this common event. This API uses a promise to return the resul
```ts ```ts
subscriber.setCode(1).then(() => { subscriber.setCode(1).then(() => {
console.info("setCode"); console.info("setCode");
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -160,7 +162,7 @@ Obtains the data of this common event. This API uses an asynchronous callback to
```ts ```ts
// Callback for result data obtaining of an ordered common event. // Callback for result data obtaining of an ordered common event.
function getDataCB(err, data) { function getDataCB(err:Base.BusinessError, data:string) {
if (err.code) { if (err.code) {
console.error(`getData failed, code is ${err.code}, message is ${err.message}`); console.error(`getData failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -187,9 +189,9 @@ Obtains the data of this common event. This API uses a promise to return the res ...@@ -187,9 +189,9 @@ Obtains the data of this common event. This API uses a promise to return the res
**Example** **Example**
```ts ```ts
subscriber.getData().then((data) => { subscriber.getData().then((data:string) => {
console.info("getData " + JSON.stringify(data)); console.info("getData " + JSON.stringify(data));
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`getData failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -213,7 +215,7 @@ Sets the data for this common event. This API uses an asynchronous callback to r
```ts ```ts
// Callback for result data setting of an ordered common event // Callback for result data setting of an ordered common event
function setDataCB(err) { function setDataCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -248,7 +250,7 @@ Sets the data for this common event. This API uses a promise to return the resul ...@@ -248,7 +250,7 @@ Sets the data for this common event. This API uses a promise to return the resul
```ts ```ts
subscriber.setData("publish_data_changed").then(() => { subscriber.setData("publish_data_changed").then(() => {
console.info("setData"); console.info("setData");
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -273,7 +275,7 @@ Sets the code and data for this common event. This API uses an asynchronous call
```ts ```ts
// Callback for code and data setting of an ordered common event. // Callback for code and data setting of an ordered common event.
function setCodeDataCB(err) { function setCodeDataCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -309,7 +311,7 @@ Sets the code and data for this common event. This API uses a promise to return ...@@ -309,7 +311,7 @@ Sets the code and data for this common event. This API uses a promise to return
```ts ```ts
subscriber.setCodeAndData(1, "publish_data_changed").then(() => { subscriber.setCodeAndData(1, "publish_data_changed").then(() => {
console.info("setCodeAndData"); console.info("setCodeAndData");
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -332,7 +334,7 @@ Checks whether this common event is an ordered one. This API uses an asynchronou
```ts ```ts
// Callback for checking whether the current common event is an ordered one. // 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) { if (err.code) {
console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`); console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -359,9 +361,9 @@ Checks whether this common event is an ordered one. This API uses a promise to r ...@@ -359,9 +361,9 @@ Checks whether this common event is an ordered one. This API uses a promise to r
**Example** **Example**
```ts ```ts
subscriber.isOrderedCommonEvent().then((isOrdered) => { subscriber.isOrderedCommonEvent().then((isOrdered:boolean) => {
console.info("isOrdered " + JSON.stringify(isOrdered)); console.info("isOrdered " + JSON.stringify(isOrdered));
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -384,7 +386,7 @@ Checks whether this common event is a sticky one. This API uses an asynchronous
```ts ```ts
// Callback for checking whether the current common event is a sticky one. // 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) { if (err.code) {
console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`); console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -411,9 +413,9 @@ Checks whether this common event is a sticky one. This API uses a promise to ret ...@@ -411,9 +413,9 @@ Checks whether this common event is a sticky one. This API uses a promise to ret
**Example** **Example**
```ts ```ts
subscriber.isStickyCommonEvent().then((isSticky) => { subscriber.isStickyCommonEvent().then((isSticky:boolean) => {
console.info("isSticky " + JSON.stringify(isSticky)); console.info("isSticky " + JSON.stringify(isSticky));
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -436,7 +438,7 @@ Aborts this common event. After the abort, the common event is not sent to the n
```ts ```ts
// Callback for common event aborting. // Callback for common event aborting.
function abortCB(err) { function abortCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -465,7 +467,7 @@ Aborts this common event. After the abort, the common event is not sent to the n ...@@ -465,7 +467,7 @@ Aborts this common event. After the abort, the common event is not sent to the n
```ts ```ts
subscriber.abortCommonEvent().then(() => { subscriber.abortCommonEvent().then(() => {
console.info("abortCommonEvent"); console.info("abortCommonEvent");
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -488,7 +490,7 @@ Clears the aborted state of this common event. This API takes effect only for or
```ts ```ts
// Callback for clearing the aborted state of the current common event. // Callback for clearing the aborted state of the current common event.
function clearAbortCB(err) { function clearAbortCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -517,7 +519,7 @@ Clears the aborted state of this common event. This API takes effect only for or ...@@ -517,7 +519,7 @@ Clears the aborted state of this common event. This API takes effect only for or
```ts ```ts
subscriber.clearAbortCommonEvent().then(() => { subscriber.clearAbortCommonEvent().then(() => {
console.info("clearAbortCommonEvent"); console.info("clearAbortCommonEvent");
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -540,7 +542,7 @@ Checks whether this common event is in the aborted state. This API takes effect
```ts ```ts
// Callback for checking whether the current common event is in the aborted state. // 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) { if (err.code) {
console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -567,9 +569,9 @@ Checks whether this common event is in the aborted state. This API takes effect ...@@ -567,9 +569,9 @@ Checks whether this common event is in the aborted state. This API takes effect
**Example** **Example**
```ts ```ts
subscriber.getAbortCommonEvent().then((abortEvent) => { subscriber.getAbortCommonEvent().then((abortEvent:boolean) => {
console.info("abortCommonEvent " + JSON.stringify(abortEvent)); console.info("abortCommonEvent " + JSON.stringify(abortEvent));
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -592,7 +594,7 @@ Obtains the subscriber information. This API uses an asynchronous callback to re
```ts ```ts
// Callback for subscriber information obtaining. // Callback for subscriber information obtaining.
function getCB(err, subscribeInfo) { function getCB(err:Base.BusinessError, subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) {
if (err.code) { if (err.code) {
console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -619,9 +621,9 @@ Obtains the subscriber information. This API uses a promise to return the result ...@@ -619,9 +621,9 @@ Obtains the subscriber information. This API uses a promise to return the result
**Example** **Example**
```ts ```ts
subscriber.getSubscribeInfo().then((subscribeInfo) => { subscriber.getSubscribeInfo().then((subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) => {
console.info("subscribeInfo " + JSON.stringify(subscribeInfo)); console.info("subscribeInfo " + JSON.stringify(subscribeInfo));
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`); 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 ...@@ -644,7 +646,7 @@ Finishes this common event. This API takes effect only for ordered common events
```ts ```ts
// Callback for ordered common event finishing. // Callback for ordered common event finishing.
function finishCB(err) { function finishCB(err:Base.BusinessError) {
if (err.code) { if (err.code) {
console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else { } else {
...@@ -674,7 +676,7 @@ Finishes this common event. This API takes effect only for ordered common events ...@@ -674,7 +676,7 @@ Finishes this common event. This API takes effect only for ordered common events
```ts ```ts
subscriber.finishCommonEvent().then(() => { subscriber.finishCommonEvent().then(() => {
console.info("FinishCommonEvent"); console.info("FinishCommonEvent");
}).catch((err) => { }).catch((err:Base.BusinessError) => {
console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`); console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`);
}); });
``` ```
...@@ -158,7 +158,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy ...@@ -158,7 +158,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy
| Name | Type | Mandatory| Description | | 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** **Error codes**
...@@ -192,7 +192,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses a prom ...@@ -192,7 +192,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses a prom
| Type | Description | | Type | Description |
| --------------------------------- | ------------------------------------- | | --------------------------------- | ------------------------------------- |
| Promise\<[HttpProxy](#httpproxy)> | Promise used to return the result.| | Promise\<[HttpProxy](#httpproxy10)> | Promise used to return the result.|
**Error codes** **Error codes**
...@@ -229,7 +229,7 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch ...@@ -229,7 +229,7 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch
| Name | Type | Mandatory| Description | | 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\<void> | 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.| | callback | AsyncCallback\<void> | 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** **Error codes**
...@@ -274,7 +274,7 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise ...@@ -274,7 +274,7 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise
| Name | Type | Mandatory| Description | | 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** **Return value**
...@@ -324,7 +324,7 @@ This API uses an asynchronous callback to return the result. ...@@ -324,7 +324,7 @@ This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description | | 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** **Error codes**
...@@ -347,7 +347,7 @@ connection.getDefaultHttpProxy((error, data) => { ...@@ -347,7 +347,7 @@ connection.getDefaultHttpProxy((error, data) => {
getDefaultHttpProxy(): Promise\<HttpProxy>; getDefaultHttpProxy(): Promise\<HttpProxy>;
Obtains the default proxy configuration of the network. 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. This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core **System capability**: SystemCapability.Communication.NetManager.Core
...@@ -356,7 +356,7 @@ This API uses a promise to return the result. ...@@ -356,7 +356,7 @@ This API uses a promise to return the result.
| Type | Description | | Type | Description |
| -------------------------------- | ----------------------------------------- | | -------------------------------- | ----------------------------------------- |
| Promise<[HttpProxy](#httpproxy)> | Promise used to return the result.| | Promise<[HttpProxy](#httpproxy10)> | Promise used to return the result.|
**Error codes** **Error codes**
......
...@@ -486,7 +486,7 @@ Defines the network configuration for the Ethernet connection. ...@@ -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.| | 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.| | 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 (,).| | 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 (,).|
| httpProxy<sup>10+</sup> | [HttpProxy](js-apis-net-connection.md#httpproxy) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.| | httpProxy<sup>10+</sup> | [HttpProxy](js-apis-net-connection.md#httpproxy10) | No| HTTP proxy of the Ethernet connection. By default, no proxy is configured.|
## IPSetMode<sup>9+</sup> ## IPSetMode<sup>9+</sup>
......
...@@ -4,7 +4,7 @@ The **Notification** module provides notification management capabilities, cover ...@@ -4,7 +4,7 @@ The **Notification** module provides notification management capabilities, cover
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > 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. > 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 ...@@ -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. | | bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. |
| notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | | 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\<void\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -1502,7 +1502,7 @@ Removes a notification for a specified bundle. This API uses a promise to return ...@@ -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.| | bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.|
| notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. | | 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** **Example**
...@@ -1536,8 +1536,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal ...@@ -1536,8 +1536,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal
| Name | Type | Mandatory| Description | | 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. | | 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. | | reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.| | callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -1573,7 +1573,7 @@ Removes a notification for a specified bundle. This API uses a promise to return ...@@ -1573,7 +1573,7 @@ Removes a notification for a specified bundle. This API uses a promise to return
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ---------- | ---- | ---------- | | -------- | ---------- | ---- | ---------- |
| hashCode | string | Yes | Unique notification ID.| | 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** **Example**
...@@ -2872,10 +2872,10 @@ Notification.getDeviceRemindType().then((data) => { ...@@ -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. > 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 | | Name | Type | Mandatory| Description |
| ------ | ------ |---- | --- | ------ | | ------ | ------ | --- | ------ |
| bundle | string | No | Yes | Bundle information of the application.| | bundle | string | Yes | Bundle information of the application.|
| uid | number | No | No | User ID.| | uid | number | No | User ID.|
## NotificationKey<sup>deprecated</sup> ## NotificationKey<sup>deprecated</sup>
...@@ -3059,7 +3059,7 @@ Describes the notification request. ...@@ -3059,7 +3059,7 @@ Describes the notification request.
| classification | string | Yes | Yes | Notification category.<br>**System API**: This is a system API and cannot be called by third-party applications. | | classification | string | Yes | Yes | Notification category.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| groupName<sup>8+</sup>| string | Yes | Yes | Notification group name. | | groupName<sup>8+</sup>| string | Yes | Yes | Notification group name. |
| template<sup>8+</sup> | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. | | template<sup>8+</sup> | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. |
| isRemoveAllowed<sup>8+</sup> | boolean | Yes | No | Whether the notification can be removed.<br>**System API**: This is a system API and cannot be called by third-party applications. | | isRemoveAllowed<sup>10+</sup> | boolean | Yes | No | Whether the notification can be removed.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| source<sup>8+</sup> | number | Yes | No | Notification source.<br>**System API**: This is a system API and cannot be called by third-party applications. | | source<sup>8+</sup> | number | Yes | No | Notification source.<br>**System API**: This is a system API and cannot be called by third-party applications. |
| distributedOption<sup>8+</sup> | [DistributedOptions](#distributedoptions8) | Yes | Yes | Distributed notification options. | | distributedOption<sup>8+</sup> | [DistributedOptions](#distributedoptions8) | Yes | Yes | Distributed notification options. |
| deviceId<sup>8+</sup> | string | Yes | No | Device ID of the notification source.<br>**System API**: This is a system API and cannot be called by third-party applications. | | deviceId<sup>8+</sup> | string | Yes | No | Device ID of the notification source.<br>**System API**: This is a system API and cannot be called by third-party applications. |
...@@ -3203,7 +3203,7 @@ Provides the notification user input. ...@@ -3203,7 +3203,7 @@ Provides the notification user input.
| TYPE_CONTINUOUS | 1 | Continuous notification. | | TYPE_CONTINUOUS | 1 | Continuous notification. |
| TYPE_TIMER | 2 | Timed notification. | | TYPE_TIMER | 2 | Timed notification. |
## RemoveReason<sup>9+</sup> <sup>deprecated</sup> ## RemoveReason <sup>deprecated</sup>
**System capability**: SystemCapability.Notification.Notification **System capability**: SystemCapability.Notification.Notification
...@@ -3211,9 +3211,9 @@ Provides the notification user input. ...@@ -3211,9 +3211,9 @@ Provides the notification user input.
> **NOTE** > **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 | | Name | Value | Description |
| -------------------- | --- | -------------------- | | -------------------- | --- | -------------------- |
| CLICK_REASON_REMOVE<sup>9+</sup> | 1 | The notification is removed after a click on it. | | CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. |
| CANCEL_REASON_REMOVE<sup>9+</sup> | 2 | The notification is removed by the user. | | CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. |
...@@ -443,6 +443,90 @@ notificationSubscribe.remove(hashCode, reason).then(() => { ...@@ -443,6 +443,90 @@ notificationSubscribe.remove(hashCode, reason).then(() => {
console.info("remove success"); console.info("remove success");
}); });
``` ```
## NotificationSubscribe.remove
remove(hashCodes: Array\<string\>, reason: RemoveReason, callback: AsyncCallback\<void\>): 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\<string\> | 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\<void\> | 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\<string\>, reason: RemoveReason): Promise\<void\>
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\<string\> | 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 ## NotificationSubscribe.removeAll
......
...@@ -850,7 +850,7 @@ Enumerates mouse pointer styles. ...@@ -850,7 +850,7 @@ Enumerates mouse pointer styles.
| MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east |![MID_Btn_South_East.png](./figures/MID_Btn_South_East.png)| | MIDDLE_BTN_SOUTH_EAST | 36 | Scrolling south-east |![MID_Btn_South_East.png](./figures/MID_Btn_South_East.png)|
| MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west |![MID_Btn_South_West.png](./figures/MID_Btn_South_West.png)| | MIDDLE_BTN_SOUTH_WEST | 37 | Scrolling south-west |![MID_Btn_South_West.png](./figures/MID_Btn_South_West.png)|
| MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions|![MID_Btn_North_South_West_East.png](./figures/MID_Btn_North_South_West_East.png)| | MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | 38 | Moving as a cone in four directions|![MID_Btn_North_South_West_East.png](./figures/MID_Btn_North_South_West_East.png)|
| HORIZONTAL_TEXT_CURSOR<sup>10+</sup> | 39 | Horizontal text selection|![Horizontal_Text_Cursor.png](./figures/Horizontal_Text_Cursor.png)| | HORIZONTAL_TEXT_CURSOR<sup>10+</sup> | 39 | Horizontal text cursor|![Horizontal_Text_Cursor.png](./figures/Horizontal_Text_Cursor.png)|
| CURSOR_CROSS<sup>10+</sup> | 40 | Cross cursor|![Cursor_Cross.png](./figures/Cursor_Cross.png)| | CURSOR_CROSS<sup>10+</sup> | 40 | Cross cursor|![Cursor_Cross.png](./figures/Cursor_Cross.png)|
| CURSOR_CIRCLE<sup>10+</sup> | 41 | Circular cursor|![Cursor_Circle.png](./figures/Cursor_Circle.png)| | CURSOR_CIRCLE<sup>10+</sup> | 41 | Circular cursor|![Cursor_Circle.png](./figures/Cursor_Circle.png)|
...@@ -1726,3 +1726,357 @@ try { ...@@ -1726,3 +1726,357 @@ try {
console.log(`getTouchpadRightClickType failed, error: ${JSON.stringify(error, [`code`, `message`])}`); console.log(`getTouchpadRightClickType failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
} }
``` ```
## pointer.setPointerSize<sup>10+</sup>
setPointerSize(size: number, callback: AsyncCallback&lt;void&gt;): 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&lt;void&gt; | 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.setPointerSize<sup>10+</sup>
setPointerSize(size: number): Promise&lt;void&gt;
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&lt;void&gt; | 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.setPointerSizeSync<sup>10+</sup>
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.getPointerSize<sup>10+</sup>
getPointerSize(callback: AsyncCallback&lt;number&gt;): 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&lt;number&gt; | 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.getPointerSize<sup>10+</sup>
getPointerSize(): Promise&lt;number&gt;
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&lt;number&gt; | 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.getPointerSizeSync<sup>10+</sup>
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.setPointerColor<sup>10+</sup>
setPointerColor(color: number, callback: AsyncCallback&lt;void&gt;): 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&lt;void&gt; | 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.setPointerColor<sup>10+</sup>
setPointerColor(color: number): Promise&lt;void&gt;
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&lt;void&gt; | 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.setPointerColorSync<sup>10+</sup>
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.getPointerColor<sup>10+</sup>
getPointerColor(callback: AsyncCallback&lt;number&gt;): 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&lt;number&gt; | 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.getPointerColor<sup>10+</sup>
getPointerColor(): Promise&lt;number&gt;
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&lt;number&gt; | 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.getPointerColorSync<sup>10+</sup>
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`])}`);
}
```
# @ohos.reminderAgentManager (reminderAgentManager) # @ohos.reminderAgentManager (Agent-Powered Reminders)
The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. 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.
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.
> **NOTE** > **NOTE**
> >
...@@ -15,12 +13,15 @@ You can use the APIs to create scheduled reminders for countdown timers, calenda ...@@ -15,12 +13,15 @@ You can use the APIs to create scheduled reminders for countdown timers, calenda
import reminderAgentManager from'@ohos.reminderAgentManager'; import reminderAgentManager from'@ohos.reminderAgentManager';
``` ```
## reminderAgentManager.publishReminder ## reminderAgentManager.publishReminder
publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\<number>): void publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\<number>): 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 **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER
...@@ -28,10 +29,10 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c ...@@ -28,10 +29,10 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.|
| callback | AsyncCallback\<number> | Yes| Callback used to return the published reminder's ID.| | callback | AsyncCallback\<number> | Yes| Callback used to return the published reminder's ID.|
**Error codes** **Error codes**
...@@ -62,26 +63,29 @@ try { ...@@ -62,26 +63,29 @@ try {
}; };
``` ```
## reminderAgentManager.publishReminder ## reminderAgentManager.publishReminder
publishReminder(reminderReq: ReminderRequest): Promise\<number> publishReminder(reminderReq: ReminderRequest): Promise\<number>
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 **Required permissions**: ohos.permission.PUBLISH_AGENT_REMINDER
**System capability**: SystemCapability.Notification.ReminderAgent **System capability**: SystemCapability.Notification.ReminderAgent
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.|
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<number> | Promise used to return the published reminder's ID.| | Promise\<number> | Promise used to return the published reminder's ID.|
**Error codes** **Error codes**
...@@ -115,7 +119,7 @@ try { ...@@ -115,7 +119,7 @@ try {
cancelReminder(reminderId: number, callback: AsyncCallback\<void>): void cancelReminder(reminderId: number, callback: AsyncCallback\<void>): 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 **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -124,7 +128,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba ...@@ -124,7 +128,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| reminderId | number | Yes| ID of the reminder to cancel.| | reminderId | number | Yes| ID of the reminder to cancel.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the reminder is canceled, **err** is **undefined**. Otherwise, **err** is an error object.|
**Error codes** **Error codes**
...@@ -151,12 +155,11 @@ try { ...@@ -151,12 +155,11 @@ try {
}; };
``` ```
## reminderAgentManager.cancelReminder ## reminderAgentManager.cancelReminder
cancelReminder(reminderId: number): Promise\<void> cancelReminder(reminderId: number): Promise\<void>
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 **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -170,7 +173,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th ...@@ -170,7 +173,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise that returns no value.|
**Error codes** **Error codes**
...@@ -199,8 +202,7 @@ try { ...@@ -199,8 +202,7 @@ try {
getValidReminders(callback: AsyncCallback<Array\<ReminderRequest>>): void getValidReminders(callback: AsyncCallback<Array\<ReminderRequest>>): void
Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the result.
Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders.
**System capability**: SystemCapability.Notification.ReminderAgent **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -208,7 +210,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th ...@@ -208,7 +210,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<Array\<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| | callback | AsyncCallback\<Array\<[ReminderRequest](#reminderrequest)>> | Yes| Callback used to return all the valid reminders.|
**Error codes** **Error codes**
...@@ -259,7 +261,7 @@ try { ...@@ -259,7 +261,7 @@ try {
getValidReminders(): Promise\<Array\<ReminderRequest>> getValidReminders(): Promise\<Array\<ReminderRequest>>
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 **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -267,7 +269,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th ...@@ -267,7 +269,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<Array\<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| | Promise\<Array\<[ReminderRequest](#reminderrequest)>> | Promise used to return all the valid reminders.|
**Error codes** **Error codes**
...@@ -312,12 +314,11 @@ try { ...@@ -312,12 +314,11 @@ try {
}; };
``` ```
## reminderAgentManager.cancelAllReminders ## reminderAgentManager.cancelAllReminders
cancelAllReminders(callback: AsyncCallback\<void>): void cancelAllReminders(callback: AsyncCallback\<void>): 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 **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -325,7 +326,7 @@ Cancels all reminders set by the current application. This API uses an asynchron ...@@ -325,7 +326,7 @@ Cancels all reminders set by the current application. This API uses an asynchron
| Name| Type| Mandatory| Description| | 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 all the reminders are canceled, **err** is **undefined**. Otherwise, **err** is an error object. |
**Error codes** **Error codes**
...@@ -351,12 +352,11 @@ try { ...@@ -351,12 +352,11 @@ try {
}; };
``` ```
## reminderAgentManager.cancelAllReminders ## reminderAgentManager.cancelAllReminders
cancelAllReminders(): Promise\<void> cancelAllReminders(): Promise\<void>
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 **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -364,7 +364,7 @@ Cancels all reminders set by the current application. This API uses a promise to ...@@ -364,7 +364,7 @@ Cancels all reminders set by the current application. This API uses a promise to
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise that returns no value.|
**Error codes** **Error codes**
...@@ -401,8 +401,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r ...@@ -401,8 +401,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r
| Name| Type| Mandatory| Description| | 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.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the notification slot is added, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -438,13 +438,13 @@ Adds a notification slot. This API uses a promise to return the result. ...@@ -438,13 +438,13 @@ Adds a notification slot. This API uses a promise to return the result.
| Name| Type| Mandatory| Description| | 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** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise that returns no value.|
**Example** **Example**
...@@ -470,7 +470,7 @@ try { ...@@ -470,7 +470,7 @@ try {
removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\<void>): void removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\<void>): 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 **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -479,7 +479,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c ...@@ -479,7 +479,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the notification slot is removed, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example** **Example**
...@@ -504,7 +504,7 @@ try { ...@@ -504,7 +504,7 @@ try {
removeNotificationSlot(slotType: notification.SlotType): Promise\<void> removeNotificationSlot(slotType: notification.SlotType): Promise\<void>
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 **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -518,7 +518,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu ...@@ -518,7 +518,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise that returns no value.|
**Example** **Example**
...@@ -538,7 +538,7 @@ try { ...@@ -538,7 +538,7 @@ try {
## ActionButtonType ## ActionButtonType
Enumerates button types. Enumerates the button types.
**System capability**: SystemCapability.Notification.ReminderAgent **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -551,7 +551,7 @@ Enumerates button types. ...@@ -551,7 +551,7 @@ Enumerates button types.
## ReminderType ## ReminderType
Enumerates reminder types. Enumerates the reminder types.
**System capability**: SystemCapability.Notification.ReminderAgent **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -564,8 +564,7 @@ Enumerates reminder types. ...@@ -564,8 +564,7 @@ Enumerates reminder types.
## ActionButton ## ActionButton
Defines a button displayed for the reminder in the notification panel. Defines the button on the reminder displayed.
**System capability**: SystemCapability.Notification.ReminderAgent **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -573,7 +572,7 @@ Defines a button displayed for the reminder in the notification panel. ...@@ -573,7 +572,7 @@ Defines a button displayed for the reminder in the notification panel.
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| title | string | Yes| Text on the button.| | title | string | Yes| Text on the button.|
| type | [ActionButtonType](#actionbuttontype) | Yes| Button type.| | type | [ActionButtonType](#actionbuttontype) | Yes| Button type.|
| wantAgent<sup>10+</sup> | [WantAgent](#wantagent) | No| Ability information that is displayed after the button is clicked.<br>**System API**: This is a system API and cannot be called by third-party applications.| | wantAgent<sup>10+</sup> | [WantAgent](#wantagent) | No| Information about the ability that is displayed after the button is clicked.<br>**System API**: This is a system API and cannot be called by third-party applications.|
## WantAgent ## WantAgent
...@@ -592,19 +591,19 @@ Defines the information about the redirected-to ability. ...@@ -592,19 +591,19 @@ Defines the information about the redirected-to ability.
## MaxScreenWantAgent ## 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 **System capability**: SystemCapability.Notification.ReminderAgent
| Name| Type| Mandatory| Description| | 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.| | 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 ability that is automatically started when the reminder arrives and the device is not in use.| | abilityName | string | Yes| Name of the target ability. (If the device is in use, only a notification banner is displayed.)|
## ReminderRequest ## ReminderRequest
Defines the reminder to publish. Defines the request for publishing a reminder.
**System capability**: SystemCapability.Notification.ReminderAgent **System capability**: SystemCapability.Notification.ReminderAgent
...@@ -613,7 +612,7 @@ Defines the reminder to publish. ...@@ -613,7 +612,7 @@ Defines the reminder to publish.
| reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.| | reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.|
| actionButton<sup></sup> | [ActionButton](#actionbutton) | No| Buttons displayed for the reminder in the notification panel.<br>- For common applications, a maximum of two buttons are supported.<br>- 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.| | actionButton<sup></sup> | [ActionButton](#actionbutton) | No| Buttons displayed for the reminder in the notification panel.<br>- For common applications, a maximum of two buttons are supported.<br>- 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.| | 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.<br> This API is reserved.|
| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| | 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**.| | 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.| | timeInterval | number | No| Reminder snooze interval, in seconds. The minimum value is 5 minutes.|
...@@ -623,8 +622,8 @@ Defines the reminder to publish. ...@@ -623,8 +622,8 @@ Defines the reminder to publish.
| snoozeContent | string | No| Content to be displayed when the reminder is snoozing.| | 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.| | 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.| | slotType | [notification.SlotType](js-apis-notificationManager.md#slottype) | No| Type of the slot used by the reminder.|
| tapDismissed<sup>10+</sup> | 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).| | tapDismissed<sup>10+</sup> | boolean | No| Whether the reminder is automatically cleared. For details, see [NotificationRequest.tapDismissed](js-apis-inner-notification-notificationRequest.md#notificationrequest). |
| autoDeletedTime<sup>10+</sup> | 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).| | autoDeletedTime<sup>10+</sup> | number | No| Time when the reminder is automatically cleared. For details, see [NotificationRequest.autoDeletedTime](js-apis-inner-notification-notificationRequest.md#notificationrequest).|
## ReminderRequestCalendar ## ReminderRequestCalendar
......
# @ohos.resourceschedule.workScheduler (Deferred Task Scheduling) # @ohos.resourceschedule.workScheduler (Deferred Task Scheduling)
The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks. 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.
The system schedules and executes deferred tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
> **NOTE** > **NOTE**
> >
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - The APIs of this module can be used only in the stage model. > - 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 ## Modules to Import
...@@ -18,9 +15,10 @@ import workScheduler from '@ohos.resourceschedule.workScheduler'; ...@@ -18,9 +15,10 @@ import workScheduler from '@ohos.resourceschedule.workScheduler';
``` ```
## workScheduler.startWork ## workScheduler.startWork
startWork(work: WorkInfo): void startWork(work: WorkInfo): void
Instructs the WorkSchedulerService to add a task to the execution queue. Starts a deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -28,7 +26,7 @@ Instructs the WorkSchedulerService to add a task to the execution queue. ...@@ -28,7 +26,7 @@ Instructs the WorkSchedulerService to add a task to the execution queue.
| Name | Type | Mandatory | Description | | 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** **Error codes**
...@@ -42,7 +40,6 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -42,7 +40,6 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700004 | Check workInfo failed. | | 9700004 | Check workInfo failed. |
| 9700005 | StartWork failed. | | 9700005 | StartWork failed. |
**Example** **Example**
```js ```js
...@@ -69,9 +66,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -69,9 +66,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## workScheduler.stopWork ## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): void stopWork(work: WorkInfo, needCancel?: boolean): void
Instructs the WorkSchedulerService to stop a task. Stops a deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -79,8 +77,8 @@ Instructs the WorkSchedulerService to stop a task. ...@@ -79,8 +77,8 @@ Instructs the WorkSchedulerService to stop a task.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | --------------------- | ---- | ---------- | | ---------- | --------------------- | ---- | ---------- |
| work | [WorkInfo](#workinfo) | Yes | Task to stop. | | work | [WorkInfo](#workinfo) | Yes | Deferred task to stop.|
| needCancel | boolean | No | Whether to cancel the task. The default value is **false**.| | needCancel | boolean | No | Whether to clear the task while stopping it.<br>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** **Error codes**
...@@ -119,9 +117,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -119,9 +117,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## workScheduler.getWorkStatus ## workScheduler.getWorkStatus
getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): void getWorkStatus(workId: number, callback : AsyncCallback\<WorkInfo>): 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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -129,8 +128,8 @@ Obtains the latest task status. This API uses an asynchronous callback to return ...@@ -129,8 +128,8 @@ Obtains the latest task status. This API uses an asynchronous callback to return
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------- | | -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. | | workId | number | Yes | ID of the deferred task. |
| 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.| | 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** **Error codes**
...@@ -162,9 +161,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -162,9 +161,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## workScheduler.getWorkStatus ## workScheduler.getWorkStatus
getWorkStatus(workId: number): Promise\<WorkInfo> getWorkStatus(workId: number): Promise\<WorkInfo>
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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -172,13 +172,13 @@ Obtains the latest task status. This API uses a promise to return the result. ...@@ -172,13 +172,13 @@ Obtains the latest task status. This API uses a promise to return the result.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- | | ------ | ------ | ---- | -------- |
| workId | number | Yes | Task ID.| | workId | number | Yes | ID of the deferred task.|
**Return value** **Return value**
| Type | Description | | 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** **Error codes**
...@@ -208,9 +208,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -208,9 +208,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## workScheduler.obtainAllWorks ## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo> obtainAllWorks(callback : AsyncCallback\<void>): Array\<WorkInfo>
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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -218,13 +219,13 @@ Obtains all tasks associated with the application. This API uses an asynchronous ...@@ -218,13 +219,13 @@ Obtains all tasks associated with the application. This API uses an asynchronous
| Name | Type | Mandatory | Description | | 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 all the deferred tasks are obtained, **err** is **undefined**. Otherwise, **err** is an error object.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------------------- | --------------- | | ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the application.| | Array\<[WorkInfo](#workinfo)> | All the deferred tasks.|
**Error codes** **Error codes**
...@@ -253,9 +254,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -253,9 +254,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## workScheduler.obtainAllWorks ## workScheduler.obtainAllWorks
obtainAllWorks(): Promise\<Array\<WorkInfo>> obtainAllWorks(): Promise\<Array\<WorkInfo>>
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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -263,7 +265,7 @@ Obtains all tasks associated with the application. This API uses a promise to re ...@@ -263,7 +265,7 @@ Obtains all tasks associated with the application. This API uses a promise to re
| Type | Description | | Type | Description |
| -------------------------------------- | ------------------------------ | | -------------------------------------- | ------------------------------ |
| Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all tasks associated with the application.| | Promise<Array\<[WorkInfo](#workinfo)>> | Promise used to return all the deferred tasks.|
**Error codes** **Error codes**
...@@ -290,9 +292,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -290,9 +292,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## workScheduler.stopAndClearWorks ## workScheduler.stopAndClearWorks
stopAndClearWorks(): void stopAndClearWorks(): void
Stops and cancels all tasks associated with the application. Stops and clears all the deferred tasks.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -318,6 +321,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -318,6 +321,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## workScheduler.isLastWorkTimeOut ## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result. 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 ...@@ -328,14 +332,14 @@ Checks whether the last execution of a task timed out. This API uses an asynchro
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ---------------------------------------- | | -------- | -------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. | | workId | number | Yes | ID of the deferred task. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. | | callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Return value** **Return value**
| Type | Description | | 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** **Error codes**
...@@ -365,6 +369,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -365,6 +369,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## workScheduler.isLastWorkTimeOut ## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean> isLastWorkTimeOut(workId: number): Promise\<boolean>
Checks whether the last execution of a task timed out. This API uses a promise to return the result. 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 ...@@ -375,13 +380,13 @@ Checks whether the last execution of a task timed out. This API uses a promise t
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- | | ------ | ------ | ---- | -------- |
| workId | number | Yes | Task ID.| | workId | number | Yes | ID of the deferred task.|
**Return value** **Return value**
| Type | Description | | Type | Description |
| ----------------- | ---------------------------------------- | | ----------------- | ---------------------------------------- |
| Promise\<boolean> | Promise used to return the result. If the last execution of the task timed out, **true** is returned. Otherwise, **false** is returned.| | Promise\<boolean> | 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** **Error codes**
...@@ -411,31 +416,33 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes ...@@ -411,31 +416,33 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
``` ```
## WorkInfo ## 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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Type | Mandatory | Description | | 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. | | 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.| | abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback.|
| networkType | [NetworkType](#networktype) | No | Network type. | | 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.<br>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. | | chargerType | [ChargingType](#chargingtype) | No | Charging type. |
| batteryLevel | number | No | Battery level. | | batteryLevel | number | No | Battery level. |
| batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. | | batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. |
| storageRequest | [StorageRequest](#storagerequest) | No | Storage status. | | storageRequest | [StorageRequest](#storagerequest) | No | Storage status. |
| isRepeat | boolean | No | Whether the task is repeated. | | isRepeat | boolean | No | Whether the task is repeated.<br>The value** true** means that the task is repeated, and **false** means the opposite.|
| repeatCycleTime | number | No | Repeat interval. | | repeatCycleTime | number | No | Repeat interval. |
| repeatCount | number | No | Number of repeat times. | | repeatCount | number | No | Number of repeat times. |
| isPersisted | boolean | No | Whether to enable persistent storage for the task. | | isPersisted | boolean | No | Whether to enable persistent storage for the task.<br>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. | | isDeepIdle | boolean | No | Whether the device needs to enter the idle state to trigger deferred task scheduling.<br>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. | | idleWaitTime | number | No | Time to wait in the idle state before triggering deferred task scheduling. |
| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. | | parameters | [key: string]: number \| string \| boolean | No | Carried parameters.|
## NetworkType ## 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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -449,7 +456,8 @@ Enumerates the network types that can trigger task scheduling. ...@@ -449,7 +456,8 @@ Enumerates the network types that can trigger task scheduling.
| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | | NETWORK_TYPE_ETHERNET | 5 | Ethernet. |
## ChargingType ## 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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -461,7 +469,8 @@ Enumerates the charging types that can trigger task scheduling. ...@@ -461,7 +469,8 @@ Enumerates the charging types that can trigger task scheduling.
| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | | CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. |
## BatteryStatus ## 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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -472,7 +481,8 @@ Enumerates the battery states that can trigger task scheduling. ...@@ -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.| | BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.|
## StorageRequest ## 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 **System capability**: SystemCapability.ResourceSchedule.WorkScheduler
...@@ -480,4 +490,4 @@ Enumerates the storage states that can trigger task scheduling. ...@@ -480,4 +490,4 @@ Enumerates the storage states that can trigger task scheduling.
| ------------------------- | ---- | ------------------------------ | | ------------------------- | ---- | ------------------------------ |
| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | | STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. |
| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | | 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.|
...@@ -51,21 +51,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ...@@ -51,21 +51,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
router.pushUrl({ try {
url: 'pages/routerpage2', router.pushUrl({
params: { url: 'pages/routerpage2',
data1: 'message', params: {
data2: { data1: 'message',
data3: [123, 456, 789] 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.pushUrl<sup>9+</sup> ## router.pushUrl<sup>9+</sup>
...@@ -146,21 +144,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ...@@ -146,21 +144,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
router.pushUrl({ try {
url: 'pages/routerpage2', router.pushUrl({
params: { url: 'pages/routerpage2',
data1: 'message', params: {
data2: { data1: 'message',
data3: [123, 456, 789] data2: {
data3: [123, 456, 789]
}
} }
} }, router.RouterMode.Standard)
}, router.RouterMode.Standard) } catch (err) {
.then(() => { console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
// success }
})
.catch(err => {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
})
``` ```
## router.pushUrl<sup>9+</sup> ## router.pushUrl<sup>9+</sup>
...@@ -241,18 +237,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ...@@ -241,18 +237,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
router.replaceUrl({ try {
url: 'pages/detail', router.replaceUrl({
params: { url: 'pages/detail',
data1: 'message' params: {
} data1: 'message'
}) }
.then(() => {
// success
})
.catch(err => {
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
}) })
} catch (err) {
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
}
``` ```
## router.replaceUrl<sup>9+</sup> ## router.replaceUrl<sup>9+</sup>
...@@ -330,18 +324,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ...@@ -330,18 +324,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
router.replaceUrl({ try {
url: 'pages/detail', router.replaceUrl({
params: { url: 'pages/detail',
data1: 'message' params: {
} data1: 'message'
}, router.RouterMode.Standard) }
.then(() => { }, router.RouterMode.Standard)
// success } catch (err) {
}) console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
.catch(err => { }
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
})
``` ```
## router.replaceUrl<sup>9+</sup> ## router.replaceUrl<sup>9+</sup>
...@@ -420,23 +412,23 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ...@@ -420,23 +412,23 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
router.pushNamedRoute({ try {
name: 'myPage', router.pushNamedRoute({
params: { name: 'myPage',
data1: 'message', params: {
data2: { data1: 'message',
data3: [123, 456, 789] 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.pushNamedRoute<sup>10+</sup> ## router.pushNamedRoute<sup>10+</sup>
pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
...@@ -515,21 +507,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ...@@ -515,21 +507,19 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
router.pushNamedRoute({ try {
name: 'myPage', router.pushNamedRoute({
params: { name: 'myPage',
data1: 'message', params: {
data2: { data1: 'message',
data3: [123, 456, 789] data2: {
data3: [123, 456, 789]
}
} }
} }, router.RouterMode.Standard)
}, router.RouterMode.Standard) } catch (err) {
.then(() => { console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
// success }
})
.catch(err => {
console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
})
``` ```
## router.pushNamedRoute<sup>10+</sup> ## router.pushNamedRoute<sup>10+</sup>
...@@ -610,18 +600,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ...@@ -610,18 +600,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example** **Example**
```ts ```ts
router.replaceNamedRoute({ try {
name: 'myPage', router.replaceNamedRoute({
params: { name: 'myPage',
data1: 'message' params: {
} data1: 'message'
}) }
.then(() => {
// success
})
.catch(err => {
console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
}) })
} catch (err) {
console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
}
``` ```
## router.replaceNamedRoute<sup>10+</sup> ## router.replaceNamedRoute<sup>10+</sup>
...@@ -693,24 +681,22 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc ...@@ -693,24 +681,22 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message| | 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. | | 100004 | if the named route is not exist. |
**Example** **Example**
```ts ```ts
router.replaceNamedRoute({ try {
name: 'myPage', router.replaceNamedRoute({
params: { name: 'myPage',
data1: 'message' params: {
} data1: 'message'
}, router.RouterMode.Standard) }
.then(() => { }, router.RouterMode.Standard)
// success } catch (err) {
}) console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
.catch(err => { }
console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
})
``` ```
## router.replaceNamedRoute<sup>10+</sup> ## router.replaceNamedRoute<sup>10+</sup>
...@@ -932,7 +918,7 @@ Describes the page routing options. ...@@ -932,7 +918,7 @@ Describes the page routing options.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ | | ------ | ------ | ---- | ------------------------------------------------------------ |
| url | string | Yes | URL of the target page, in either of the following formats:<br>- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:<br>- pages/index/index<br>- pages/detail/detail<br>- Particular path. If the URL is a slash (/), the home page is displayed.| | url | string | Yes | URL of the target page, in either of the following formats:<br>- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:<br>- pages/index/index<br>- pages/detail/detail<br>- 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.<br>**NOTE**<br>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** > **NOTE**
......
...@@ -2732,7 +2732,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses an async ...@@ -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. **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 **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 ...@@ -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. **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 **System capability**: SystemCapability.Telephony.CoreService
......
...@@ -1691,7 +1691,7 @@ listen(address: NetAddress, callback: AsyncCallback\<void\>): void ...@@ -1691,7 +1691,7 @@ listen(address: NetAddress, callback: AsyncCallback\<void\>): 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. 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**<br>
> 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. > 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 **Required permissions**: ohos.permission.INTERNET
...@@ -1736,7 +1736,7 @@ listen(address: NetAddress): Promise\<void\> ...@@ -1736,7 +1736,7 @@ listen(address: NetAddress): Promise\<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 a promise to return the result. 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**<br>
> 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. > 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 **Required permissions**: ohos.permission.INTERNET
......
...@@ -254,20 +254,20 @@ struct WebComponent { ...@@ -254,20 +254,20 @@ struct WebComponent {
.onClick(() => { .onClick(() => {
// Use the local port to send messages to HTML5. // Use the local port to send messages to HTML5.
try { try {
console.log("In eTS side send true start"); console.log("In ArkTS side send true start");
if (this.nativePort) { if (this.nativePort) {
this.message.setString("helloFromEts"); this.message.setString("helloFromEts");
this.nativePort.postMessageEventExt(this.message); this.nativePort.postMessageEventExt(this.message);
} }
} }
catch (error) { 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 }) Web({ src: $rawfile('index.html'), controller: this.controller })
.onPageEnd((e)=>{ .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. // 1. Create a message port.
this.ports = this.controller.createWebMessagePorts(true); this.ports = this.controller.createWebMessagePorts(true);
// 2. Send port 1 to HTML5. // 2. Send port 1 to HTML5.
...@@ -276,10 +276,10 @@ struct WebComponent { ...@@ -276,10 +276,10 @@ struct WebComponent {
this.nativePort = this.ports[0]; this.nativePort = this.ports[0];
// 4. Set the callback. // 4. Set the callback.
this.nativePort.onMessageEventExt((result) => { this.nativePort.onMessageEventExt((result) => {
console.log("In eTS side got message"); console.log("In ArkTS side got message");
try { try {
var type = result.getType(); var type = result.getType();
console.log("In eTS side getType:" + type); console.log("In ArkTS side getType:" + type);
switch (type) { switch (type) {
case web_webview.WebMessageType.STRING: { case web_webview.WebMessageType.STRING: {
this.msg1 = "result type:" + typeof (result.getString()); this.msg1 = "result type:" + typeof (result.getString());
...@@ -652,71 +652,71 @@ struct WebComponent { ...@@ -652,71 +652,71 @@ struct WebComponent {
There are three methods for loading local resource files: There are three methods for loading local resource files:
1. Using $rawfile 1. Using $rawfile
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview' import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController(); controller: web_webview.WebviewController = new web_webview.WebviewController();
build() { build() {
Column() { Column() {
Button('loadUrl') Button('loadUrl')
.onClick(() => { .onClick(() => {
try { try {
// Load a local resource file through $rawfile. // Load a local resource file through $rawfile.
this.controller.loadUrl($rawfile('index.html')); this.controller.loadUrl($rawfile('index.html'));
} catch (error) { } catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
} }
}) })
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
} }
} }
} }
``` ```
2. Using the resources protocol 2. Using the resources protocol
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview' import web_webview from '@ohos.web.webview'
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController(); controller: web_webview.WebviewController = new web_webview.WebviewController();
build() { build() {
Column() { Column() {
Button('loadUrl') Button('loadUrl')
.onClick(() => { .onClick(() => {
try { try {
// Load a local resource file through the resource protocol. // Load local resource files through the resource protocol.
this.controller.loadUrl("resource://rawfile/index.html"); this.controller.loadUrl("resource://rawfile/index.html");
} catch (error) { } catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
} }
}) })
Web({ src: 'www.example.com', controller: this.controller }) 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). 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 file to be loaded:
```html ```html
<!-- index.html --> <!-- index.html -->
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>
<p>Hello World</p> <p>Hello World</p>
</body> </body>
</html> </html>
``` ```
### loadData ### loadData
...@@ -4320,6 +4320,107 @@ export default class EntryAbility extends UIAbility { ...@@ -4320,6 +4320,107 @@ export default class EntryAbility extends UIAbility {
} }
``` ```
### setCustomUserAgent<sup>10+</sup>
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 })
}
}
}
```
### getCustomUserAgent<sup>10+</sup>
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 ## WebCookieManager
Implements a **WebCookieManager** instance to manage behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookieManager** instance. Implements a **WebCookieManager** instance to manage behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookieManager** instance.
......
...@@ -26,6 +26,11 @@ StepperItem() ...@@ -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.| | 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.<br>Default value: **ItemState.Normal**| | status | [ItemState](#itemstate) | Display status of **nextLabel** in the stepper. Optional.<br>Default value: **ItemState.Normal**|
> **NOTE**
>
> - The **\<StepperItem>** component does not support setting of the universal width attribute. By default, its width is the same as that of the parent **\<Stepper>** component.
> - The **\<StepperItem>** component does not support setting of the universal height attribute. Its height is the height of the parent **\<Stepper>** component minus the height of the label button.
> - The **\<StepperItem>** component does not support setting of the **aspectRadio** or **constrainSize** attribute, which may affect the length and width.
## ItemState ## ItemState
| Name | Description| | Name | Description|
......
...@@ -41,7 +41,7 @@ Since API version 9, this API is supported in ArkTS widgets. ...@@ -41,7 +41,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------------ | ---------------------------------------- | ---- | ---------------------------------------- | | ------------ | ---------------------------------------- | ---- | ---------------------------------------- |
| space | number \| string | No | Spacing between list items along the main axis.<br>Default value: **0**<br>**NOTE**<br>If the set value is a negative number, the default value will be used.<br>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.<br>Default value: **0**<br>**NOTE**<br>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.<br>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.<br>Default value: **0**<br>**NOTE**<br>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.| | 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.<br>Default value: **0**<br>**NOTE**<br>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.<br>**NOTE**<br>The scroller cannot be bound to other scrollable components.| | scroller | [Scroller](ts-container-scroll.md#scroller) | No | Scroller, which can be bound to scrollable components.<br>**NOTE**<br>The scroller cannot be bound to other scrollable components.|
......
# Application Event Logging Error Codes # Application Event Logging Error Codes
> **NOTE** > **NOTE**
> >
...@@ -63,8 +63,8 @@ This error code is reported if the **write** API is called to perform applicatio ...@@ -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 specified event name does not comply with the following rules:
- The event name contains only digits, lowercase letters, and underscores (\_). - An event name contains only digits, letters, and underscores (_).
- The event name starts with a lowercase letter and does not end with an underscore (\_). - 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. - The event name is not empty and contains a maximum of 48 characters.
**Solution** **Solution**
...@@ -119,11 +119,11 @@ This error code is reported if the **write** API is called to perform applicatio ...@@ -119,11 +119,11 @@ This error code is reported if the **write** API is called to perform applicatio
**Possible Causes** **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 (\_). - An event name contains only digits, letters, and underscores (_).
- The event parameter name starts with a lowercase letter and does not end with an underscore (\_). - An event name starts with a letter or dollar sign ($) and does not end with an underscore (_).
- The event parameter name is not empty and contains a maximum of 16 characters. - An event parameter name is not empty and contains a maximum of 16 characters.
**Solution** **Solution**
...@@ -163,7 +163,7 @@ The specified watcher name does not comply with the following rules: ...@@ -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 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 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** **Solution**
......
...@@ -62,8 +62,8 @@ The table below lists the APIs used for developing deferred tasks. For details a ...@@ -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.| | startWork(work: WorkInfo): void; | Starts a deferred task.|
| stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.| | stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.|
| getWorkStatus(workId: number, callback: AsyncCallback&lt;WorkInfo&gt;): void; | Obtains the status of a deferred task. This API uses an asynchronous callback to return the result.| | getWorkStatus(workId: number, callback: AsyncCallback&lt;WorkInfo&gt;): void; | Obtains the information about a deferred task. This API uses an asynchronous callback to return the result.|
| getWorkStatus(workId: number): Promise&lt;WorkInfo&gt;; | Obtains the status of a deferred task. This API uses a promise to return the result.| | getWorkStatus(workId: number): Promise&lt;WorkInfo&gt;; | Obtains the information about a deferred task. This API uses a promise to return the result.|
| obtainAllWorks(callback: AsyncCallback&lt;void&gt;): Array&lt;WorkInfo&gt;; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.| | obtainAllWorks(callback: AsyncCallback&lt;void&gt;): Array&lt;WorkInfo&gt;; | Obtains all the deferred tasks. This API uses an asynchronous callback to return the result.|
| obtainAllWorks(): Promise&lt;Array&lt;WorkInfo&gt;&gt;; | Obtains all the deferred tasks. This API uses a promise to return the result.| | obtainAllWorks(): Promise&lt;Array&lt;WorkInfo&gt;&gt;; | Obtains all the deferred tasks. This API uses a promise to return the result.|
| stopAndClearWorks(): void; | Stops and clears all the deferred tasks.| | 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 ...@@ -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.| | 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.| | 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.| | 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.| | chargerType | [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.|
| batteryLevel | number | Battery level.| | batteryLevel | number | Battery level.|
| batteryStatus | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.| | batteryStatus | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.|
......
...@@ -299,7 +299,7 @@ List() { ...@@ -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** >**NOTE**
> >
...@@ -653,8 +653,6 @@ The following describes the implementation of the pull-and-refresh feature: ...@@ -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. 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 ## Editing a List
......
...@@ -33,10 +33,11 @@ Constraints on the event domain, event name, and parameter ...@@ -33,10 +33,11 @@ Constraints on the event domain, event name, and parameter
| Field| Description| | Field| Description|
| -------- | -------- | | -------- | -------- |
| type | Event type. This field is mandatory.<br>Value:<br>- FAULT: fault<br>- STATISTIC: statistics<br>- SECURITY: security<br>- BEHAVIOR: user behavior| | type | Event type. This field is mandatory.<br>Value:<br>- **FAULT**: fault<br>- STATISTIC: statistics<br>- **SECURITY**: security<br>- **BEHAVIOR**: behavior|
| level | Event level. This field is mandatory.<br>Value:<br>- CRITICAL: critical<br>- MINOR: minor| | level | Event level. This field is mandatory.<br>Value:<br>- CRITICAL: critical<br>- MINOR: minor|
| tag | Event tag. This field is mandatory.<br>Rule:<br>- You can define a maximum of five tags, separated with a space.<br>- A single tag can contain a maximum of 16 characters, including a to z, A to Z, and 0 to 9.| | tag | Event tag. This field is mandatory.<br>Rule:<br>- You can define a maximum of five tags, separated with a space.<br>- 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.<br>Rule:<br>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.<br>Rule:<br>- 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**.<br>Value:<br>- **true**: Events need to be logged in the event file.<br>- **false**: Events do not need to be logged in the event file.|
**Table 2** Description of custom parameters **Table 2** Description of custom parameters
...@@ -44,7 +45,7 @@ Constraints on the event domain, event name, and parameter ...@@ -44,7 +45,7 @@ Constraints on the event domain, event name, and parameter
| -------- | -------- | | -------- | -------- |
| type | Parameter type. This field is mandatory.<br>Value:<br>- BOOL<br>- INT8<br>- UINT8<br>- INT16<br>- UINT16<br>- INT32<br>- UINT32<br>- INT64<br>- UINT64<br>- FLOAT<br>- DOUBLE<br>- STRING | | type | Parameter type. This field is mandatory.<br>Value:<br>- BOOL<br>- INT8<br>- UINT8<br>- INT16<br>- UINT16<br>- INT32<br>- UINT32<br>- INT64<br>- UINT64<br>- FLOAT<br>- DOUBLE<br>- STRING |
| arrsize | Length of the parameter of the array type. This field is optional.<br>Value:<br>1-100| | arrsize | Length of the parameter of the array type. This field is optional.<br>Value:<br>1-100|
| desc | Parameter description. This field is mandatory.<br>Rule:<br>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.<br>Rule:<br>- A string of 3 to 128 characters.|
## How to Develop ## How to Develop
......
...@@ -40,7 +40,7 @@ The standard system capabilities of OpenHarmony 4.0 are continuously improved. A ...@@ -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. - 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 ### DSoftBus
...@@ -391,7 +391,7 @@ This version has the following updates to OpenHarmony 4.0 Beta1. ...@@ -391,7 +391,7 @@ This version has the following updates to OpenHarmony 4.0 Beta1.
### API ### 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 ### Feature Updates
......
# 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<number>): void;
- request2(url: string, options: HttpRequestOptions, callback: AsyncCallback<number>): void;
- request2(url: string, options?: HttpRequestOptions): Promise<number>;
- 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<number>): void;
- requestInStream(url: string, options: HttpRequestOptions, callback: AsyncCallback<number>): void;
- requestInStream(url: string, options?: HttpRequestOptions): Promise<number>;
- 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.
# 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.
...@@ -21,22 +21,24 @@ ArkTS卡片开放了使用动画效果的能力,支持[显式动画](../refere ...@@ -21,22 +21,24 @@ ArkTS卡片开放了使用动画效果的能力,支持[显式动画](../refere
```ts ```ts
@Entry @Entry
@Component @Component
struct AttrAnimationExample { struct AnimationCard {
@State rotateAngle: number = 0; @State rotateAngle: number = 0;
build() { build() {
Column() { Row() {
Button('change rotate angle') Button('change rotate angle')
.height('20%')
.width('90%')
.margin('5%')
.onClick(() => { .onClick(() => {
this.rotateAngle = 90; this.rotateAngle = (this.rotateAngle === 0 ? 90 : 0);
}) })
.margin(50)
.rotate({ angle: this.rotateAngle }) .rotate({ angle: this.rotateAngle })
.animation({ .animation({
curve: Curve.EaseOut, curve: Curve.EaseOut,
playMode: PlayMode.AlternateReverse playMode: PlayMode.Normal,
}) })
}.width('100%').margin({ top: 20 }) }.height('100%').alignItems(VerticalAlign.Center)
} }
} }
``` ```
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册