提交 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
zh-cn/application-dev/reference/apis/js-apis-data-rdb.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-udmf.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-cloudData.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-relationStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-relationalStore.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-resultset.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-storage.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
zh-cn/application-dev/reference/apis/js-apis-data-ValuesBucket.md @feng-aiwen @ge-yafang @gong-a-shi @logic42
......
......@@ -54,7 +54,7 @@ Widget-related configuration includes **FormExtensionAbility** configuration and
| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification.| String| Yes (initial value: left empty)|
| metadata | Metadata of the widget. This field contains the array of the **customizeData** field.| Object| Yes (initial value: left empty)|
| dataProxyEnabled | Whether the widget supports the [update-through-proxy](./arkts-ui-widget-update-by-proxy.md) feature.<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
......
......@@ -26,7 +26,7 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
- If the **exported** field of the target component is **false**, verify the **ohos.permission.START_INVISIBLE_ABILITY** permission.
- For details, see [Component exported Configuration](../quick-start/module-configuration-file.md#abilities).
- **Before starting a component of a background application, verify the BACKGROUND permission.**
- **Before starting a UIAbility component of a background application, verify the BACKGROUND permission.**
- An application is considered as a foreground application only when the application process gains focus or its UIAbility component is running in the foreground.
- Verify the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission.
......@@ -45,7 +45,9 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
The rules for starting components on the same device vary in the following scenarios:
- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components
- Starting the UIAbility component
- Starting the ServiceExtensionAbility and DataShareExtensionAbility components
- Using **startAbilityByCall()** to start the UIAbility component
......@@ -56,9 +58,10 @@ In view of this, OpenHarmony formulates a set of component startup rules, as fol
The rules for starting components on a different device vary in the following scenarios:
- Starting or connecting to the UIAbility, ServiceExtensionAbility, and DataShareExtensionAbility components
- Starting the UIAbility component
- Starting the ServiceExtensionAbility and DataShareExtensionAbility components
- Using **startAbilityByCall()** to start the UIAbility component
![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
A UIAbility starts a PageAbility in the same way as it starts another UIAbility.
> **NOTE**
>
> In the FA model, **abilityName** consists of **bundleName** and **AbilityName**. For details, see the code snippet below.
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
......@@ -25,7 +29,7 @@ export default class EntryAbility extends UIAbility {
});
let want = {
bundleName: "com.ohos.fa",
abilityName: "EntryAbility",
abilityName: "com.ohos.fa.EntryAbility",
};
this.context.startAbility(want).then(() => {
console.info('Start Ability successfully.');
......
......@@ -14,7 +14,7 @@ import featureAbility from '@ohos.ability.featureAbility';
let parameter = {
"want": {
bundleName: "com.ohos.stage",
abilityName: "com.ohos.stage.EntryAbility"
abilityName: "EntryAbility"
}
};
featureAbility.startAbility(parameter).then((code) => {
......
......@@ -12,7 +12,7 @@
## Types of Want
- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an an application component, explicit Want is used.
- **Explicit Want**: If **abilityName** and **bundleName** are specified in the **want** parameter when starting an application component, explicit Want is used.
Explicit Want is usually used to start a known target application component in the same application. The target application component is started by specifying **bundleName** of the application where the target application component is located and **abilityName** in the **Want** object. When there is an explicit object to process the request, explicit Want is a simple and effective way to start the target application component.
......@@ -24,7 +24,7 @@
}
```
- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting the an application component, implicit Want is used.
- **Implicit Want**: If **abilityName** is not specified in the **want** parameter when starting an application component, implicit Want is used.
Implicit Want can be used when the object used to process the request is unclear and the current application wants to use a capability (defined by the [skills tag](../quick-start/module-configuration-file.md#skills)) provided by another application. The system matches all applications that declare to support the capability. For example, for a link open request, the system matches all applications that support the request and provides the available ones for users to select.
......@@ -47,6 +47,7 @@
> - An application component that meets the conditions is matched. That application component is started.
> - Multiple application components that meet the conditions are matched. A dialog box is displayed for users to select one of them.
>
> - If the **want** parameter passed does not contain **abilityName** or **bundleName**, the ServiceExtensionAbility components of all applications cannot be started through implicit Want.
> - In the scenario for starting the ServiceExtensionAbility component:
> - If the **want** parameter passed in contains **abilityName**, the ServiceExtensionAbility component cannot be started through implicit Want.
>
> - If the **want** parameter passed contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start ServiceExtensionAbility. By default, ServiceExtensionAbility with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility is returned.
> - If the **want** parameter passed in contains **bundleName**, the **startServiceExtensionAbility()** method can be used to implicitly start the ServiceExtensionAbility component. By default, the ServiceExtensionAbility component with the highest priority is returned. If all the matching ServiceExtensionAbility components have the same priority, the first ServiceExtensionAbility component is returned.
# HTTP Data Request
## When to Use
## Overview
An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
......@@ -18,7 +18,7 @@ The following table provides only a simple description of the related APIs. For
| ----------------------------------------- | ----------------------------------- |
| createHttp() | Creates an HTTP request. |
| request() | Initiates an HTTP request to a given URL. |
| request2()<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. |
| on(type: 'headersReceive') | Registers an observer for HTTP Response Header events. |
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
......@@ -27,8 +27,8 @@ The following table provides only a simple description of the related APIs. For
| off\('dataReceive'\)<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. |
| 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. |
| off\('dataProgress'\)<sup>10+</sup> | Unregisters the 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\('dataReceiveProgress'\)<sup>10+</sup> | Unregisters the observer for events indicating progress of receiving HTTP streaming responses.|
## How to Develop request APIs
......@@ -53,6 +53,7 @@ httpRequest.on('headersReceive', (header) => {
});
httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
......@@ -81,7 +82,7 @@ httpRequest.request(
// Call the destroy() method to release resources after HttpRequest is complete.
httpRequest.destroy();
} else {
console.info('error:' + JSON.stringify(err));
console.error('error:' + JSON.stringify(err));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Call the destroy() method to release resources after HttpRequest is complete.
......@@ -91,12 +92,12 @@ httpRequest.request(
);
```
## How to Develop request2 APIs
## How to Develop requestInStream APIs
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
3. Depending on your need, call **on()** of the **HttpRequest** object to subscribe to HTTP response header events as well as events indicating receiving of HTTP streaming responses, progress of receiving HTTP streaming responses, and completion of receiving HTTP streaming responses.
4. Call **request2()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
4. Call **requestInStream()** to initiate a network request. You need to pass in the URL and optional parameters of the HTTP request.
5. Parse the returned response code as needed.
6. Call **off()** of the **HttpRequest** object to unsubscribe from the related events.
7. Call **httpRequest.destroy()** to release resources after the request is processed.
......@@ -122,11 +123,11 @@ httpRequest.on('dataEnd', () => {
console.info('No more data in response, data receive end');
});
// Subscribe to events indicating progress of receiving HTTP streaming responses.
httpRequest.on('dataProgress', (data) => {
console.log("dataProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
httpRequest.on('dataReceiveProgress', (data) => {
console.log("dataReceiveProgress receiveSize:" + data.receiveSize + ", totalSize:" + data.totalSize);
});
httpRequest.request2(
httpRequest.requestInStream(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
......@@ -146,14 +147,14 @@ httpRequest.request2(
readTimeout: 60000, // Optional. The default value is 60000, in ms. If a large amount of data needs to be transmitted, you are advised to set this parameter to a larger value to ensure normal data transmission.
usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system.
}, (err, data) => {
console.info('error:' + JSON.stringify(err));
console.error('error:' + JSON.stringify(err));
console.info('ResponseCode :' + JSON.stringify(data));
// Unsubscribe from HTTP Response Header events.
httpRequest.off('headersReceive');
// Unregister the observer for events indicating receiving of HTTP streaming responses.
httpRequest.off('dataReceive');
// Unregister the observer for events indicating progress of receiving HTTP streaming responses.
httpRequest.off('dataProgress');
httpRequest.off('dataReceiveProgress');
// Unregister the observer for events indicating completion of receiving HTTP streaming responses.
httpRequest.off('dataEnd');
// Call the destroy() method to release resources after HttpRequest is complete.
......@@ -161,10 +162,3 @@ httpRequest.request2(
}
);
```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`Http`: Data Request (ArkTS) (API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/Http)
- [HTTP Communication (ArkTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH)
# 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.
......
# Network Connection Management
## Introduction
## Overview
The Network Connection Management module provides basic network management capabilities, including management of Wi-Fi/cellular/Ethernet connection priorities, network quality evaluation, subscription to network connection status changes, query of network connection information, and DNS resolution.
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-connection.md).
## Basic Concepts
......
# Ethernet Connection
## Introduction
## Overview
The Ethernet Connection module allows a device to access the Internet through a network cable. After a device is connected to the Ethernet through a network cable, the device can obtain a series of network attributes, such as the dynamically allocated IP address, subnet mask, gateway, and DNS. You can manually configure and obtain the network attributes of the device in static mode.
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-ethernet.md).
## **Constraints**
......
# MDNS Management
## Introduction
## Overview
Multicast DNS (mDNS) provides functions such as adding, removing, discovering, and resolving local services on a LAN.
- Local service: a service provider on a LAN, for example, a printer or scanner.
......
# Network Sharing
## Introduction
## Overview
The Network Sharing module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md).
## Basic Concepts
......
# Traffic Management
## Introduction
## Overview
The traffic management module allows you to query real-time or historical data traffic by the specified network interface card (NIC) or user ID (UID).
......@@ -11,6 +11,7 @@ Its functions include:
- Subscribing to traffic change events by NIC or UID
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-statistics.md).
The following describes the development procedure specific to each application scenario.
......
......@@ -5,6 +5,7 @@
A virtual private network (VPN) is a dedicated network established on a public network. On a VPN, the connection between any two nodes does not have an end-to-end physical link required by the traditional private network. Instead, user data is transmitted over a logical link because a VPN is a logical network deployed over the network platform (such as the Internet) provided by the public network service provider.
> **NOTE**
>
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [Traffic Management](../reference/apis/js-apis-net-vpn.md).
The following describes the development procedure specific to each application scenario.
......
# 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.
......
# Subscribing to State Changes of a Remote Object
## Overview
IPC/RPC allows you to subscribe to the state changes of a remote stub object. When the remote stub object dies, a death notification will be sent to your local proxy object. Such subscription and unsubscription are controlled by APIs. To be specific, you need to implement the **DeathRecipient** interface and the **onRemoteDied** API to clear resources. This callback is invoked when the process accommodating the remote stub object dies, or the device accommodating the remote stub object leaves the network. It is worth noting that these APIs should be called in the following order: The proxy object must first subscribe to death notifications of the stub object. If the stub object is in the normal state, the proxy object can cancel the subscription as required. If the process of the stub object exits or the device hosting the stub object goes offline, subsequent operations customized by the proxy object will be automatically triggered.
## When to Use
......
# 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.
......
# DFX
- [Development of Application Event Logging](hiappevent-guidelines.md)
- [Development of Performance Tracing](hitracemeter-guidelines.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- [HiLog Development (Native)](hilog-guidelines.md)
- Performance Tracing
......
# 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 Recovery Development
## When to Use
## Overview
During application running, some unexpected behaviors are inevitable. For example, unprocessed exceptions and errors are thrown, and the call or running constraints of the recovery framework are violated.
......@@ -99,9 +99,12 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
- Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback. For details about its usage, see [errorManager](../reference/apis/js-apis-app-ability-errorManager.md).
```ts
var registerId = -1;
var callback = {
onUnhandledException(errMsg) {
export let abilityWant : Want // file1
import * as G form "../file1"
let registerId = -1;
let callback: Callback = {
onUnhandledException(errMsg: string): void {
console.log(errMsg);
appRecovery.saveAppState();
appRecovery.restartApp();
......@@ -112,7 +115,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant'
// Main window is created, set main page for this ability
console.log("[Demo] MainAbility onWindowStageCreate")
globalThis.registerObserver = (() => {
G.registerObserver = (() => {
registerId = errorManager.on('error', callback);
})
......@@ -138,13 +141,16 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state,
After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onCreate(want, launchParam)** of **MainAbility** is called, and the saved data is in **parameters** of **want**.
```ts
export let abilityWant : Want // file1
import * as GlobalWant form "../file1"
storage: LocalStorage
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want;
GlobalWant.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage();
let recoveryData = want.parameters["myData"];
let recoveryData: string = want.parameters["myData"];
this.storage.setOrCreate("myData", recoveryData);
this.context.restoreWindowStage(this.storage);
}
......@@ -154,12 +160,15 @@ onCreate(want, launchParam) {
- Unregister the **ErrorObserver** callback.
```ts
export let abilityWant : Want // file1
import * as G form "../file1"
onWindowStageDestroy() {
// Main window is destroyed, release UI related resources
console.log("[Demo] MainAbility onWindowStageDestroy")
globalThis.unRegisterObserver = (() => {
errorManager.off('error', registerId, (err) => {
G.unRegisterObserver = (() => {
errorManager.off(type: 'error', registerId: number, (err:Error) => {
console.error("[Demo] err:", err);
});
})
......@@ -171,20 +180,22 @@ onWindowStageDestroy() {
This is triggered by the recovery framework. You do not need to register an **ErrorObserver** callback. You only need to implement **onSaveState** for application state saving and **onCreate** for data restore.
```ts
export let abilityWant : Want // file1
import * as GlobalWant form "../file1"
export default class MainAbility extends Ability {
storage: LocalStorage
onCreate(want, launchParam) {
onCreate(want: Want, launchParam:AbilityConstant.LaunchParam):void {
console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want;
GlobalWant.abilityWant = want;
if (launchParam.launchReason == AbilityConstant.LaunchReason.APP_RECOVERY) {
this.storage = new LocalStorage();
let recoveryData = want.parameters["myData"];
this.storage.setOrCreate("myData", recoveryData);
let recoveryData: string = want.parameters["myData"];
this.storage.setOrCreate<string>("myData", recoveryData);
this.context.restoreWindowStage(this.storage);
}
}
onSaveState(state, wantParams) {
onSaveState(state: AbilityConstant.StateType, wantParams: { [key: string]: Object }) : AbilityConstant.OnSaveResult{
// Ability has called to save app data
console.log("[Demo] MainAbility onSaveState")
wantParams["myData"] = "my1234567";
......
# 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.
......
# 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.
......
# 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.
......
# 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.
......
# 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.
......
# Development of Performance Tracing (ArkTS)
## Introduction
## Overview
hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
......@@ -21,7 +21,7 @@ hiTraceMeter provides APIs for system performance tracing. You can call the APIs
## Available APIs
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference](../reference/apis/js-apis-hitracemeter.md).
The performance tracing APIs are provided by the **hiTraceMeter** module. For details, see [API Reference]( ../reference/apis/js-apis-hitracemeter.md).
**APIs for performance tracing**
......@@ -35,51 +35,7 @@ The performance tracing APIs are provided by the **hiTraceMeter** module. For de
In this example, distributed call chain tracing begins when the application startup execution page is loaded and stops when the service usage is completed.
1. Create a JS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **js** > **default** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. The sample code is as follows:
```js
import hiTraceMeter from '@ohos.hiTraceMeter'
export default {
data: {
title: ""
},
onInit() {
this.title = this.$t('strings.world');
// Start trace tasks with the same name concurrently.
hiTraceMeter.startTrace("business", 1);
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.startTrace("business", 2); // Start the second trace task with the same name while the first task is still running. The tasks are running concurrently and therefore their taskId must be different.
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.finishTrace("business", 1);
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.finishTrace("business", 2);
// Start trace tasks with the same name in serial mode.
hiTraceMeter.startTrace("business", 1);
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.finishTrace("business", 1); // End the first trace task.
// Keep the service process running.
console.log(`business running`);
hiTraceMeter.startTrace("business", 1); // Start the second trace task with the same name in serial mode.
// Keep the service process running.
console.log(`business running`);
let traceCount = 3;
hiTraceMeter.traceByValue("myTestCount", traceCount);
traceCount = 4;
hiTraceMeter.traceByValue("myTestCount", traceCount);
hiTraceMeter.finishTrace("business", 1);
}
}
```
2. Create an ArkTs application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows:
1. Create an ArkTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index**, and double-click **index.js**. Add the code to implement performance tracing upon page loading. For example, if the name of the trace task is **HITRACE\_TAG\_APP**, the sample code is as follows:
```ts
import hitrace from '@ohos.hiTraceMeter';
......
# Development of Performance Tracing (Native)
## Introduction
## Overview
hiTraceMeter provides APIs for system performance tracing. You can call the APIs provided by the hiTraceMeter module in your own service logic to effectively track service processes and check the system performance.
> **NOTE**
......
......@@ -21,42 +21,6 @@ try {
}
```
## How do I hide the status bar to get the immersive effect?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9)
**Solution**
1. Use **onWindowStageCreate** to obtain a **windowClass** object.
```
onWindowStageCreate(windowStage) {
// When the main window is created, set the main page for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
windowStage.getMainWindow((err, data) => {
if (err.code) {
console.error('Failed to obtain the main window.')
return;
}
// Obtain a windowClass object.
globalThis.windowClass = data;
})
}
```
2. Enable the full-screen mode for the window and hide the status bar.
```
globalThis.windowClass.setFullScreen(isFullScreen, (err, data) => {
if (err.code) {
console.error('Failed to enable the full-screen mode. Cause:' + JSON.stringify(err));
return;
}
console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data));
});
```
## How do I obtain the window width and height?
Applicable to: OpenHarmony 3.2 Beta5 (API version 9, stage model)
......
......@@ -20,11 +20,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
import media from '@ohos.multimedia.media';
let avRecorder = undefined;
media.createAVRecorder().then((recorder) => {
let avRecorder: media.AVRecorder;
media.createAVRecorder().then((recorder: media.AVRecorder) => {
avRecorder = recorder;
}, (err) => {
console.error(`Invoke createAVRecorder failed, code is ${err.code}, message is ${err.message}`);
}, (error: Error) => {
console.error(`createAVRecorder failed`);
})
```
......@@ -37,13 +37,13 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
// Callback function for state changes.
avRecorder.on('stateChange', (state, reason) => {
avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.log(`current state is ${state}`);
// You can add the action to be performed after the state is switched.
})
// Callback function for errors.
avRecorder.on('error', (err) => {
avRecorder.on('error', (err: BusinessError) => {
console.error(`avRecorder failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -62,21 +62,21 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
let avProfile = {
let avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // Audio bit rate.
audioChannels: 2, // Number of audio channels.
audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported.
audioSampleRate: 48000, // Audio sampling rate.
fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported.
}
let avConfig = {
let avConfig: media.AVRecorderConfig = {
audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used.
profile: avProfile,
url: 'fd://35', // Obtain the file descriptor of the created audio file by referring to the sample code in Application File Access and Management.
}
avRecorder.prepare(avConfig).then(() => {
console.log('Invoke prepare succeeded.');
}, (err) => {
}, (err: BusinessError) => {
console.error(`Invoke prepare failed, code is ${err.code}, message is ${err.message}`);
})
```
......@@ -100,17 +100,17 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
import media from '@ohos.multimedia.media';
import { BusinessError } from '@ohos.base';
export class AudioRecorderDemo {
private avRecorder;
private avProfile = {
private avRecorder: media.AVRecorder;
private avProfile: media.AVRecorderProfile = {
audioBitrate: 100000, // Audio bit rate.
audioChannels: 2, // Number of audio channels.
audioCodec: media.CodecMimeType.AUDIO_AAC, // Audio encoding format. Currently, only AAC is supported.
audioSampleRate: 48000, // Audio sampling rate.
fileFormat: media.ContainerFormatType.CFT_MPEG_4A, // Encapsulation format. Currently, only M4A is supported.
};
private avConfig = {
private avConfig: media.AVRecorderConfig = {
audioSourceType: media.AudioSourceType.AUDIO_SOURCE_TYPE_MIC, // Audio input source. In this example, the microphone is used.
profile: this.avProfile,
url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
......@@ -119,11 +119,11 @@ export class AudioRecorderDemo {
// Set AVRecorder callback functions.
setAudioRecorderCallback() {
// Callback function for state changes.
this.avRecorder.on('stateChange', (state, reason) => {
this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.log(`AudioRecorder current state is ${state}`);
})
// Callback function for errors.
this.avRecorder.on('error', (err) => {
this.avRecorder.on('error', (err: BusinessError) => {
console.error(`AudioRecorder failed, code is ${err.code}, message is ${err.message}`);
})
}
......
......@@ -24,10 +24,10 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
import media from '@ohos.multimedia.media'
let avRecorder
media.createAVRecorder().then((recorder) => {
let avRecorder: media.AVRecorder;
media.createAVRecorder().then((recorder: media.AVRecorder) => {
avRecorder = recorder
}, (error) => {
}, (error: Error) => {
console.error('createAVRecorder failed')
})
```
......@@ -40,11 +40,11 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
```ts
// Callback function for state changes.
avRecorder.on('stateChange', (state, reason) => {
avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.info('current state is: ' + state);
})
// Callback function for errors.
avRecorder.on('error', (err) => {
avRecorder.on('error', (err: BusinessError) => {
console.error('error happened, error message is ' + err);
})
```
......@@ -62,7 +62,7 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
> - The recording output URL (URL in **avConfig** in the sample code) must be in the format of fd://xx (where xx indicates a file descriptor). You must call [ohos.file.fs](../reference/apis/js-apis-file-fs.md) to implement access to the application file. For details, see [Application File Access and Management](../file-management/app-file-access.md).
```ts
let avProfile = {
let avProfile: media.AVRecorderProfile = {
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
videoBitrate: 200000, // Video bit rate.
videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported.
......@@ -70,15 +70,15 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
videoFrameHeight: 480, // Video frame height.
videoFrameRate: 30 // Video frame rate.
}
let avConfig = {
let avConfig: media.AVRecorderConfig = {
videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
profile : this.avProfile,
profile : avProfile,
url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
rotation: 0, // Video rotation angle. The default value is 0, indicating that the video is not rotated. The value can be 0, 90, 180, or 270.
}
avRecorder.prepare(avConfig).then(() => {
console.info('avRecorder prepare success')
}, (error) => {
}, (error: Error) => {
console.error('avRecorder prepare failed')
})
```
......@@ -90,9 +90,9 @@ Read [AVRecorder](../reference/apis/js-apis-media.md#avrecorder9) for the API re
The video data collection module obtains the surface based on the surface ID and transmits video data to the AVRecorder through the surface. Then the AVRecorder processes the video data.
```ts
avRecorder.getInputSurface().then((surfaceId) => {
avRecorder.getInputSurface().then((surfaceId: string) => {
console.info('avRecorder getInputSurface success')
}, (error) => {
}, (error: Error) => {
console.error('avRecorder getInputSurface failed')
})
```
......@@ -123,19 +123,20 @@ Refer to the sample code below to complete the process of starting, pausing, res
```ts
import media from '@ohos.multimedia.media'
import { BusinessError } from '@ohos.base';
const TAG = 'VideoRecorderDemo:'
export class VideoRecorderDemo {
private avRecorder;
private videoOutSurfaceId;
private avProfile = {
private avRecorder: media.AVRecorder;
private videoOutSurfaceId: string;
private avProfile: media.AVRecorderProfile = {
fileFormat: media.ContainerFormatType.CFT_MPEG_4, // Video file encapsulation format. Only MP4 is supported.
videoBitrate : 100000, // Video bit rate.
videoBitrate: 100000, // Video bit rate.
videoCodec: media.CodecMimeType.VIDEO_AVC, // Video file encoding format. Both MPEG-4 and AVC are supported.
videoFrameWidth: 640, // Video frame width.
videoFrameHeight: 480, // Video frame height.
videoFrameRate: 30 // Video frame rate.
}
private avConfig = {
private avConfig: media.AVRecorderConfig = {
videoSourceType: media.VideoSourceType.VIDEO_SOURCE_TYPE_SURFACE_YUV, // Video source type. YUV and ES are supported.
profile : this.avProfile,
url: 'fd://35', // Create, read, and write a file by referring to the sample code in Application File Access and Management.
......@@ -145,11 +146,11 @@ export class VideoRecorderDemo {
// Set AVRecorder callback functions.
setAvRecorderCallback() {
// Callback function for state changes.
this.avRecorder.on('stateChange', (state, reason) => {
this.avRecorder.on('stateChange', (state: media.AVRecorderState, reason: media.StateChangeReason) => {
console.info(TAG + 'current state is: ' + state);
})
// Callback function for errors.
this.avRecorder.on('error', (err) => {
this.avRecorder.on('error', (err: BusinessError) => {
console.error(TAG + 'error ocConstantSourceNode, error message is ' + err);
})
}
......@@ -188,7 +189,7 @@ export class VideoRecorderDemo {
// 5. Start the camera stream output.
await this.startCameraOutput();
// 6. Start recording.
await this.videoRecorder.start();
await this.avRecorder.start();
}
// Process of pausing recording.
......
# 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
......@@ -21,7 +21,6 @@ The environment requirements for the Neural Network Runtime are as follows:
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
1. Start the Ubuntu server.
......@@ -33,7 +32,6 @@ unzip native-linux-{version number}.zip
```
The directory structure after decompression is as follows. The content in the directory may vary depending on version iteration. Use the Native APIs of the latest version.
```text
native/
─ ─ build // Cross-compilation toolchain
......
......@@ -23,8 +23,7 @@ Selected state attributes of AppStorage can be synced with different data source
As mentioned above, if you want to establish a binding between AppStorage and a custom component, you'll need the \@StorageProp and \@StorageLink decorators. Use \@StorageProp(key) or \@StorageLink(key) to decorate variables in the component, where **key** identifies the attribute in AppStorage.
When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Local initialization is mandatory. If an attribute with the given key is missing from AppStorage, it will be added with the stated initializing value. (Whether the attribute with the given key exists in AppStorage depends on the application logic.)
When a custom component is initialized, the \@StorageProp(key)/\@StorageLink(key) decorated variable is initialized with the value of the attribute with the given key in AppStorage. Whether the attribute with the given key exists in AppStorage depends on the application logic. This means that the attribute with the given key may be missing from AppStorage. In light of this, local initialization is mandatory for the \@StorageProp(key)/\@StorageLink(key) decorated variable.
By decorating a variable with \@StorageProp(key), a one-way data synchronization is established with the attribute with the given key in AppStorage. A local change can be made, but it will not be synchronized to AppStorage. An update to the attribute with the given key in AppStorage will overwrite local changes.
......@@ -193,9 +192,85 @@ struct CompA {
}
```
### Persistent Subscription and Callback
### Unrecommended: Using @StorageLink to Implement Event Notification
Compared with the common mechanism for event notification, the two-way synchronization mechanism of @StorageLink and AppStorage is far less cost efficient and therefore not recommended. This is because AppStorage stores UI-related data, and its changes will cause costly UI refresh.
In the following example, any tap event in the **TapImage** component will trigger a change of the **tapIndex** attribute. As @StorageLink establishes a two-way data synchronization with AppStorage, the local change is synchronized to AppStorage. As a result, all visible custom components owning the **tapIndex** attribute bound to AppStorage are notified to refresh the UI.
```ts
// xxx.ets
class ViewData {
title: string;
uri: Resource;
color: Color = Color.Black;
constructor(title: string, uri: Resource) {
this.title = title;
this.uri = uri
}
}
@Entry
@Component
struct Gallery2 {
dataList: Array<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
......@@ -294,10 +369,9 @@ export struct TapImage {
}
```
The following example uses the message mechanism to subscribe to events. Because this mechanism can result in a large number of nodes to listen for and a long implementation time, it is not recommended.
The preceding notification logic is simple. It can be simplified into a ternary expression as follows:
```ts
```
// xxx.ets
class ViewData {
title: string;
......@@ -338,22 +412,11 @@ struct Gallery2 {
@Component
export struct TapImage {
@StorageLink('tapIndex') @Watch('onTapIndexChange') tapIndex: number = -1;
@StorageLink('tapIndex') tapIndex: number = -1;
@State tapColor: Color = Color.Black;
private index: number;
private uri: Resource;
// Check whether the component is selected.
onTapIndexChange() {
if (this.tapIndex >= 0 && this.index === this.tapIndex) {
console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, red`)
this.tapColor = Color.Red;
} else {
console.info(`tapindex: ${this.tapIndex}, index: ${this.index}, black`)
this.tapColor = Color.Black;
}
}
build() {
Column() {
Image(this.uri)
......@@ -361,14 +424,18 @@ export struct TapImage {
.onClick(() => {
this.tapIndex = this.index;
})
.border({ width: 5, style: BorderStyle.Dotted, color: this.tapColor })
.border({
width: 5,
style: BorderStyle.Dotted,
color: (this.tapIndex >= 0 && this.index === this.tapIndex) ? Color.Red : Color.Black
})
}
}
}
```
## Restrictions
When using AppStorage together with [PersistentStorage](arkts-persiststorage.md) and [Environment](arkts-environment.md), pay attention to the following:
......@@ -377,5 +444,5 @@ When using AppStorage together with [PersistentStorage](arkts-persiststorage.md)
- A call to **Environment.EnvProp()** after creating the attribute in AppStorage will fail. This is because AppStorage already has an attribute with the same name, and the environment variable will not be written into AppStorage. Therefore, you are advised not to use the preset environment variable name in AppStorage.
- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Persistent Subscription and Callback](#persistent-subscription-and-callback).
- Changes to the variables decorated by state decorators will cause UI re-render. If the changes are for message communication, rather than for UI re-render, the emitter mode is recommended. For the example, see [Unrecommended: Using @StorageLink to Implement Event Notification](#unrecommended-using-storagelink-to-implement-event-notification).
<!--no_check-->
......@@ -21,14 +21,14 @@ Syntax:
```ts
@Builder myBuilderFunction({ ... })
@Builder MyBuilderFunction({ ... })
```
Usage:
```ts
this.myBuilderFunction({ ... })
this.MyBuilderFunction({ ... })
```
- Defining one or more custom builder (\@Builder decorated) functions inside a custom component is allowed. Such a custom builder function can be considered as a private, special type of member functions of that component.
......@@ -66,7 +66,7 @@ There are two types of parameter passing for custom builder functions: [by-value
- The parameter type must be the same as the declared parameter type. The **undefined** or **null** constants as well as expressions evaluating to these values are not allowed.
- All parameters are immutable inside the custom builder function. If mutability and synchronization of the mutation is required, the custom builder should be replaced by a custom component with a [@Link](arkts-link.md) decorated variable.
- All parameters are immutable inside the@Builder decorated function.
- The \@Builder function body follows the same [syntax rules](arkts-create-custom-components.md#build-function) as the **build** function.
......
......@@ -15,12 +15,11 @@ Environment is a singleton object created by the ArkUI framework at application
- Use **Environment.EnvProp** to save the environment variables of the device to AppStorage.
```ts
// Save the language code of the device to AppStorage. The default value is en.
// Whenever its value changes in the device environment, it will update its value in AppStorage.
// Save languageCode to AppStorage. The default value is en.
Environment.EnvProp('languageCode', 'en');
```
- To keep a component variable updated with changes in the device environment, this variable should be decorated with \@StorageProp.
- Decorate the variables with \@StorageProp to link them with components.
```ts
@StorageProp('languageCode') lang : string = 'en';
......@@ -29,6 +28,7 @@ Environment is a singleton object created by the ArkUI framework at application
The chain of updates is as follows: Environment > AppStorage > Component.
> **NOTE**
>
> An \@StorageProp decorated variable can be locally modified, but the change will not be updated to AppStorage. This is because the environment variable parameters are read-only to the application.
......@@ -69,3 +69,29 @@ if (lang.get() === 'en') {
console.info('Hello!');
}
```
## Restrictions
Environment can be called only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified. If Environment is called otherwise, no device environment data can be obtained.
```ts
// EntryAbility.ts
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
export default class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage: window.WindowStage) {
windowStage.loadContent('pages/Index');
let window = windowStage.getMainWindow()
window.then(window => {
let uicontext = window.getUIContext()
uicontext.runScopedTask(() => {
Environment.EnvProp('languageCode', 'en');
})
})
}
}
```
......@@ -162,6 +162,26 @@ class ClassB {
this.a = a;
}
}
@Observed
class ClassD {
public c: ClassC;
constructor(c: ClassC) {
this.c = c;
}
}
@Observed
class ClassC extends ClassA {
public k: number;
constructor(k: number) {
// Invoke the parent class method to process k.
super(k);
this.k = k;
}
}
```
......@@ -169,60 +189,64 @@ class ClassB {
```ts
@Component
struct ViewA {
label: string = 'ViewA1';
@ObjectLink a: ClassA;
struct ViewC {
label: string = 'ViewC1';
@ObjectLink c: ClassC;
build() {
Row() {
Button(`ViewA [${this.label}] this.a.c=${this.a.c} +1`)
Column() {
Text(`ViewC [${this.label}] this.a.c = ${this.c.c}`)
.fontColor('#ffffffff')
.backgroundColor('#ff3fc4c4')
.height(50)
.borderRadius(25)
Button(`ViewC: this.c.c add 1`)
.backgroundColor('#ff7fcf58')
.onClick(() => {
this.a.c += 1;
this.c.c += 1;
console.log('this.c.c:' + this.c.c)
})
}
.width(300)
}
}
}
@Entry
@Component
struct ViewB {
@State b: ClassB = new ClassB(new ClassA(0));
@State child : ClassD = new ClassD(new ClassC(0));
build() {
Column() {
ViewA({ label: 'ViewA #1', a: this.b.a })
ViewA({ label: 'ViewA #2', a: this.b.a })
Button(`ViewB: this.b.a.c+= 1`)
.onClick(() => {
this.b.a.c += 1;
})
Button(`ViewB: this.b.a = new ClassA(0)`)
ViewC({ label: 'ViewC #3', c: this.child.c})
Button(`ViewC: this.child.c.c add 10`)
.backgroundColor('#ff7fcf58')
.onClick(() => {
this.b.a = new ClassA(0);
})
Button(`ViewB: this.b = new ClassB(ClassA(0))`)
.onClick(() => {
this.b = new ClassB(new ClassA(0));
this.child.c.c += 10
console.log('this.child.c.c:' + this.child.c.c)
})
}
}
}
```
The @Observed decorated **ClassC** class can observe changes in attributes inherited from the base class.
Event handlers in **ViewB**:
- this.b.a = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes.
- this.child.c = new ClassA(0) and this.b = new ClassB(new ClassA(0)): Change to the \@State decorated variable **b** and its attributes.
- this.b.a.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink.
- this.child.c.c = ... : Change at the second layer. Though [@State](arkts-state.md#observed-changes) cannot observe the change at the second layer, the change of an attribute of \@Observed decorated ClassA, which is attribute **c** in this example, can be observed by \@ObjectLink.
Event handlers in **ViewA**:
Event handle in **ViewC**:
- this.a.c += 1: Changes to the \@ObjectLink decorated variable cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source.
- this.c.c += 1: Changes to the \@ObjectLink decorated variable **a** cause the button label to be updated. Unlike \@Prop, \@ObjectLink does not have a copy of its source. Instead, \@ObjectLink creates a reference to its source.
- The \@ObjectLink decorated variable is read-only. Assigning **this.a = new ClassA(...)** is not allowed. Once value assignment occurs, the reference to the data source is reset and the synchronization is interrupted.
......@@ -297,7 +321,7 @@ struct ViewB {
2. ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] }): The preceding update changes the first element in the array. Therefore, the **ViewA** component instance bound to **this.arrA[0]** is updated.
- this.arrA.push(new ClassA(0)): The change of this state variable triggers two updates with different effects.
1. ForEach: The newly added Class A object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **View A** component instance.
1. ForEach: The newly added **ClassA** object is unknown to the **ForEach** [itemGenerator](arkts-rendering-control-foreach.md#api-description). The item builder of **ForEach** will be executed to create a **ViewA** component instance.
2. ViewA({ label: ViewA this.arrA[last], a: this.arrA[this.arrA.length-1] }): The last item of the array is changed. As a result, the second **View A** component instance is changed. For **ViewA({ label: ViewA this.arrA[first], a: this.arrA[0] })**, a change to the array does not trigger a change to the array item, so the first **View A** component instance is not refreshed.
- this.arrA[Math.floor (this.arrA.length/2)].c: [@State](arkts-state.md#observed-changes) cannot observe changes at the second layer. However, as **ClassA** is decorated by \@Observed, the change of its attributes will be observed by \@ObjectLink.
......
......@@ -24,7 +24,7 @@ Persistence of data is a relatively slow operation. Applications should avoid th
The preceding situations may overload the change process of persisted data. As a result, the PersistentStorage implementation may limit the change frequency of persisted attributes.
PersistentStorage is associated with UIContext and can be called to persist data only when [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext) is specified. The context can be identified in [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask).
PersistentStorage can be called to persist data only when the [UIContext](../reference/apis/js-apis-arkui-UIContext.md#uicontext), which can be obtained through [runScopedTask](../reference/apis/js-apis-arkui-UIContext.md#runscopedtask), is specified.
## Application Scenarios
......
......@@ -3,6 +3,9 @@
**ForEach** enables repeated content based on array-type data.
> **NOTE**
>
> Since API version 9, this API is supported in ArkTS widgets.
## API Description
......@@ -19,8 +22,8 @@ ForEach(
| Name | Type | Mandatory | Description |
| ------------- | ---------------------------------------- | ---- | ---------------------------------------- |
| arr | Array | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.|
| itemGenerator | (item:&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.|
| 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.|
| 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: 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
......
# @ohos.WorkSchedulerExtensionAbility (Deferred Task Scheduling Callbacks)
The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling.
When developing an application, you can override the APIs of this module and add your own task logic to the APIs.
The **WorkSchedulerExtensionAbility** module provides callbacks for deferred task scheduling. You can override the APIs provided by this module. When a deferred task is triggered, the system calls back the application through the APIs and processes the task logic in the callback.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
......@@ -36,7 +34,7 @@ Called when the system starts scheduling the deferred task.
| Name | Type | Mandatory | Description |
| ---- | ---------------------------------------- | ---- | -------------- |
| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Target task.|
| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Deferred task that starts.|
**Example**
......@@ -60,7 +58,7 @@ Called when the system stops scheduling the deferred task.
| Name | Type | Mandatory | Description |
| ---- | ---------------------------------------- | ---- | -------------- |
| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Target task.|
| work | [workScheduler.WorkInfo](js-apis-resourceschedule-workScheduler.md#workinfo) | Yes | Deferred task that stops.|
**Example**
......
......@@ -12,6 +12,8 @@ The **CommonEvent** module provides common event capabilities, including the cap
```ts
import CommonEvent from '@ohos.commonEvent';
import CommonEventManager from '@ohos.commonEventManager';
import Base from '@ohos.base';
```
## Support
......@@ -43,7 +45,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r
```ts
// Callback for common event publication
function publishCB(err) {
function publishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`publish failed, code is ${err.code}`);
} else {
......@@ -80,14 +82,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca
```ts
// Attributes of a common event.
let options = {
let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event.
data: "initial data";// Result data of the common event.
data: "initial data",// Result data of the common event.
isOrdered: true // The common event is an ordered one.
}
// Callback for common event publication
function publishCB(err) {
function publishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`publish failed, code is ${err.code}`);
} else {
......@@ -125,7 +127,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb
```ts
// Callback for common event publication
function publishCB(err) {
function publishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`publishAsUser failed, code is ${err.code}`);
} else {
......@@ -168,13 +170,13 @@ Publishes a common event with given attributes to a specific user. This API uses
```ts
// Attributes of a common event.
let options = {
let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event.
data: "initial data",// Result data of the common event.
}
// Callback for common event publication
function publishCB(err) {
function publishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`publishAsUser failed, code is ${err.code}`);
} else {
......@@ -212,15 +214,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul
```ts
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for subscriber creation.
function createCB(err, commonEventSubscriber) {
function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
......@@ -259,18 +261,18 @@ Creates a subscriber. This API uses a promise to return the result.
**Example**
```ts
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Create a subscriber.
CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber) => {
CommonEvent.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => {
console.info("createSubscriber");
subscriber = commonEventSubscriber;
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`createSubscriber failed, code is ${err.code}`);
});
```
......@@ -297,15 +299,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th
**Example**
```ts
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for common event subscription.
function subscribeCB(err, data) {
function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err.code) {
console.error(`subscribe failed, code is ${err.code}`);
} else {
......@@ -314,7 +316,7 @@ function subscribeCB(err, data) {
}
// Callback for subscriber creation.
function createCB(err, commonEventSubscriber) {
function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
......@@ -351,15 +353,15 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur
**Example**
```ts
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for common event subscription.
function subscribeCB(err, data) {
function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err.code) {
console.error(`subscribe failed, code is ${err.code}`);
} else {
......@@ -368,7 +370,7 @@ function subscribeCB(err, data) {
}
// Callback for subscriber creation.
function createCB(err, commonEventSubscriber) {
function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
......@@ -380,7 +382,7 @@ function createCB(err, commonEventSubscriber) {
}
// Callback for common event unsubscription.
function unsubscribeCB(err) {
function unsubscribeCB(err:Base.BusinessError) {
if (err.code) {
console.error(`unsubscribe failed, code is ${err.code}`);
} else {
......
......@@ -10,6 +10,7 @@ The **CommonEventManager** module provides common event capabilities, including
```ts
import CommonEventManager from '@ohos.commonEventManager';
import Base from '@ohos.base';
```
## Support
......@@ -48,7 +49,7 @@ Publishes a common event and executes an asynchronous callback after the event i
```ts
// Callback for common event publication
function publishCB(err) {
function publishCB(err:Base.BusinessError) {
if (err) {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -95,14 +96,14 @@ Publishes a common event with given attributes. This API uses an asynchronous ca
```ts
// Attributes of a common event.
let options = {
let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event.
data: "initial data",// Result data of the common event.
isOrdered: true // The common event is an ordered one.
}
// Callback for common event publication
function publishCB(err) {
function publishCB(err:Base.BusinessError) {
if (err) {
console.error(`publish failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -151,7 +152,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb
```ts
// Callback for common event publication
function publishCB(err) {
function publishCB(err:Base.BusinessError) {
if (err) {
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -205,13 +206,13 @@ Publishes a common event with given attributes to a specific user. This API uses
```ts
// Attributes of a common event.
let options = {
let options:CommonEventManager.CommonEventPublishData = {
code: 0, // Result code of the common event.
data: "initial data",// Result data of the common event.
}
// Callback for common event publication.
function publishCB(err) {
function publishCB(err:Base.BusinessError) {
if (err) {
console.error(`publishAsUser failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -248,15 +249,15 @@ Creates a subscriber. This API uses an asynchronous callback to return the resul
**Example**
```ts
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for subscriber creation.
function createCB(err, commonEventSubscriber) {
function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if(!err) {
console.info("createSubscriber");
subscriber = commonEventSubscriber;
......@@ -295,18 +296,18 @@ Creates a subscriber. This API uses a promise to return the result.
**Example**
```ts
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Create a subscriber.
CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => {
CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber:CommonEventManager.CommonEventSubscriber) => {
console.info("createSubscriber");
subscriber = commonEventSubscriber;
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
});
......@@ -341,15 +342,15 @@ Subscribes to common events. This API uses an asynchronous callback to return th
```ts
// Subscriber information.
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for common event subscription.
function SubscribeCB(err, data) {
function SubscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err) {
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -358,7 +359,7 @@ function SubscribeCB(err, data) {
}
// Callback for subscriber creation.
function createCB(err, commonEventSubscriber) {
function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if(!err) {
console.info("createSubscriber");
subscriber = commonEventSubscriber;
......@@ -409,13 +410,13 @@ Unsubscribes from common events. This API uses an asynchronous callback to retur
**Example**
```ts
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for common event subscription.
function subscribeCB(err, data) {
function subscribeCB(err:Base.BusinessError, data:CommonEventManager.CommonEventData) {
if (err) {
console.error(`subscribe failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -423,7 +424,7 @@ function subscribeCB(err, data) {
}
}
// Callback for subscriber creation.
function createCB(err, commonEventSubscriber) {
function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err) {
console.error(`createSubscriber failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -438,7 +439,7 @@ function createCB(err, commonEventSubscriber) {
}
}
// Callback for common event unsubscription.
function unsubscribeCB(err) {
function unsubscribeCB(err:Base.BusinessError) {
if (err) {
console.error(`unsubscribe failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -493,7 +494,7 @@ Removes a sticky common event. This API uses an asynchronous callback to return
```ts
CommonEventManager.removeStickyCommonEvent("sticky_event", (err) => {
CommonEventManager.removeStickyCommonEvent("sticky_event", (err:Base.BusinessError) => {
if (err) {
console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
return;
......@@ -542,7 +543,7 @@ Removes a sticky common event. This API uses a promise to return the result.
```ts
CommonEventManager.removeStickyCommonEvent("sticky_event").then(() => {
console.info(`Remove sticky event AsyncCallback success`);
}).catch ((err) => {
}).catch ((err:Base.BusinessError) => {
console.info(`Remove sticky event AsyncCallback failed, errCode: ${err.code}, errMes: ${err.message}`);
});
```
......@@ -577,7 +578,7 @@ Enables or disables static subscription for the current application. This API us
```ts
CommonEventManager.setStaticSubscriberState(true, (err) => {
CommonEventManager.setStaticSubscriberState(true, (err:Base.BusinessError) => {
if (!err) {
console.info(`Set static subscriber state callback failed, err is null.`);
return;
......@@ -627,7 +628,7 @@ Enables or disables static subscription for the current application. This API us
```ts
CommonEventManager.setStaticSubscriberState(false).then(() => {
console.info(`Set static subscriber state promise success`);
}).catch ((err) => {
}).catch ((err:Base.BusinessError) => {
console.info(`Set static subscriber state promise failed, errCode: ${err.code}, errMes: ${err.message}`);
});
```
......@@ -26,7 +26,7 @@ Prepares for screen hopping. This API uses an asynchronous callback to return th
| 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**
......@@ -56,7 +56,7 @@ Prepares for screen hopping. This API uses a promise to return the result.
| 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 {
```
## cooperate.unprepare
unprepare(callback: AsyncCallback&lt;void&gt;): void;
......@@ -86,7 +85,7 @@ Cancels the preparation for screen hopping. This API uses an asynchronous callba
| 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**
......@@ -104,8 +103,6 @@ try {
}
```
## cooperate.unprepare
unprepare(): Promise&lt;void&gt;;
......@@ -118,7 +115,7 @@ Cancels the preparation for screen hopping. This API uses a promise to return th
| Parameters | Description |
| ------------------- | --------------------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
```js
try {
......@@ -133,7 +130,6 @@ try {
```
## cooperate.activate
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
| -------- | ---------------------------- | ---- | ---------------------------- |
| targetNetworkId | string | Yes | Descriptor of the target 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**
......@@ -156,7 +152,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
| ID| Error Message|
| -------- | ---------------------------------------- |
| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. |
| 20900001 | Operation failed.|
**Example**
......@@ -197,7 +193,7 @@ Starts screen hopping. This API uses a promise to return the result.
| Name | Description |
| ---------------------- | ------------------------------- |
| Promise&lt;void&gt; | Promise used to return the result. |
| Promise&lt;void&gt; | Promise that returns no value. |
**Error codes**
......@@ -205,7 +201,7 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode
| ID| Error Message|
| -------- | ---------------------------------------- |
| 20900001 | This error code is reported if the screen hopping status is abnormal when the screen hopping API is called. |
| 20900001 | Operation failed. |
**Example**
......@@ -235,8 +231,8 @@ Stops screen hopping. This API uses an asynchronous callback to return the resul
| Name | Type | Mandatory | Description |
| -------- | ---------------------------- | ---- | ---------------------------- |
| isUnchained | boolean | Yes| Whether to disable the cross-device link.|
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result. |
| 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. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.|
......@@ -268,7 +264,7 @@ Stops screen hopping. This API uses a promise to return the result.
| Name | Type | Mandatory| Description |
| ----------- | ------- | ---- | ------------------ |
| isUnchained | boolean | Yes | Whether to disable the cross-device link.|
| isUnchained | boolean | Yes | Whether to disable the cross-device link.<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.
| 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
| Name | Type | Mandatory | Description |
| -------- | --------- | ---- | ---------------------------- |
| 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**
......@@ -346,7 +342,7 @@ Obtains the screen hopping status of the target device. This API uses a promise
| 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)
The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device.
The **distributedMissionManager** module implements mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device by mission ID or bundle name.
> **NOTE**
>
......@@ -14,7 +14,6 @@ The **distributedMissionManager** module implements system mission management ac
import distributedMissionManager from '@ohos.distributedMissionManager'
```
## distributedMissionManager.registerMissionListener
registerMissionListener(parameter: MissionDeviceInfo, options: MissionCallback, callback: AsyncCallback&lt;void&gt;): void;
......@@ -30,8 +29,8 @@ Registers a mission status listener. This API uses an asynchronous callback to r
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | --------- |
| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for.|
| options | [MissionCallback](#missioncallback) | Yes | Callback to register. |
| callback | AsyncCallback&lt;void&gt; | Yes | Callback used to return the result.|
| options | [MissionCallback](#missioncallback) | Yes | Callback to register.|
| 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**
......@@ -87,7 +86,7 @@ Registers a mission status listener. This API uses a promise to return the resul
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
......@@ -123,7 +122,6 @@ Registers a mission status listener. This API uses a promise to return the resul
}
```
## distributedMissionManager.unRegisterMissionListener
unRegisterMissionListener(parameter: MissionDeviceInfo, callback: AsyncCallback&lt;void&gt;): void;
......@@ -139,7 +137,7 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | --------- |
| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Information about the device to listen for. |
| callback | AsyncCallback&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**
......@@ -159,7 +157,6 @@ Deregisters a mission status listener. This API uses an asynchronous callback to
}
```
## distributedMissionManager.unRegisterMissionListener
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
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; |Promise that returns no value.|
**Example**
......@@ -215,7 +212,7 @@ Starts to synchronize the remote mission list. This API uses an asynchronous cal
| Name | Type | Mandatory | Description |
| --------- | ------------------------------------- | ---- | --------- |
| parameter | [MissionParameter](#missionparameter) | Yes | Parameters required for synchronization. |
| callback | AsyncCallback&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**
......@@ -257,7 +254,7 @@ Starts to synchronize the remote mission list. This API uses a promise to return
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
......@@ -294,7 +291,7 @@ Stops synchronizing the remote mission list. This API uses an asynchronous callb
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | --------- |
| parameter | [MissionDeviceInfo](#missiondeviceinfo) | Yes | Parameters required for synchronization. |
| callback | AsyncCallback&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**
......@@ -334,7 +331,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Example**
......@@ -358,7 +355,7 @@ Stops synchronizing the remote mission list. This API uses a promise to return t
continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callback: AsyncCallback&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
......@@ -370,7 +367,7 @@ Continues a mission on a remote device. This API uses an asynchronous callback t
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) | Yes | Parameters required for mission continuation.|
| options | [ContinueCallback](js-apis-inner-application-continueCallback.md) | Yes | Callback invoked when the mission continuation is complete.|
| callback | AsyncCallback&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**
......@@ -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;
Continues a mission on a remote device. This API uses a promise to return the result.
Continues a mission on a remote device, with the mission ID specified. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MANAGE_MISSIONS and ohos.permission.DISTRIBUTED_DATASYNC
......@@ -433,7 +430,7 @@ Continues a mission on a remote device. This API uses a promise to return the re
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; |Promise that returns no value.|
**Error codes**
......@@ -490,7 +487,7 @@ Continues a mission on a remote device, with the bundle name specified. This API
| Name | Type | Mandatory | Description |
| --------- | --------------------------------------- | ---- | ----- |
| parameter | [ContinueMissionInfo](./js-apis-inner-application-continueMissionInfo.md) | Yes | Parameters required for mission continuation.|
| callback | AsyncCallback&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**
......@@ -546,7 +543,7 @@ Continues a mission on a remote device, with the bundle name specified. This API
| Type | Description |
| ------------------- | ---------------- |
| Promise&lt;void&gt; | Promise used to return the result.|
| Promise&lt;void&gt; | Promise that returns no value.|
**Error codes**
......@@ -586,7 +583,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er
on(type: 'continueStateChange', callback: Callback&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
......@@ -596,8 +593,8 @@ Registers a listener for the mission continuation state of the current applicati
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- |
| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. |
| callback | Callback&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. |
| 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 continuation state and information of the current mission. |
**Example**
......@@ -615,7 +612,7 @@ Registers a listener for the mission continuation state of the current applicati
off(type: 'continueStateChange', callback?: Callback&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
......@@ -625,8 +622,8 @@ Deregisters a listener for the mission continuation state of the current applica
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------- |
| type | string | Yes | Type of the listener. The value is fixed at **'continueStateChange'**. |
| callback | Callback&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. |
| 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 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**
......@@ -688,5 +685,5 @@ Enumerates the mission continuation states.
| Name | Value | Description |
| ------------- | --------- | ------------------------------------------------------------ |
| ACTIVE | 0 | Mission continuation is activated for the current application. |
| INACTIVE | 1 | Mission continuation is not activated for the current application. |
| ACTIVE | 0 | Continuation is activated for the current mission. |
| INACTIVE | 1 | Continuation is not activated for the current mission. |
......@@ -4,7 +4,7 @@ The **hiAppEvent** module provides the application event logging functions, such
> **NOTE**
>
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead.
> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md).
> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......@@ -20,7 +20,7 @@ Before using application event logging, you need to understand the requirements
**Event Name**
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter or dollar sign ($) and cannot end with an underscore (_).
**Event Type**
......@@ -30,8 +30,8 @@ An event type is an enumerated value of [EventType](#eventtype).
An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows:
- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_).
- The parameter value can be of the string, number, boolean, or array type.
- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter or dollar sign ($) and cannot end with an underscore (_).
- A parameter value can be of the string, number, boolean, or array type.
- If the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be discarded.
- If the parameter value is a number, the value must be within the range of **Number.MIN_SAFE_INTEGER** to **Number.MAX_SAFE_INTEGER**. Otherwise, uncertain values may be generated.
- If the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded.
......@@ -156,12 +156,12 @@ Provides the configuration items for application event logging.
| Name | Type | Mandatory| Description |
| ---------- | ------- | ---- | ------------------------------------------------------------ |
| disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.|
| maxStorage | string | No | Maximum size of the event file storage directory. The default value is <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
Enumerates event types.
Enumerates the event types.
**System capability**: SystemCapability.HiviewDFX.HiAppEvent
......
......@@ -122,10 +122,10 @@ Defines parameters for an **AppEventInfo** object.
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| domain | string | Yes | Event domain. Event domain name, which is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| name | string | Yes | Event name. Event name, which is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| domain | string | Yes | Event domain. The value is a string of up to 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_).|
| name | string | Yes | Event name. The value is a string of up to 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter or dollar sign ($) and cannot end with an underscore (_).|
| eventType | [EventType](#eventtype) | Yes | Event type. |
| params | object | Yes | Event parameter object, which consists of a parameter name and a parameter value. The specifications are as follows:<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
......@@ -436,7 +436,7 @@ hiAppEvent.clearData();
## EventType
Enumerates event types.
Enumerates the event types.
**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
| Type | Description |
| :---------- | :----------------------------------------------------------- |
| HttpRequest | An **HttpRequest** object, which contains the **request**, **request2**, **destroy**, **on**, or **off** method.|
| HttpRequest | An **HttpRequest** object, which contains the **request**, **requestInStream**, **destroy**, **on**, or **off** method.|
**Example**
......@@ -364,9 +364,9 @@ Destroys an HTTP request.
httpRequest.destroy();
```
### 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.
......@@ -424,18 +424,18 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
httpRequest.request2("EXAMPLE_URL", (err, data) => {
httpRequest.requestInStream("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
}
})
```
### 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.
......@@ -494,7 +494,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
httpRequest.request2("EXAMPLE_URL",
httpRequest.requestInStream("EXAMPLE_URL",
{
method: http.RequestMethod.GET,
header: {
......@@ -504,16 +504,16 @@ httpRequest.request2("EXAMPLE_URL",
connectTimeout: 60000
}, (err, data) => {
if (!err) {
console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
console.info("requestInStream OK! ResponseCode is " + JSON.stringify(data));
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
}
})
```
### 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.
......@@ -577,7 +577,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Example**
```js
let promise = httpRequest.request2("EXAMPLE_URL", {
let promise = httpRequest.requestInStream("EXAMPLE_URL", {
method: http.RequestMethod.GET,
connectTimeout: 60000,
readTimeout: 60000,
......@@ -586,9 +586,9 @@ let promise = httpRequest.request2("EXAMPLE_URL", {
}
});
promise.then((data) => {
console.info("request2 OK!" + JSON.stringify(data));
console.info("requestInStream OK!" + JSON.stringify(data));
}).catch((err) => {
console.info("request2 ERROR : err = " + JSON.stringify(err));
console.info("requestInStream ERROR : err = " + JSON.stringify(err));
});
```
......@@ -815,9 +815,9 @@ Unregisters the observer for events indicating completion of receiving HTTP stre
httpRequest.off('dataEnd');
```
### on('dataProgress')<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.
......@@ -830,20 +830,20 @@ Registers an observer for events indicating progress of receiving HTTP streaming
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value is **dataProgress**.|
| type | string | Yes | Event type. The value is **dataReceiveProgress**.|
| callback | AsyncCallback\<{ receiveSize: number, totalSize: number }\> | Yes | Callback used to return the result.<br>- **receiveSize**: number of received bytes.<br>- **totalSize**: total number of bytes to be received.|
**Example**
```js
httpRequest.on('dataProgress', (data) => {
console.info('dataProgress:' + JSON.stringify(data));
httpRequest.on('dataReceiveProgress', (data) => {
console.info('dataReceiveProgress:' + JSON.stringify(data));
});
```
### off('dataProgress')<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.
......@@ -856,13 +856,13 @@ Unregisters the observer for events indicating progress of receiving HTTP stream
| Name | Type | Mandatory| Description |
| -------- | ------------------ | ---- | -------------------------------------- |
| type | string | Yes | Event type. The value is **dataProgress**.|
| type | string | Yes | Event type. The value is **dataReceiveProgress**.|
| callback | Callback\<{ receiveSize: number, totalSize: number }\> | No | Callback used to return the result. |
**Example**
```js
httpRequest.off('dataProgress');
httpRequest.off('dataReceiveProgress');
```
## HttpRequestOptions<sup>6+</sup>
......
......@@ -10,15 +10,17 @@ Before using the **CommonEventSubscriber** module, you must obtain a **subscribe
```ts
import CommonEvent from '@ohos.commonEvent';
let subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
import CommonEventManager from '@ohos.commonEventManager';
import Base from '@ohos.base';
let subscriber:CommonEventManager.CommonEventSubscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information.
let subscribeInfo = {
let subscribeInfo:CommonEventManager.CommonEventSubscribeInfo = {
events: ["event"]
};
// Callback for subscriber creation.
function createCB(err, commonEventSubscriber) {
function createCB(err:Base.BusinessError, commonEventSubscriber:CommonEventManager.CommonEventSubscriber) {
if (err.code) {
console.error(`createSubscriber failed, code is ${err.code}`);
} else {
......@@ -49,7 +51,7 @@ Obtains the code of this common event. This API uses an asynchronous callback to
```ts
// Callback for result code obtaining of an ordered common event.
function getCodeCB(err, code) {
function getCodeCB(err:Base.BusinessError, code:number) {
if (err.code) {
console.error(`getCode failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -76,9 +78,9 @@ Obtains the code of this common event. This API uses a promise to return the res
**Example**
```ts
subscriber.getCode().then((code) => {
subscriber.getCode().then((code:number) => {
console.info("getCode " + JSON.stringify(code));
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`getCode failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -102,7 +104,7 @@ Sets the code for this common event. This API uses an asynchronous callback to r
```ts
// Callback for result code setting of an ordered common event.
function setCodeCB(err) {
function setCodeCB(err:Base.BusinessError) {
if (err.code) {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -137,7 +139,7 @@ Sets the code for this common event. This API uses a promise to return the resul
```ts
subscriber.setCode(1).then(() => {
console.info("setCode");
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -160,7 +162,7 @@ Obtains the data of this common event. This API uses an asynchronous callback to
```ts
// Callback for result data obtaining of an ordered common event.
function getDataCB(err, data) {
function getDataCB(err:Base.BusinessError, data:string) {
if (err.code) {
console.error(`getData failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -187,9 +189,9 @@ Obtains the data of this common event. This API uses a promise to return the res
**Example**
```ts
subscriber.getData().then((data) => {
subscriber.getData().then((data:string) => {
console.info("getData " + JSON.stringify(data));
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`getData failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -213,7 +215,7 @@ Sets the data for this common event. This API uses an asynchronous callback to r
```ts
// Callback for result data setting of an ordered common event
function setDataCB(err) {
function setDataCB(err:Base.BusinessError) {
if (err.code) {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -248,7 +250,7 @@ Sets the data for this common event. This API uses a promise to return the resul
```ts
subscriber.setData("publish_data_changed").then(() => {
console.info("setData");
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`setCode failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -273,7 +275,7 @@ Sets the code and data for this common event. This API uses an asynchronous call
```ts
// Callback for code and data setting of an ordered common event.
function setCodeDataCB(err) {
function setCodeDataCB(err:Base.BusinessError) {
if (err.code) {
console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -309,7 +311,7 @@ Sets the code and data for this common event. This API uses a promise to return
```ts
subscriber.setCodeAndData(1, "publish_data_changed").then(() => {
console.info("setCodeAndData");
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`setCodeAndData failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -332,7 +334,7 @@ Checks whether this common event is an ordered one. This API uses an asynchronou
```ts
// Callback for checking whether the current common event is an ordered one.
function isOrderedCB(err, isOrdered) {
function isOrderedCB(err:Base.BusinessError, isOrdered:boolean) {
if (err.code) {
console.error(`isOrderedCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -359,9 +361,9 @@ Checks whether this common event is an ordered one. This API uses a promise to r
**Example**
```ts
subscriber.isOrderedCommonEvent().then((isOrdered) => {
subscriber.isOrderedCommonEvent().then((isOrdered:boolean) => {
console.info("isOrdered " + JSON.stringify(isOrdered));
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`isOrdered failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -384,7 +386,7 @@ Checks whether this common event is a sticky one. This API uses an asynchronous
```ts
// Callback for checking whether the current common event is a sticky one.
function isStickyCB(err, isSticky) {
function isStickyCB(err:Base.BusinessError, isSticky:boolean) {
if (err.code) {
console.error(`isStickyCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -411,9 +413,9 @@ Checks whether this common event is a sticky one. This API uses a promise to ret
**Example**
```ts
subscriber.isStickyCommonEvent().then((isSticky) => {
subscriber.isStickyCommonEvent().then((isSticky:boolean) => {
console.info("isSticky " + JSON.stringify(isSticky));
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`isSticky failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -436,7 +438,7 @@ Aborts this common event. After the abort, the common event is not sent to the n
```ts
// Callback for common event aborting.
function abortCB(err) {
function abortCB(err:Base.BusinessError) {
if (err.code) {
console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -465,7 +467,7 @@ Aborts this common event. After the abort, the common event is not sent to the n
```ts
subscriber.abortCommonEvent().then(() => {
console.info("abortCommonEvent");
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`abortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -488,7 +490,7 @@ Clears the aborted state of this common event. This API takes effect only for or
```ts
// Callback for clearing the aborted state of the current common event.
function clearAbortCB(err) {
function clearAbortCB(err:Base.BusinessError) {
if (err.code) {
console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -517,7 +519,7 @@ Clears the aborted state of this common event. This API takes effect only for or
```ts
subscriber.clearAbortCommonEvent().then(() => {
console.info("clearAbortCommonEvent");
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`clearAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -540,7 +542,7 @@ Checks whether this common event is in the aborted state. This API takes effect
```ts
// Callback for checking whether the current common event is in the aborted state.
function getAbortCB(err, abortEvent) {
function getAbortCB(err:Base.BusinessError, abortEvent:boolean) {
if (err.code) {
console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -567,9 +569,9 @@ Checks whether this common event is in the aborted state. This API takes effect
**Example**
```ts
subscriber.getAbortCommonEvent().then((abortEvent) => {
subscriber.getAbortCommonEvent().then((abortEvent:boolean) => {
console.info("abortCommonEvent " + JSON.stringify(abortEvent));
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`getAbortCommonEvent failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -592,7 +594,7 @@ Obtains the subscriber information. This API uses an asynchronous callback to re
```ts
// Callback for subscriber information obtaining.
function getCB(err, subscribeInfo) {
function getCB(err:Base.BusinessError, subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) {
if (err.code) {
console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -619,9 +621,9 @@ Obtains the subscriber information. This API uses a promise to return the result
**Example**
```ts
subscriber.getSubscribeInfo().then((subscribeInfo) => {
subscriber.getSubscribeInfo().then((subscribeInfo:CommonEventManager.CommonEventSubscribeInfo) => {
console.info("subscribeInfo " + JSON.stringify(subscribeInfo));
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`getSubscribeInfo failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -644,7 +646,7 @@ Finishes this common event. This API takes effect only for ordered common events
```ts
// Callback for ordered common event finishing.
function finishCB(err) {
function finishCB(err:Base.BusinessError) {
if (err.code) {
console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`);
} else {
......@@ -674,7 +676,7 @@ Finishes this common event. This API takes effect only for ordered common events
```ts
subscriber.finishCommonEvent().then(() => {
console.info("FinishCommonEvent");
}).catch((err) => {
}).catch((err:Base.BusinessError) => {
console.error(`finishCommonEvent failed, code is ${err.code}, message is ${err.message}`);
});
```
......@@ -158,7 +158,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses an asy
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback\<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
| callback | AsyncCallback\<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
**Error codes**
......@@ -192,7 +192,7 @@ Obtains the global HTTP proxy configuration of the network. This API uses a prom
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<[HttpProxy](#httpproxy)> | Promise used to return the result.|
| Promise\<[HttpProxy](#httpproxy10)> | Promise used to return the result.|
**Error codes**
......@@ -229,7 +229,7 @@ Sets the global HTTP proxy configuration of the network. This API uses an asynch
| Name | Type | Mandatory| Description |
| --------- | ----------------------- | ---- | ------------------------------------------------------------ |
| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network. |
| httpProxy | [HttpProxy](#httpproxy10) | Yes | Global HTTP proxy configuration of the network. |
| callback | AsyncCallback\<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**
......@@ -274,7 +274,7 @@ Sets the global HTTP proxy configuration of the network. This API uses a promise
| Name | Type | Mandatory| Description |
| --------- | ------------------------------------------------------------ | ---- | ---------------- |
| httpProxy | [HttpProxy](#httpproxy) | Yes | Global HTTP proxy configuration of the network.|
| httpProxy | [HttpProxy](#httpproxy10) | Yes | Global HTTP proxy configuration of the network.|
**Return value**
......@@ -324,7 +324,7 @@ This API uses an asynchronous callback to return the result.
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
| callback | AsyncCallback<[HttpProxy](#httpproxy)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
| callback | AsyncCallback<[HttpProxy](#httpproxy10)> | Yes | Callback used to return the result. If the global HTTP proxy configuration of the network is obtained successfully, **error** is **undefined** and **data** is the global HTTP proxy configuration. Otherwise, **error** is an error object.|
**Error codes**
......@@ -347,7 +347,7 @@ connection.getDefaultHttpProxy((error, data) => {
getDefaultHttpProxy(): Promise\<HttpProxy>;
Obtains the default proxy configuration of the network.
If the global proxy is set, the global proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
If the global proxy is set, the global HTTP proxy configuration is returned. If [setAppNet](#connectionsetappnet) is used to bind the application to the network specified by [NetHandle](#nethandle), the HTTP proxy configuration of this network is returned. In other cases, the HTTP proxy configuration of the default network is returned.
This API uses a promise to return the result.
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -356,7 +356,7 @@ This API uses a promise to return the result.
| Type | Description |
| -------------------------------- | ----------------------------------------- |
| Promise<[HttpProxy](#httpproxy)> | Promise used to return the result.|
| Promise<[HttpProxy](#httpproxy10)> | Promise used to return the result.|
**Error codes**
......
......@@ -486,7 +486,7 @@ Defines the network configuration for the Ethernet connection.
| gateway | string | Yes| Gateway of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| netMask | string | Yes| Subnet mask of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in DHCP mode.|
| dnsServers | string | Yes| DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).|
| 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>
......
......@@ -4,7 +4,7 @@ The **Notification** module provides notification management capabilities, cover
> **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. This module is deprecated since API version 9.
>
> Notification subscription and unsubscription APIs are available only to system applications.
......@@ -1460,7 +1460,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal
| --------------- | ----------------------------------| ---- | -------------------- |
| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application. |
| notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. |
| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. |
| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
......@@ -1502,7 +1502,7 @@ Removes a notification for a specified bundle. This API uses a promise to return
| --------------- | --------------- | ---- | ---------- |
| bundle | [BundleOption](#bundleoptiondeprecated) | Yes | Bundle information of the application.|
| notificationKey | [NotificationKey](#notificationkeydeprecated) | Yes | Notification key. |
| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. |
| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. |
**Example**
......@@ -1536,8 +1536,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | -------------------- |
| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback. |
| reason | [RemoveReason](#removereason9-deprecated) | Yes | Indicates the reason for deleting a notification. |
| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](js-apis-inner-notification-notificationSubscriber.md#onconsume) callback.|
| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting a notification. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result.|
**Example**
......@@ -1573,7 +1573,7 @@ Removes a notification for a specified bundle. This API uses a promise to return
| Name | Type | Mandatory| Description |
| -------- | ---------- | ---- | ---------- |
| hashCode | string | Yes | Unique notification ID.|
| reason | [RemoveReason](#removereason9-deprecated) | Yes | Reason for deleting the notification. |
| reason | [RemoveReason](#removereason-deprecated) | Yes | Reason for deleting the notification. |
**Example**
......@@ -2872,10 +2872,10 @@ Notification.getDeviceRemindType().then((data) => {
>
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.BundleOption](js-apis-inner-notification-notificationCommonDef.md#bundleoption) instead.
| Name | Type | Read-only| Mandatory| Description |
| ------ | ------ |---- | --- | ------ |
| bundle | string | No | Yes | Bundle information of the application.|
| uid | number | No | No | User ID.|
| Name | Type | Mandatory| Description |
| ------ | ------ | --- | ------ |
| bundle | string | Yes | Bundle information of the application.|
| uid | number | No | User ID.|
## NotificationKey<sup>deprecated</sup>
......@@ -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. |
| groupName<sup>8+</sup>| string | Yes | Yes | Notification group name. |
| 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. |
| 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. |
......@@ -3203,7 +3203,7 @@ Provides the notification user input.
| TYPE_CONTINUOUS | 1 | Continuous notification. |
| TYPE_TIMER | 2 | Timed notification. |
## RemoveReason<sup>9+</sup> <sup>deprecated</sup>
## RemoveReason <sup>deprecated</sup>
**System capability**: SystemCapability.Notification.Notification
......@@ -3211,9 +3211,9 @@ Provides the notification user input.
> **NOTE**
>
> This API is supported since API version 9 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead.
> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [notificationManager.RemoveReason](js-apis-notificationSubscribe.md#removereason) instead.
| Name | Value | Description |
| -------------------- | --- | -------------------- |
| CLICK_REASON_REMOVE<sup>9+</sup> | 1 | The notification is removed after a click on it. |
| CANCEL_REASON_REMOVE<sup>9+</sup> | 2 | The notification is removed by the user. |
| CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. |
| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. |
......@@ -443,6 +443,90 @@ notificationSubscribe.remove(hashCode, reason).then(() => {
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
......
......@@ -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_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)|
| 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_CIRCLE<sup>10+</sup> | 41 | Circular cursor|![Cursor_Circle.png](./figures/Cursor_Circle.png)|
......@@ -1726,3 +1726,357 @@ try {
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.
You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits.
The **reminderAgentManager** module provides APIs related to agent-powered reminders. When your application is frozen or exits, the timing and notification functions of your application will be taken over by a system service running in the background. You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks.
> **NOTE**
>
......@@ -15,12 +13,15 @@ You can use the APIs to create scheduled reminders for countdown timers, calenda
import reminderAgentManager from'@ohos.reminderAgentManager';
```
## reminderAgentManager.publishReminder
publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\<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
......@@ -28,10 +29,10 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.|
| callback | AsyncCallback\<number> | Yes| Callback used to return the published reminder's ID.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.|
| callback | AsyncCallback\<number> | Yes| Callback used to return the published reminder's ID.|
**Error codes**
......@@ -62,26 +63,29 @@ try {
};
```
## reminderAgentManager.publishReminder
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
**System capability**: SystemCapability.Notification.ReminderAgent
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reminderReq | [ReminderRequest](#reminderrequest) | Yes| Request used for publishing the reminder.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<number> | Promise used to return the published reminder's ID.|
| Type| Description|
| -------- | -------- |
| Promise\<number> | Promise used to return the published reminder's ID.|
**Error codes**
......@@ -115,7 +119,7 @@ try {
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
......@@ -124,7 +128,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reminderId | number | Yes| ID of the reminder to cancel.|
| callback | AsyncCallback\<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**
......@@ -151,12 +155,11 @@ try {
};
```
## reminderAgentManager.cancelReminder
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
......@@ -170,7 +173,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise that returns no value.|
**Error codes**
......@@ -199,8 +202,7 @@ try {
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 reminders.
Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Notification.ReminderAgent
......@@ -208,7 +210,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback\<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**
......@@ -259,7 +261,7 @@ try {
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
......@@ -267,7 +269,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th
| 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**
......@@ -312,12 +314,11 @@ try {
};
```
## reminderAgentManager.cancelAllReminders
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
......@@ -325,7 +326,7 @@ Cancels all reminders set by the current application. This API uses an asynchron
| 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**
......@@ -351,12 +352,11 @@ try {
};
```
## reminderAgentManager.cancelAllReminders
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
......@@ -364,7 +364,7 @@ Cancels all reminders set by the current application. This API uses a promise to
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise that returns no value.|
**Error codes**
......@@ -401,8 +401,8 @@ Adds a notification slot. This API uses an asynchronous callback to return the r
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot. Only the type can be set.|
| callback | AsyncCallback\<void> | Yes| Callback used to return the result. If the notification slot is added, **err** is **undefined**. Otherwise, **err** is an error object.|
**Example**
......@@ -438,13 +438,13 @@ Adds a notification slot. This API uses a promise to return the result.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.|
| slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot. Only the type can be set.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise that returns no value.|
**Example**
......@@ -470,7 +470,7 @@ try {
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
......@@ -479,7 +479,7 @@ Removes a notification slot of a specified type. This API uses an asynchronous c
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.|
| callback | AsyncCallback\<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**
......@@ -504,7 +504,7 @@ try {
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
......@@ -518,7 +518,7 @@ Removes a notification slot of a specified type. This API uses a promise to retu
| Type| Description|
| -------- | -------- |
| Promise\<void> | Promise used to return the result.|
| Promise\<void> | Promise that returns no value.|
**Example**
......@@ -538,7 +538,7 @@ try {
## ActionButtonType
Enumerates button types.
Enumerates the button types.
**System capability**: SystemCapability.Notification.ReminderAgent
......@@ -551,7 +551,7 @@ Enumerates button types.
## ReminderType
Enumerates reminder types.
Enumerates the reminder types.
**System capability**: SystemCapability.Notification.ReminderAgent
......@@ -564,8 +564,7 @@ Enumerates reminder types.
## ActionButton
Defines a button displayed for the reminder in the notification panel.
Defines the button on the reminder displayed.
**System capability**: SystemCapability.Notification.ReminderAgent
......@@ -573,7 +572,7 @@ Defines a button displayed for the reminder in the notification panel.
| -------- | -------- | -------- | -------- |
| title | string | Yes| Text on the button.|
| type | [ActionButtonType](#actionbuttontype) | Yes| Button type.|
| 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
......@@ -592,19 +591,19 @@ Defines the information about the redirected-to ability.
## MaxScreenWantAgent
Provides the information about the target package and ability to start automatically when the reminder is displayed in full-screen mode. This API is reserved.
Provides the information about the ability that is started automatically and displayed in full-screen mode when the reminder arrives. This API is reserved.
**System capability**: SystemCapability.Notification.ReminderAgent
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.|
| abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.|
| pkgName | string | Yes| Name of the target package. (If the device is in use, only a notification banner is displayed.)|
| abilityName | string | Yes| Name of the target ability. (If the device is in use, only a notification banner is displayed.)|
## ReminderRequest
Defines the reminder to publish.
Defines the request for publishing a reminder.
**System capability**: SystemCapability.Notification.ReminderAgent
......@@ -613,7 +612,7 @@ Defines the reminder to publish.
| reminderType | [ReminderType](#remindertype) | Yes| Type of the reminder.|
| actionButton<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.|
| 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**.|
| snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.|
| timeInterval | number | No| Reminder snooze interval, in seconds. The minimum value is 5 minutes.|
......@@ -623,8 +622,8 @@ Defines the reminder to publish.
| snoozeContent | string | No| Content to be displayed when the reminder is snoozing.|
| notificationId | number | No| Notification ID used by the reminder. If there are reminders with the same notification ID, the later one will overwrite the earlier one.|
| slotType | [notification.SlotType](js-apis-notificationManager.md#slottype) | No| Type of the slot used by the reminder.|
| 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).|
| 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).|
| 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 reminder is automatically cleared. For details, see [NotificationRequest.autoDeletedTime](js-apis-inner-notification-notificationRequest.md#notificationrequest).|
## ReminderRequestCalendar
......
# @ohos.resourceschedule.workScheduler (Deferred Task Scheduling)
The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks.
The system schedules and executes deferred tasks at an appropriate time, subject to the storage space, power consumption, temperature, and more.
The **workScheduler** module provides the APIs for registering, canceling, and querying deferred tasks. You can use the APIs to register tasks that do not have high requirements on real-time performance as deferred tasks. The system schedules and executes the deferred tasks at an appropriate time, subject to the storage space, power consumption, and more.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> - The APIs of this module can be used only in the stage model.
> - For details about the constraints on deferred task scheduling, see [Constraints](../../task-management/work-scheduler.md#constraints).
## Modules to Import
......@@ -18,9 +15,10 @@ import workScheduler from '@ohos.resourceschedule.workScheduler';
```
## workScheduler.startWork
startWork(work: WorkInfo): void
Instructs the WorkSchedulerService to add a task to the execution queue.
Starts a deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -28,7 +26,7 @@ Instructs the WorkSchedulerService to add a task to the execution queue.
| Name | Type | Mandatory | Description |
| ---- | --------------------- | ---- | -------------- |
| work | [WorkInfo](#workinfo) | Yes | Task to be added to the execution queue.|
| work | [WorkInfo](#workinfo) | Yes | Deferred task to start.|
**Error codes**
......@@ -42,7 +40,6 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
| 9700004 | Check workInfo failed. |
| 9700005 | StartWork failed. |
**Example**
```js
......@@ -69,9 +66,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.stopWork
stopWork(work: WorkInfo, needCancel?: boolean): void
Instructs the WorkSchedulerService to stop a task.
Stops a deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -79,8 +77,8 @@ Instructs the WorkSchedulerService to stop a task.
| Name | Type | Mandatory | Description |
| ---------- | --------------------- | ---- | ---------- |
| work | [WorkInfo](#workinfo) | Yes | Task to stop. |
| needCancel | boolean | No | Whether to cancel the task. The default value is **false**.|
| work | [WorkInfo](#workinfo) | Yes | Deferred task to stop.|
| needCancel | boolean | No | Whether to clear the task while stopping it.<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**
......@@ -119,9 +117,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.getWorkStatus
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
......@@ -129,8 +128,8 @@ Obtains the latest task status. This API uses an asynchronous callback to return
| Name | Type | Mandatory | Description |
| -------- | ------------------------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. |
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
| workId | number | Yes | ID of the deferred task. |
| callback | AsyncCallback\<[WorkInfo](#workinfo)> | Yes | Callback used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned. Otherwise, an exception is thrown.|
**Error codes**
......@@ -162,9 +161,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.getWorkStatus
getWorkStatus(workId: number): Promise\<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
......@@ -172,13 +172,13 @@ Obtains the latest task status. This API uses a promise to return the result.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
| workId | number | Yes | Task ID.|
| workId | number | Yes | ID of the deferred task.|
**Return value**
| Type | Description |
| ------------------------------- | ---------------------------------------- |
| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If the specified task ID is valid, the task status obtained from the WorkSchedulerService is returned. Otherwise, an exception is thrown.|
| Promise\<[WorkInfo](#workinfo)> | Promise used to return the result. If **workId** is valid, the task information obtained from WorkSchedulerService is returned.|
**Error codes**
......@@ -208,9 +208,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.obtainAllWorks
obtainAllWorks(callback : AsyncCallback\<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
......@@ -218,13 +219,13 @@ Obtains all tasks associated with the application. This API uses an asynchronous
| 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**
| Type | Description |
| ----------------------------- | --------------- |
| Array\<[WorkInfo](#workinfo)> | All tasks associated with the application.|
| Array\<[WorkInfo](#workinfo)> | All the deferred tasks.|
**Error codes**
......@@ -253,9 +254,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.obtainAllWorks
obtainAllWorks(): Promise\<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
......@@ -263,7 +265,7 @@ Obtains all tasks associated with the application. This API uses a promise to re
| 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**
......@@ -290,9 +292,10 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.stopAndClearWorks
stopAndClearWorks(): void
Stops and cancels all tasks associated with the application.
Stops and clears all the deferred tasks.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -318,6 +321,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number, callback : AsyncCallback\<void>): boolean
Checks whether the last execution of a task timed out. This API uses an asynchronous callback to return the result.
......@@ -328,14 +332,14 @@ Checks whether the last execution of a task timed out. This API uses an asynchro
| Name | Type | Mandatory | Description |
| -------- | -------------------- | ---- | ---------------------------------------- |
| workId | number | Yes | Task ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
| workId | number | Yes | ID of the deferred task. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result.|
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if the last execution of the task timed out; returns **false** otherwise.|
| boolean | The value **true** means that the last execution of the specified task times out, and **false** means the opposite.|
**Error codes**
......@@ -365,6 +369,7 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## workScheduler.isLastWorkTimeOut
isLastWorkTimeOut(workId: number): Promise\<boolean>
Checks whether the last execution of a task timed out. This API uses a promise to return the result.
......@@ -375,13 +380,13 @@ Checks whether the last execution of a task timed out. This API uses a promise t
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | -------- |
| workId | number | Yes | Task ID.|
| workId | number | Yes | ID of the deferred task.|
**Return value**
| Type | Description |
| ----------------- | ---------------------------------------- |
| Promise\<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**
......@@ -411,31 +416,33 @@ For details about the error codes, see [workScheduler Error Codes](../errorcodes
```
## WorkInfo
Provides detailed information about the task. For details about the constraints on setting the **WorkInfo** parameter, see [Constraints](../../task-management/work-scheduler.md#constraints).
Defines the information about the deferred task.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
| Name | Type | Mandatory | Description |
| --------------- | --------------------------------- | ---- | ---------------- |
| workId | number | Yes | Task ID. |
| workId | number | Yes | ID of the deferred task. |
| bundleName | string | Yes | Bundle name of the application that requests the task. |
| abilityName | string | Yes | Name of the component to be notified by a deferred task scheduling callback.|
| networkType | [NetworkType](#networktype) | No | Network type. |
| isCharging | boolean | No | Whether the device is charging. |
| isCharging | boolean | No | Whether the device needs to enter the charging state to trigger deferred task scheduling.<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. |
| batteryLevel | number | No | Battery level. |
| batteryStatus | [BatteryStatus](#batterystatus) | No | Battery status. |
| storageRequest | [StorageRequest](#storagerequest) | No | Storage status. |
| isRepeat | boolean | No | Whether the task is repeated. |
| isRepeat | boolean | No | Whether the task is repeated.<br>The value** true** means that the task is repeated, and **false** means the opposite.|
| repeatCycleTime | number | No | Repeat interval. |
| repeatCount | number | No | Number of repeat times. |
| isPersisted | boolean | No | Whether to enable persistent storage for the task. |
| isDeepIdle | boolean | No | Whether the device needs to enter the idle state. |
| idleWaitTime | number | No | Time to wait in the idle state. |
| parameters | {[key: string]: number \| string \| boolean} | No | Carried parameters. |
| isPersisted | boolean | No | Whether to enable persistent storage for the task.<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 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 before triggering deferred task scheduling. |
| parameters | [key: string]: number \| string \| boolean | No | Carried parameters.|
## NetworkType
Enumerates the network types that can trigger task scheduling.
Enumerates the network types that can trigger deferred task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -449,7 +456,8 @@ Enumerates the network types that can trigger task scheduling.
| NETWORK_TYPE_ETHERNET | 5 | Ethernet. |
## ChargingType
Enumerates the charging types that can trigger task scheduling.
Enumerates the charging types that can trigger deferred task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -461,7 +469,8 @@ Enumerates the charging types that can trigger task scheduling.
| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. |
## BatteryStatus
Enumerates the battery states that can trigger task scheduling.
Enumerates the battery statuses that can trigger deferred task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -472,7 +481,8 @@ Enumerates the battery states that can trigger task scheduling.
| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.|
## StorageRequest
Enumerates the storage states that can trigger task scheduling.
Enumerates the storage statuses that can trigger deferred task scheduling.
**System capability**: SystemCapability.ResourceSchedule.WorkScheduler
......@@ -480,4 +490,4 @@ Enumerates the storage states that can trigger task scheduling.
| ------------------------- | ---- | ------------------------------ |
| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. |
| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. |
| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.|
| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is insufficient, or the storage space is restored from insufficient to normal.|
......@@ -51,7 +51,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
router.pushUrl({
try {
router.pushUrl({
url: 'pages/routerpage2',
params: {
data1: 'message',
......@@ -59,13 +60,10 @@ router.pushUrl({
data3: [123, 456, 789]
}
}
})
.then(() => {
// success
})
.catch(err => {
} catch (err) {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
})
}
```
## router.pushUrl<sup>9+</sup>
......@@ -146,7 +144,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
router.pushUrl({
try {
router.pushUrl({
url: 'pages/routerpage2',
params: {
data1: 'message',
......@@ -154,13 +153,10 @@ router.pushUrl({
data3: [123, 456, 789]
}
}
}, router.RouterMode.Standard)
.then(() => {
// success
})
.catch(err => {
}, router.RouterMode.Standard)
} catch (err) {
console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`);
})
}
```
## router.pushUrl<sup>9+</sup>
......@@ -241,18 +237,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
router.replaceUrl({
try {
router.replaceUrl({
url: 'pages/detail',
params: {
data1: 'message'
}
})
.then(() => {
// success
})
.catch(err => {
} catch (err) {
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
})
}
```
## router.replaceUrl<sup>9+</sup>
......@@ -330,18 +324,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
router.replaceUrl({
try {
router.replaceUrl({
url: 'pages/detail',
params: {
data1: 'message'
}
}, router.RouterMode.Standard)
.then(() => {
// success
})
.catch(err => {
}, router.RouterMode.Standard)
} catch (err) {
console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`);
})
}
```
## router.replaceUrl<sup>9+</sup>
......@@ -420,7 +412,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
router.pushNamedRoute({
try {
router.pushNamedRoute({
name: 'myPage',
params: {
data1: 'message',
......@@ -428,15 +421,14 @@ router.pushNamedRoute({
data3: [123, 456, 789]
}
}
})
.then(() => {
// success
})
.catch(err => {
} 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>
pushNamedRoute(options: NamedRouterOptions, callback: AsyncCallback&lt;void&gt;): void
......@@ -515,7 +507,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
router.pushNamedRoute({
try {
router.pushNamedRoute({
name: 'myPage',
params: {
data1: 'message',
......@@ -523,13 +516,10 @@ router.pushNamedRoute({
data3: [123, 456, 789]
}
}
}, router.RouterMode.Standard)
.then(() => {
// success
})
.catch(err => {
}, router.RouterMode.Standard)
} catch (err) {
console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
})
}
```
## router.pushNamedRoute<sup>10+</sup>
......@@ -610,18 +600,16 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
**Example**
```ts
router.replaceNamedRoute({
try {
router.replaceNamedRoute({
name: 'myPage',
params: {
data1: 'message'
}
})
.then(() => {
// success
})
.catch(err => {
} catch (err) {
console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
})
}
```
## router.replaceNamedRoute<sup>10+</sup>
......@@ -693,24 +681,22 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc
| ID | Error Message|
| --------- | ------- |
| 100001 | if UI execution context not found, only throw in standard system. |
| 100001 | if can not get the delegate, only throw in standard system. |
| 100004 | if the named route is not exist. |
**Example**
```ts
router.replaceNamedRoute({
try {
router.replaceNamedRoute({
name: 'myPage',
params: {
data1: 'message'
}
}, router.RouterMode.Standard)
.then(() => {
// success
})
.catch(err => {
}, router.RouterMode.Standard)
} catch (err) {
console.error(`replaceNamedRoute failed, code is ${err.code}, message is ${err.message}`);
})
}
```
## router.replaceNamedRoute<sup>10+</sup>
......@@ -932,7 +918,7 @@ Describes the page routing options.
| Name | Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------------------------------------------ |
| url | string | Yes | URL of the target page, in either of the following formats:<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**
......
......@@ -2732,7 +2732,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses an async
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_TELEPHONY_STATE
**Required permission**: ohos.permission.GET_PHONE_NUMBERS
**System capability**: SystemCapability.Telephony.CoreService
......@@ -2775,7 +2775,7 @@ Obtains the MSISDN of the SIM card in the specified slot. This API uses a promis
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_TELEPHONY_STATE
**Required permission**: ohos.permission.GET_PHONE_NUMBERS
**System capability**: SystemCapability.Telephony.CoreService
......
......@@ -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.
> **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.
**Required permissions**: ohos.permission.INTERNET
......@@ -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.
> **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.
**Required permissions**: ohos.permission.INTERNET
......
......@@ -254,20 +254,20 @@ struct WebComponent {
.onClick(() => {
// Use the local port to send messages to HTML5.
try {
console.log("In eTS side send true start");
console.log("In ArkTS side send true start");
if (this.nativePort) {
this.message.setString("helloFromEts");
this.nativePort.postMessageEventExt(this.message);
}
}
catch (error) {
console.log("In eTS side send message catch error:" + error.code + ", msg:" + error.message);
console.log("In ArkTS side send message catch error:" + error.code + ", msg:" + error.message);
}
})
Web({ src: $rawfile('index.html'), controller: this.controller })
.onPageEnd((e)=>{
console.log("In eTS side message onPageEnd init mesaage channel");
console.log("In ArkTS side message onPageEnd init mesaage channel");
// 1. Create a message port.
this.ports = this.controller.createWebMessagePorts(true);
// 2. Send port 1 to HTML5.
......@@ -276,10 +276,10 @@ struct WebComponent {
this.nativePort = this.ports[0];
// 4. Set the callback.
this.nativePort.onMessageEventExt((result) => {
console.log("In eTS side got message");
console.log("In ArkTS side got message");
try {
var type = result.getType();
console.log("In eTS side getType:" + type);
console.log("In ArkTS side getType:" + type);
switch (type) {
case web_webview.WebMessageType.STRING: {
this.msg1 = "result type:" + typeof (result.getString());
......@@ -652,13 +652,13 @@ struct WebComponent {
There are three methods for loading local resource files:
1. Using $rawfile
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
......@@ -675,17 +675,17 @@ There are three methods for loading local resource files:
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
}
```
2. Using the resources protocol
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
......@@ -693,7 +693,7 @@ There are three methods for loading local resource files:
Button('loadUrl')
.onClick(() => {
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");
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
......@@ -702,21 +702,21 @@ There are three methods for loading local resource files:
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
}
```
3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](../arkui-ts/ts-basic-components-web.md#web).
HTML file to be loaded:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
HTML file to be loaded:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
</html>
```
### loadData
......@@ -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
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()
| 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**|
> **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
| Name | Description|
......
......@@ -41,7 +41,7 @@ Since API version 9, this API is supported in ArkTS widgets.
| Name | Type | Mandatory | Description |
| ------------ | ---------------------------------------- | ---- | ---------------------------------------- |
| space | number \| string | No | Spacing between list items along the main axis.<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.|
| 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.|
......
......@@ -63,8 +63,8 @@ This error code is reported if the **write** API is called to perform applicatio
The specified event name does not comply with the following rules:
- The event name contains only digits, lowercase letters, and underscores (\_).
- The event name starts with a lowercase letter and does not end with an underscore (\_).
- An event name contains only digits, letters, and underscores (_).
- An event name starts with a letter or dollar sign ($) and does not end with an underscore (_).
- The event name is not empty and contains a maximum of 48 characters.
**Solution**
......@@ -119,11 +119,11 @@ This error code is reported if the **write** API is called to perform applicatio
**Possible Causes**
The specified event parameter name does not comply with the following rules:
The specified event name does not comply with the following rules:
- The event parameter name contains only digits, lowercase letters, and underscores (\_).
- The event parameter name starts with a lowercase letter and does not end with an underscore (\_).
- The event parameter name is not empty and contains a maximum of 16 characters.
- An event name contains only digits, letters, and underscores (_).
- An event name starts with a letter or dollar sign ($) and does not end with an underscore (_).
- An event parameter name is not empty and contains a maximum of 16 characters.
**Solution**
......@@ -163,7 +163,7 @@ The specified watcher name does not comply with the following rules:
- The watcher name can contain only digits, lowercase letters, and underscores (\_).
- The watcher name starts with a lowercase letter and does not end with an underscore (\_).
- The watcher name is not empty and contains a maximum of 32 characters.
- A watcher name is not empty and contains a maximum of 32 characters.
**Solution**
......
......@@ -62,8 +62,8 @@ The table below lists the APIs used for developing deferred tasks. For details a
| -------- | -------- |
| startWork(work: WorkInfo): void; | Starts a deferred task.|
| stopWork(work: WorkInfo, needCancel?: boolean): void; | Stops a deferred task.|
| getWorkStatus(workId: number, callback: AsyncCallback&lt;WorkInfo&gt;): void; | Obtains the status of 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, 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 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(): 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.|
......@@ -77,7 +77,7 @@ The table below lists the APIs used for developing deferred tasks. For details a
| bundleName | string | Bundle name of the application that requests the deferred task.|
| abilityName | string | Name of the ability to be notified by a deferred task scheduling callback. This parameter is mandatory.|
| networkType | [NetworkType](../reference/apis/js-apis-resourceschedule-workScheduler.md#networktype) | Network type.|
| isCharging | boolean | Whether the device is charging.|
| isCharging | boolean | Whether the device needs to enter the charging state to trigger deferred task scheduling.|
| chargerType | [ChargingType](../reference/apis/js-apis-resourceschedule-workScheduler.md#chargingtype) | Charging type.|
| batteryLevel | number | Battery level.|
| batteryStatus | [BatteryStatus](../reference/apis/js-apis-resourceschedule-workScheduler.md#batterystatus) | Battery status.|
......
......@@ -299,7 +299,7 @@ List() {
})
```
This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 8.
This example draws a divider with a stroke thickness of 1 vp from a position 60 vp away from the start edge of the list to a position 10 vp away from the end edge of the list. The effect is shown in Figure 9.
>**NOTE**
>
......@@ -653,8 +653,6 @@ The following describes the implementation of the pull-and-refresh feature:
3. Listen for the finger lift event. If the movement reaches the maximum value, trigger data loading and display the refresh view. After the loading is complete, hide the view.
You can also use the third-party component [PullToRefresh](https://gitee.com/openharmony-sig/PullToRefresh) to implement this feature.
## Editing a List
......
......@@ -11,23 +11,26 @@ Page redirection is an important part of the development process. When using an
**Figure 1** Page redirection
![router-jump-to-detail](figures/router-jump-to-detail.gif)
The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). The two modes determine whether the target page will replace the current page.
The **Router** module provides two redirection modes: [router.pushUrl()](../reference/apis/js-apis-router.md#routerpushurl9) and [router.replaceUrl()](../reference/apis/js-apis-router.md#routerreplaceurl9). Whether the target page will replace the current page depends on the mode used.
- **router.pushUrl()**: The target page does not replace the current page. Instead, it is pushed into the [page stack](../application-models/page-mission-stack.md). In this way, the state of the current page can be retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API.
- **router.pushUrl()**: The target page is pushed into the [page stack](../application-models/page-mission-stack.md) and does not replace the current page. In this mode, the state of the current page is retained, and users can return to the current page by pressing the back button or calling the [router.back()](../reference/apis/js-apis-router.md#routerback) API.
- **router.replaceUrl()**: The target page replaces the current page and destroys the current page. In this way, the resources of the current page can be released, and users cannot return to the current page.
- **router.replaceUrl()**: The target page replaces and destroys the current page. In this mode, the resources of the current page can be released, and users cannot return to the current page.
>**NOTE**
>
>The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory.
>- When creating a page, configure the route to this page by following instructions in [Building the Second Page](../quick-start/start-with-ets-stage.md).
>
>
>- The maximum capacity of a page stack is 32 pages. If this limit is exceeded, the [router.clear()](../reference/apis/js-apis-router.md#routerclear) API can be called to clear the historical page stack and free the memory.
The **Router** module also provides two instance modes: **Standard** and **Single**. The two modes determine whether the target URL corresponds to multiple instances.
The **Router** module also provides two instance modes: **Standard** and **Single**. Depending on the mode, the target URL is mapped to one or more instances.
- **Standard**: standard instance mode, which is the default instance mode. Each time this API is called, a target page is created and pushed to the top of the stack.
- **Standard**: multi-instance mode. It is the default instance mode. In this mode, the target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack.
- **Single**: singleton mode. If the URL of the target page already exists in the page stack, the page with the same URL closest to the top of the stack is moved to the top of the stack and reloaded. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode.
- **Single**: singleton mode. In this mode, if the URL of the target page already exists in the page stack, the page closest to the top of the stack with the same URL is moved to the top of the stack and becomes the new page. If the URL of the target page does not exist in the page stack, the page is redirected in standard mode.
Before using the **Router** module, you need to import it to the code.
Before using the **Router** module, import it first.
```ts
......@@ -54,7 +57,7 @@ import router from '@ohos.router';
>**NOTE**
>
>In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted.
>In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted.
- Scenario 2: There is a login page (**Login**) and a personal center page (**Profile**). After a user successfully logs in from the **Login** page, the **Profile** page is displayed. At the same time, the **Login** page is destroyed, and the application exits when the back button is pressed. In this scenario, you can use the **replaceUrl()** API and use the Standard instance mode (which can also be omitted).
......@@ -76,7 +79,7 @@ import router from '@ohos.router';
>**NOTE**
>
>In **Standard** instance mode, the **router.RouterMode.Standard** parameter can be omitted.
>In standard (multi-instance) mode, the **router.RouterMode.Standard** parameter can be omitted.
- Scenario 3: There is a setting page (**Setting**) and a theme switching page (**Theme**). You want to click a theme option on the **Setting** page to go to the **Theme** page. In addition, you want to ensure that only one **Theme** page exists in the page stack at a time. When the back button is clicked on the **Theme** page, the **Setting** page is displayed. In this scenario, you can use the **pushUrl()** API and use the **Single** instance mode.
......@@ -115,7 +118,7 @@ import router from '@ohos.router';
The preceding scenarios do not involve parameter transfer.
If you need to transfer some data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example:
If you need to transfer data to the target page during redirection, you can add a **params** attribute and specify an object as a parameter when invoking an API of the **Router** module. Example:
```ts
......@@ -150,11 +153,11 @@ function onJumpClick(): void {
}
```
On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the transferred parameters. Example:
On the target page, you can call the [getParams()](../reference/apis/js-apis-router.md#routergetparams) API of the **Router** module to obtain the passed parameters. Example:
```ts
const params = router.getParams(); // Obtain the transferred parameter object.
const params = router.getParams(); // Obtain the passed parameters.
const id = params['id']; // Obtain the value of the id attribute.
const age = params['info'].age; // Obtain the value of the age attribute.
```
......@@ -162,13 +165,13 @@ const age = params['info'].age; // Obtain the value of the age attribute.
## Page Return
After a user completes an operation on a page, the user usually needs to return to the previous page or a specified page. In this case, the page return function is required. During the return process, the data may need to be transferred to the target page, which requires the data transfer function.
Implement the page return feature so that users can return to the previous page or a specified page. You can pass parameters to the target page during the return process.
**Figure 2** Page return
![router-back-to-home](figures/router-back-to-home.gif)
Before using the **Router** module, you need to import it to the code.
Before using the **Router** module, import it first.
```ts
......@@ -195,7 +198,7 @@ You can use any of the following methods to return to a page:
});
```
This method allows you to return to a specified page. You need to specify the path of the target page. For this method to work, the target page must it exist in the page stack.
This method allows uesrs to return to a page with the specified path. For this method to work, the target page must exist in the page stack.
- Method 3: Return to the specified page and transfer custom parameter information.
......@@ -209,14 +212,14 @@ You can use any of the following methods to return to a page:
});
```
This method not only allows you to return to the specified page, but also transfer custom parameter information when returning. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page.
This method not only allows you to return to the specified page, but also pass in custom parameter information during the return process. The parameter information can be obtained and parsed by invoking the **router.getParams()** API on the target page.
On the target page, call the **router.getParams()** API at the position where parameters need to be obtained, for example, in the **onPageShow()** lifecycle callback:
```ts
onPageShow() {
const params = router.getParams(); // Obtain the transferred parameter object.
const params = router.getParams(); // Obtain the passed parameters.
const info = params['info']; // Obtain the value of the info attribute.
}
```
......@@ -243,7 +246,7 @@ Such a dialog box can be in the [default style](#default-confirmation-dialog-box
To implement this function, you can use the [router.showAlertBeforeBackPage()](../reference/apis/js-apis-router.md#routershowalertbeforebackpage9) and [router.back()](../reference/apis/js-apis-router.md#routerback) APIs provided by the **Router** module.
Before using the **Router** module, you need to import it to the code.
Before using the **Router** module, import it first.
```ts
......@@ -272,17 +275,16 @@ function onBackClick(): void {
The **router.showAlertBeforeBackPage()** API receives an object as a parameter. The object contains the following attributes:
- **message**: content of the dialog box. The value is of the string type.
If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**.
When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
**message**: content of the dialog box. The value is of the string type.
If the API is successfully called, the confirmation dialog box is displayed on the target page. Otherwise, an exception is thrown and the error code and error information is obtained through **err.code** and **err.message**.
When the user clicks the back button, a confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
### Custom Confirmation Dialog Box
To implement a custom confirmation dialog box, use APIs in the [PromptAction](../reference/apis/js-apis-promptAction.md#promptactionshowdialog) module or customize a popup window. This topic uses the APIs in the **PromptAction** module an example to describe how to implement a custom confirmation dialog box.
Before using the **Router** module, you need to import it to the code.
Before using the **Router** module, import it first.
```ts
......@@ -324,3 +326,63 @@ function onBackClick() {
```
When the user clicks the back button, the custom confirmation dialog box is displayed, prompting the user to confirm their operation. If the user selects Cancel, the application stays on the current page. If the user selects OK, the **router.back()** API is triggered and the redirection is performed based on the parameters.
## Named Route
To redirect to a [page in a shared package](../quick-start/shared-guide.md), you can use [router.pushNamedRoute()](../reference/apis/js-apis-router.md#routerpushnamedroute10).
Before using the **Router** module, import it first.
```ts
import router from '@ohos.router';
```
In the target page in the [shared package](../quick-start/shared-guide.md), name the [@Entry decorated custom component](../quick-start/arkts-create-custom-components.md#entryoptions10).
```ts
// library/src/main/ets/pages/Index.ets
@Entry({ routeName : 'myPage' })
@Component
struct MyComponent {
}
```
When the configuration is successful, import the named route page to the page from which you want to redirect.
```ts
// entry/src/main/ets/pages/Index.ets
import router from '@ohos.router';
import 'library/src/main/ets/Index.ets' // Import the named route page from the shared package library.
@Entry
@Component
struct Index {
build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Text('Hello World')
.fontSize(50)
.fontWeight(FontWeight.Bold)
.margin({ top: 20 })
.backgroundColor('#ccc')
.onClick(() => { // Click to go to a page in another shared package.
try {
router.pushNamedRoute({
name: 'myPage',
params: {
data1: 'message',
data2: {
data3: [123, 456, 789]
}
}
})
} catch (err) {
console.error(`pushNamedRoute failed, code is ${err.code}, message is ${err.message}`);
}
})
}
.width('100%')
.height('100%')
}
}
```
......@@ -33,10 +33,11 @@ Constraints on the event domain, event name, and parameter
| 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|
| 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
......@@ -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 |
| 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
......
......@@ -40,7 +40,7 @@ The standard system capabilities of OpenHarmony 4.0 are continuously improved. A
- RDB store NDK interfaces are provided. These interfaces are used for transaction addition, deletion, modification, and query, data encryption, hierarchical data protection, and backup and restore.
- The system can automatically selects a Bluetooth or Wi-Fi P2P channel for synchronization of key-value and distributed data objects based on the data volume.
- The system can automatically select a Bluetooth or Wi-Fi P2P channel for synchronization of key-value and distributed data objects based on the data volume.
### DSoftBus
......@@ -391,7 +391,7 @@ This version has the following updates to OpenHarmony 4.0 Beta1.
### API
For details about the API changes over OpenHarmony 4.0 Beta1, see [API Differences](/api-diff/v4.0-beta2/Readme-EN.md). A few API changes may affect applications developed using API version 9 or earlier. For details about the change impact and adaptation guide, see [Changelogs](changelogs/v4.0-beta2/Readme-EN.md).
For details about the API changes over OpenHarmony 4.0 Beta1, see [API Differences](https://gitee.com/openharmony/docs/blob/OpenHarmony-4.0-Beta2/en/release-notes/api-diff/v4.0-beta2/Readme-EN.md). A few API changes may affect applications developed using API version 9 or earlier. For details about the change impact and adaptation guide, see [Changelogs](https://gitee.com/openharmony/docs/blob/OpenHarmony-4.0-Beta2/en/release-notes/changelogs/v4.0-beta2/Readme-EN.md).
### Feature Updates
......
# 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.
# ArkCompiler Subsystem Changelog
## cl.ArkCompiler.1 type compileMode uses es2abc by default
## cl.ArkCompiler.1 Change of Default Compiler to es2abc in Type Compilation
The composition of ArkCompiler in sdk has ts2abc compiler and es2abc compiler, supporting compilation of ets/ts/js files.<br>
Compilation Mode Introduction:<br>
&emsp;Non-type compilation: convert ets/ts sourceCode into js sourceCode, and use ArkCompiler compiler es2abc to generate bytecode. <br>
&emsp;type compilation: convert ets/ts sourceCode into ts sourceCode, and use ArkCompiler compiler ts2abc (previous version)/es2abc (enabled in this version) to generate bytecode. <br>
Application Project hvigor version:<br>
&emsp;hvigorVersion field and @ohos/hvigor-ohos-plugin field in dependencies of hvigor-config.json5 file in the hvigor directory of the application project.<br>
Enable type compilation:<br>
&emsp;When the hvigor version is greater than or equal to 2.6.0-rc.9.s, the type compilation mode is used by default, or in the build-profile.json5 file of the same level directory as the application sourceCode (src directory), configure the "aotCompileMode": "type" option under the buildOption tag<br>
In the SDK, ArkCompiler has two compilers that support ets/ts/js compilation: ts2abc compiler and es2abc compiler.
When type compilation is enabled and this version of the SDK is used, the ArkCompiler compiler es2abc will be used by default to compile the ts sourceCode to generate bytecode, and it is not recommended to use the old version SDK with ts2abc enabled for type compilation.<br>
Introduction to compilation modes:
**Change Impact**<br>
With DevEco Studio development, after the type compilation mode is enabled and the new version of the SDK is used, due to the change of the compilation mode and the change of the ArkCompiler compiler, application compilation failures and runtime crashes may occur.<br>
- Non-type compilation: converts ArkTS/TS source code into JS source code, and uses the ArkCompiler compiler es2abc to generate bytecode.
**Key API/Component Changes**<br>
type compileMode uses arkcompiler frontend compiler es2abc by default<br>
- Type compilation: converts ArkTS/TS source code into TS source code, and uses the ArkCompiler compiler ts2abc (in earlier versions)/es2abc (enabled in this version) to generate bytecode.
You can check the hvigor version of the application project in the following fields:
**hvigorVersion** field and **@ohos/hvigor-ohos-plugin** field under **dependencies** in the **hvigor-config.json5** file in the **hvigor** directory of the application project
Enable type compilation:
If the hvigor version is 2.6.0-rc.9.s or later, the type compilation mode is enabled by default. You can also manually enable this mode by setting **aotCompileMode** to **type** under the **buildOption** tag in the **build-profile.json5** file at the same level directory as the application source code (**src** directory).
When type compilation is enabled and the SDK of this version is used, the ArkCompiler compiler es2abc is used by default. The earlier version SDK with ts2abc enabled is not recommended for type compilation.
**Change Impact**
In DevEco Studio, when the type compilation mode is enabled and the SDK of this version is used, the change in the compilation mode and ArkCompiler compiler may result in application compilation failures and runtime crashes.
**Key API/Component Changes**
In type compilation mode, the ArkCompiler compiler es2abc is used by default.
**Adaptation Guide**
1. When the hvigor version is greater than or equal to 2.6.0-rc.9.s, the developer needs to configure "aotCompileMode": "" in the build-profile.json5 file to switch to the original compilation mode (not type).
If the hvigor version is 2.6.0-rc.9.s or later, to switch to the original compilation mode (non-type), you need to set **aotCompileMode** in the **build-profile.json5** file.
\ No newline at end of file
......@@ -21,22 +21,24 @@ ArkTS卡片开放了使用动画效果的能力,支持[显式动画](../refere
```ts
@Entry
@Component
struct AttrAnimationExample {
struct AnimationCard {
@State rotateAngle: number = 0;
build() {
Column() {
Row() {
Button('change rotate angle')
.height('20%')
.width('90%')
.margin('5%')
.onClick(() => {
this.rotateAngle = 90;
this.rotateAngle = (this.rotateAngle === 0 ? 90 : 0);
})
.margin(50)
.rotate({ angle: this.rotateAngle })
.animation({
curve: Curve.EaseOut,
playMode: PlayMode.AlternateReverse
playMode: PlayMode.Normal,
})
}.width('100%').margin({ top: 20 })
}.height('100%').alignItems(VerticalAlign.Center)
}
}
```
......@@ -6,7 +6,7 @@ ArkTS卡片开放了自定义绘制的能力,在卡片上可以通过[Canvas](
```ts
@Entry
@Component
struct WidgetCard {
struct CanvasCard {
private canvasWidth: number = 0;
private canvasHeight: number = 0;
// 初始化CanvasRenderingContext2D和RenderingContextSettings
......
......@@ -58,6 +58,10 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上
## 相关实例
此文档中示例代码均有完整示例工程对应,具体对应关系如下:
- [ArkTS卡片开发指导 - 开发卡片页面](https://gitee.com/openharmony/applications_app_samples/tree/master/code/DocsSample/Form/ArkTSCardDocsSample)
针对Stage模型卡片提供方的开发,有以下相关实例可供参考:
- [ArkTS音乐卡片(ArkTS)(Full SDK)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/MusicControl)
......@@ -69,3 +73,4 @@ ArkTS卡片与JS卡片具备不同的实现原理及特征,在场景能力上
- [ArkTS卡片Canvas小游戏(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/CanvasGame)
- [ArkTS卡片计算器(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/code/SuperFeature/Widget/ArkTSCard/Calculator)
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册