During application running, some unexpected behaviors are inevitable. For example, unprocessed exceptions and errors are thrown, and the call or running constraints of the framework are violated.
During application running, some unexpected behaviors are inevitable. For example, unprocessed exceptions and errors are thrown, and the call or running constraints of the recovery framework are violated.
By default, the processes will exit as exception handling. However, if user data is generated during application use, process exits may interrupt user operations and cause data loss.
In this way, application recovery APIs may help you save temporary data, restart an application after it exits, and restore its status and data, which deliver a better user experience.
Process exit is treated as the default exception handling method. However, if user data is generated during application use, process exit may interrupt user operations and cause data loss.
Application recovery helps to restore the application state and save temporary data upon next startup in the case of an abnormal process exit, thus providing more consistent user experience. The application state includes two parts, namely, the page stack of the and the data saved in **onSaveState**.
Currently, the APIs support only the development of an application that adopts the stage model, single process, and single ability.
In API version 9, application recovery is supported only for a single ability of the application developed using the stage model. Application state saving and automatic restart are performed when a JsError occurs.
In API version 10, application recovery is also supported for multiple abilities of the application developed using the stage model. Application state storage and restore are performed when an AppFreeze occurs. If an application is killed in control mode, the application state will be restored upon next startup.
## Available APIs
The application recovery APIs are provided by the **appRecovery** module, which can be imported via **import**. For details, please refer to [Development Example](#development-example). This document describes behaviors of APIs in API version 9, and the content will update with changes.
The application recovery APIs are provided by the **appRecovery** module, which can be imported via **import**. For details, see [Development Example](#development-example).
| saveAppState(): boolean; | Saves the ability status of an application. |
| restartApp(): void; | Restarts the current process. If there is saved ability status, it will be passed to the **want** parameter's **wantParam** attribute of the **onCreate** lifecycle callback of the ability.|
| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void;<sup>9+</sup> | Enables application recovery. After this API is called, the first ability that is displayed when the application is started from the initiator can be restored.|
| saveAppState(): boolean;<sup>9+</sup> | Saves the state of the ability that supports recovery in the current application.|
| restartApp(): void;<sup>9+</sup> | Restarts the current process and starts the ability specified by **setRestartWant**. If no ability is specified, a foreground ability that supports recovery is restarted.|
| saveAppState(context?: UIAbilityContext): boolean;<sup>10+</sup> | Saves the ability state specified by **Context**.|
| setRestartWant(want: Want): void;<sup>10+</sup> | Sets the abilities to restart when **restartApp** is actively called and **RestartFlag** is not **NO_RESTART**. The abilities must be under the same bundle name and must be a **UiAbility**.|
No error will be thrown if the preceding APIs are used in the troubleshooting scenario. The following are some notes on API usage:
**enableAppRecovery**: This API should be called during application initialization. For example, you can call this API in **onCreate** of **AbilityStage**. For details, see [Parameter Description](../reference/apis/js-apis-app-ability-appRecovery.md).
**saveAppState**: After this API is called, the recovery framework invokes **onSaveState** for all abilities that support recovery in the current process. If you choose to save data in **onSaveState**, the related data and ability page stack are persistently stored in the local cache of the application. To save data of the specified ability, you need to specify the context corresponding to that ability.
**setRestartWant**: This API specifies the ability to be restarted by **appRecovery**.
**restartApp**: After this API is called, the recovery framework kills the current process and restarts the ability specified by **setRestartWant**, with **APP_RECOVERY** set as the startup cause. In API version 9 and scenarios where an ability is not specified by **setRestartWant**, the last foreground ability that supports recovery is started. If the no foreground ability supports recovery, the application crashes. If a saved state is available for the restarted ability, the saved state is passed as the **wantParam** attribute in the **want** parameter of the ability's **onCreate** callback.
### Application State Management
Since API version 10, application recovery is not limited to automatic restart in the case of an exception. Therefore, you need to understand when the application will load the saved state.
If the last exit of an application is not initiated by a user and a saved state is available for recovery, the startup reason is set to **APP_RECOVERY** when the application is started by the user next time, and the recovery state of the application is cleared.
The application recovery status flag is set when **saveAppState** is actively or passively called. The flag is cleared when the application exits normally or the saved state is consumed. (A normal exit is usually triggered by pressing the back key or clearing recent tasks.)
The APIs are used for troubleshooting and do not return any exception. Therefore, you need to be familiar with when they are used.
![Application recovery status management](./figures/application_recovery_status_management.png)
**enableAppRecovery**: This API should be called during application initialization. For example, you can call this API in **onCreate** of **AbilityStage**. For details, please refer to the [parameter description](../reference/apis/js-apis-app-ability-appRecovery.md).
### Application State Saving and Restore
**saveAppState**: After this API is called, the framework calls back **onSaveState** of the ability. If data saving is agreed to in this method, relevant data and the page stack of the ability are persisted to the local cache of the application.
API version 10 or later supports saving of the application state when an application is suspended. If a JsError occurs, **onSaveState** is called in the main thread. If an AppFreeze occurs, however, the main thread may be suspended, and therefore **onSaveState** is called in a non-main thread. The following figure shows the main service flow.
**restartApp**: After this API is called, the framework kills the current application process and restarts the ability in the foreground, with **APP_RECOVERY** specified as the startup cause.
![Application recovery from the freezing state](./figures/application_recovery_from_freezing.png)
### Framework Fault Management Process
When the application is suspended, the callback is not executed in the JS thread. Therefore, you are advised not to use the imported dynamic Native library or access the **thread_local** object created by the main thread in the code of the **onSaveState** callback.
### Framework Fault Management
Fault management is an important way for applications to deliver a better user experience. The application framework offers three methods for application fault management: fault listening, fault rectification, and fault query.
- Fault listening refers to the process of registering [ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver) via [errorManager](../reference/apis/js-apis-application-errorManager.md), listening for fault occurrence, and notifying the fault listener.
- Fault listening refers to the process of registering an [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) via [errorManager](../reference/apis/js-apis-app-ability-errorManager.md), listening for faults, and notifying the listener of the faults.
- Fault rectification refers to the process of restoring the application state and data through [appRecovery](../reference/apis/js-apis-app-ability-appRecovery.md).
- Fault rectification refers to [appRecovery](../reference/apis/js-apis-app-ability-appRecovery.md) and restarts an application to restore its status previous to a fault.
- Fault query is the process of calling APIs of [faultLogger](../reference/apis/js-apis-faultLogger.md) to obtain the fault information.
- Fault query indicates that [faultLogger](../reference/apis/js-apis-faultLogger.md) obtains the fault information using its query API.
The figure below does not illustrate the time when [faultLogger](../reference/apis/js-apis-faultLogger.md) is called. You can refer to the [LastExitReason](../reference/apis/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis/js-apis-faultLogger.md) to query information about the previous fault.
The figure below does not illustrate the time when [faultLogger](../reference/apis/js-apis-faultLogger.md) is called. You can refer to [LastExitReason](../reference/apis/js-apis-app-ability-abilityConstant.md#abilityconstantlastexitreason) passed during application initialization to determine whether to call [faultLogger](../reference/apis/js-apis-faultLogger.md) to query the information about the last fault.
It is recommended that you call [errorManager](../reference/apis/js-apis-application-errorManager.md) to process the exception. After the processing is complete, you can call the status saving API and restart the application.
If you do not register [ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver) or enable application recovery, the application process will exit according to the default processing logic of the system. Users can restart the application from the home screen.
If you have enabled application recovery, the framework first checks whether a fault allows for ability status saving and whether you have configured ability status saving. If so, [onSaveState](../reference/apis/js-apis-application-ability.md#abilityonsavestate) of [Ability](../reference/apis/js-apis-application-ability.md#ability) is called back. Finally, the application is restarted.
It is recommended that you call [errorManager](../reference/apis/js-apis-app-ability-errorManager.md) to handle the exception. After the processing is complete, you can call the **saveAppState** API and restart the application.
If you do not register [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) or enable application recovery, the application process will exit according to the default processing logic of the system. Users can restart the application from the home screen.
If you have enabled application recovery, the recovery framework first checks whether application state saving is supported and whether the application state saving is enabled. If so, the recovery framework invokes [onSaveState](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of the [Ability](../reference/apis/js-apis-app-ability-uiAbility.md). Finally, the application is restarted.
### Scenarios Supported by Application Fault Management APIs
### Supported Application Recovery Scenarios
Common fault types include JavaScript application crash, application freezing, and C++ application crash. Generally, an application is closed when a crash occurs. Application freezing occurs when the application does not respond. The fault type can be ignored for the upper layer of an application. The recovery framework implements fault management in different scenarios based on the fault type.
| [APP_FREEZE](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported|Supported|Supported|Supported|
| [CPP_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported|Not supported|Not supported|Supported|
**Status Saving** in the table header means status saving when a fault occurs. To protect user data as much as possible in the application freezing fault, you can adopt either the periodic or automatic way, and the latter will save user data when an ability is switched to the background.
**State Saving** in the table header means saving of the application state when a fault occurs. To protect user data as much as possible when an AppFreeze occurs, you can adopt either the periodic or automatic way, and the latter will save user data when an ability is switched to the background.
### Enabling Application Recovery for the Specified Abilities
Generally, the ability configuration list is named **module.json5**.
```json
{
"abilities":[
{
"name":"EntryAbility",
"recoverable":true,
}]
}
```
### Saving and Restoring Data
After enabling **appRecovery**, you can use this function by either actively or passively saving the status and restoring data in the ability.
After enabling **appRecovery**, you can use this function by either actively or passively saving the application state and restoring data in the ability.
The following is an example of **EntryAbility**:
#### Importing the Service Package
...
...
@@ -93,9 +130,9 @@ import appRecovery from '@ohos.app.ability.appRecovery';
@@ -125,7 +162,7 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state,
```ts
onSaveState(state,wantParams){
// Save application data.
// Ability has called to save app data
console.log("[Demo] EntryAbility onSaveState")
wantParams["myData"]="my1234567";
returnAbilityConstant.onSaveResult.ALL_AGREE;
...
...
@@ -134,7 +171,7 @@ After the callback triggers **appRecovery.saveAppState()**, **onSaveState(state,
- Restore data.
After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onCreate(want, launchParam)** of **EntryAbility** is called, and the saved data is in **parameters** of **want**.
After the callback triggers **appRecovery.restartApp()**, the application is restarted. After the restart, **onCreate(want, launchParam)** of **EntryAbility** is called, and the saved data is stored in **parameters** of **want**.
#### Passively Saving the Application State and Restoring Data
This is triggered by the recovery framework. You do not need to register **ErrorObserver callback**. You only need to implement **onSaveState** of the ability for status saving and **onCreate** of the ability for data restoration.
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.
Initiates a call. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [dialCall](#calldialcall9). The substitute API is available only for system applications.
Initiates a call. You can set call options as needed. This API uses an asynchronous callback to return the result.
> **NOTE**
>
> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [dialCall](#calldialcall9). The substitute API is available only for system applications.
Initiates a call. You can set call options as needed. This API uses a promise to return the result.
> **NOTE**
>
> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [dialCall](#calldialcall9). The substitute API is available only for system applications.
| type | string | Yes | This interface is used to monitor the change of call events during a call. The parameter has a fixed value of callEventChange.|
| type | string | Yes | Call event change. This field has a fixed value of **callEventChange**.|
| callback | Callback<[CallEventOptions](#calleventoptions8)> | Yes | Callback used to return the result. |
**Error codes**
...
...
@@ -2467,7 +2464,7 @@ Subscribes to **callDisconnectedCause** events. This API uses an asynchronous ca
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hichecker.containsCheckRule](#hicheckercontainscheckrule9) instead.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hichecker.containsCheckRule](#hicheckercontainscheckrule9).
Checks whether the specified rule exists in the collection of added rules. If the rule is of the thread level, this operation is performed only on the current thread.
The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
> **NOTE**<br>
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
This module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
## Modules to Import
...
...
@@ -19,31 +19,25 @@ getNativeHeapSize(): bigint
Obtains the total heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
@@ -100,7 +90,6 @@ Obtains the size of the physical memory actually used by the application process
letpss=hidebug.getPss();
```
## hidebug.getSharedDirty
getSharedDirty(): bigint
...
...
@@ -135,7 +124,6 @@ Obtains the size of the private dirty memory of a process.
| ------ | -------------------------- |
| bigint | Size of the private dirty memory of the process, in KB.|
**Example**
```js
letprivateDirty=hidebug.getPrivateDirty();
...
...
@@ -163,76 +151,6 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
letcpuUsage=hidebug.getCpuUsage();
```
## hidebug.startProfiling<sup>(deprecated)</sup>
startProfiling(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead.
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead.
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead.
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead.
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
>**NOTE**
>
...
...
@@ -13,10 +13,10 @@ This module provides the HTTP data request capability. An application can initia
importhttpfrom'@ohos.net.http';
```
## Example
## Examples
```js
// Import the http namespace.
// Import the HTTP namespace.
importhttpfrom'@ohos.net.http';
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
@@ -513,7 +513,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see:
**Example**
...
...
@@ -526,8 +526,8 @@ let promise = httpRequest.request("EXAMPLE_URL", {
@@ -13,7 +13,7 @@ The Resource Manager module provides APIs to obtain information about applicatio
importresourceManagerfrom'@ohos.resourceManager';
```
## How to Use
## Instruction
Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. For the FA model, you need to import the required bundle and then call the [getResourceManager](#resourcemanagergetresourcemanager) API to obtain a **ResourceManager** object.
For details about how to reference context in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md).
...
...
@@ -78,7 +78,7 @@ Obtains the **ResourceManager** object of an application based on the specified
| bundleName | string | Yes | Bundle name of the target application. |
| bundleName | string | Yes | Bundle name of the application. |
| callback | AsyncCallback<[ResourceManager](#resourcemanager)> | Yes | Callback used to return the result.|
**Example**
...
...
@@ -118,7 +118,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom
console.log("error is "+error);
});
```
> **NOTE**<br>> In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file.
> **NOTE**<br>In the sample code, **0x1000000** indicates the resource ID, which can be found in the compiled **ResourceTable.txt** file.
## resourceManager.getResourceManager
...
...
@@ -135,7 +135,7 @@ Obtains the **ResourceManager** object of an application based on the specified
| Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | ------------- |
| bundleName | string | Yes | Bundle name of the target application.|
| bundleName | string | Yes | Bundle name of the application.|
**Return value**
...
...
@@ -171,12 +171,12 @@ Enumerates the device types.
| Name | Value | Description |
| -------------------- | ---- | ---- |
| DEVICE_TYPE_PHONE | 0x00 | Phone. |
| DEVICE_TYPE_TABLET | 0x01 | Tablet. |
| DEVICE_TYPE_CAR | 0x02 | Head unit. |
| DEVICE_TYPE_PC | 0x03 | PC. |
| DEVICE_TYPE_TV | 0x04 | TV. |
| DEVICE_TYPE_WEARABLE | 0x06 | Wearable. |
| DEVICE_TYPE_PHONE | 0x00 | Phone |
| DEVICE_TYPE_TABLET | 0x01 | Tablet |
| DEVICE_TYPE_CAR | 0x02 | Head unit |
| DEVICE_TYPE_PC | 0x03 | PC |
| DEVICE_TYPE_TV | 0x04 | TV |
| DEVICE_TYPE_WEARABLE | 0x06 | Wearable |
## ScreenDensity
...
...
@@ -278,7 +278,7 @@ Defines the capability of accessing application resources.
> **NOTE**
>
> - The methods involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm.
> - The APIs involved in **ResourceManager** are applicable only to the TypeScript-based declarative development paradigm.
>
> - Resource files are defined in the **resources** directory of the project. You can obtain the resource ID using **$r(resource address).id**, for example, **$r('app.string.test').id**.
...
...
@@ -645,7 +645,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('message',callback);
udp.off('message');
```
...
...
@@ -582,14 +582,14 @@ let callback1 = () =>{
console.log("on listening, success");
}
udp.on('listening',callback1);
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
udp.off('listening',callback1);
udp.off('listening');
letcallback2=()=>{
console.log("on close, success");
}
udp.on('close',callback2);
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('message',callback);
tcp.off('message');
```
...
...
@@ -1486,14 +1486,14 @@ let callback1 = () =>{
console.log("on connect success");
}
tcp.on('connect',callback1);
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('connect',callback1);
tcp.off('connect');
letcallback2=()=>{
console.log("on close success");
}
tcp.on('close',callback2);
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks.
// You can pass the callback of the on method to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks.
tcp.off('error',callback);
tcp.off('error');
```
...
...
@@ -2674,4 +2674,4 @@ Defines the certificate raw data.
USB devices are classified into two types: USB host and USB device. On OpenHarmony, you can use the port service to switch between the host mode and device mode. In host mode, you can obtain the list of connected USB devices, manage device access permissions, and perform bulk transfer or control transfer between the host and connected devices. In device mode, you can switch between functions including HDC (debugging), ACM (serial port), and ECM (Ethernet port).
### Basic Concepts
- USB service
An abstraction of underlying hardware-based USB devices. Your application can access the USB devices via the USB service. With the APIs provided by the USB service, you can obtain the list of connected USB devices, manage device access permissions, and perform data transfer or control transfer between the host and connected devices.
- USB API
A collection of JS APIs provided for the upper layer through NAPI. Your application can use USB APIs to implement various basic functions, for example, query of the USB device list, USB device plug notification, USB host and device mode switching, bulk transfer, control transfer, right management, and function switching in device mode.
- USB Service layer
A layer implemented by using the C++ programming language. It consists of four modules: Host, Device, Port, and Right. HDI-based APIs provided by USB Service are mainly used to implement management of USB device list, USB functions, USB ports, and USB device access permissions. The USB Service layer interacts with the HAL layer to receive, parse, and distribute data, manages foreground and background policies, and performs USB device management and right control.
- USB HAL layer
A layer implemented by using the C programming language. Based on the Host Driver Development Kit (SDK) and Device DDK, USB HAL encapsulates basic USB device operations, provides C++ APIs for the upper layer, and receives information from the kernel through the Hardware Driver Foundation (HDF) framework.
### Working Principles
The USB subsystem logically consists of three parts: USB API, USB Service, and USB HAL. The following figure shows how the USB service is implemented.
**Figure 1** USB service architecture
![USB service architecture](figures/en-us_image_0000001267088285.png)
- USB API: provides USB APIs that implement various basic functions, for example, query of the USB device list, bulk data transfer, control transfer, and right management.
- USB Service: receives, parses, and distributes Hardware Abstraction Layer (HAL) data, manages and controls foreground and background policies, and manages devices.
- USB HAL: provides driver capability APIs that can be directly called in user mode.
## Usage Guidelines
### When to Use
In Host mode, you can obtain the list of connected devices, enable or disable the devices, manage device access permissions, and perform data transfer or control transfer.
| int32_t OpenDevice(const UsbDevice &device, USBDevicePipe &pip); | Opens a USB device to set up a connection. |
| bool HasRight(std::string deviceName); | Checks whether the application has the permission to access the device. |
| int32_t RequestRight(std::string deviceName); | Requests the temporary permission for a given application to access the USB device. |
| int32_t GetDevices(std::vector &deviceList); | Obtains the USB device list. |
| int32_t ClaimInterface(USBDevicePipe &pip, const UsbInterface &interface, bool force); | Claims a USB interface exclusively. This must be done before data transfer. |
| int32_t ReleaseInterface(USBDevicePipe &pip, const UsbInterface &interface); | Releases a USB interface. This is usually done after data transfer. |
| int32_t BulkTransfer(USBDevicePipe &pip, const USBEndpoint &endpoint, std::vector &vdata, int32_t timeout); | Performs a bulk transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction.|
| int32_t ControlTransfer(USBDevicePipe &pip, const UsbCtrlTransfer &ctrl, std::vector &vdata); | Performs control transfer for endpoint 0 of the device. The data transfer direction is determined by the request type. |
| int32_t SetConfiguration(USBDevicePipe &pip, const USBConfig &config); | Sets the current configuration of the USB device. |
| int32_t SetInterface(USBDevicePipe &pipe, const UsbInterface &interface); | Sets the alternate settings for the specified USB interface. This allows you to switch between two interfaces with the same ID but different alternate settings.|
| int32_t GetRawDescriptors(std::vector &vdata); | Obtains the raw USB descriptor. |
| int32_t GetFileDescriptor(); | Obtains the file descriptor. |
| bool Close(const USBDevicePipe &pip); | Closes a USB device to release all system resources related to the device. |
| int32_t PipeRequestWait(USBDevicePipe &pip, int64_t timeout, UsbRequest &req); | Obtains the isochronous transfer result. |
| int32_t RequestInitialize(UsbRequest &request); | Initializes the isochronous transfer request. |
| int32_t RequestFree(UsbRequest &request); | Frees the isochronous transfer request. |
| int32_t RequestAbort(UsbRequest &request); | Cancels the data transfer request to be processed. |
| int32_t RequestQueue(UsbRequest &request); | Sends or receives requests for isochronous transfer on a specified endpoint. The data transfer direction is determined by the endpoint direction.|
| int32_t RegBulkCallback(USBDevicePipe &pip, const USBEndpoint &endpoint, const sptr<IRemoteObject>&cb); | Registers an asynchronous callback for bulk transfer. |
| int32_t UnRegBulkCallback(USBDevicePipe &pip, const USBEndpoint &endpoint); | Unregisters the asynchronous callback for bulk transfer. |
| int32_t BulkRead(USBDevicePipe &pip, const USBEndpoint &endpoint, sptr<Ashmem>&ashmem); | Reads data asynchronously during bulk transfer. |
| int32_t BulkWrite(USBDevicePipe &pip, const USBEndpoint &endpoint, sptr<Ashmem>&ashmem); | Writes data asynchronously during bulk transfer. |
| int32_t BulkCancel(USBDevicePipe &pip, const USBEndpoint &endpoint); | Cancels bulk transfer. The asynchronous read and write operations on the current USB interface will be cancelled. |
| int32_t GetSupportedModes(int32_t portId, int32_t &supportedModes); | Obtains the mask combination for the supported mode list of a given port. |
| int32_t SetPortRole(int32_t portId, int32_t powerRole, int32_t dataRole); | Sets the role types supported by a specified port, which can be **powerRole** (for charging) and **dataRole** (for data transfer).|
| int32_t GetPorts(std::vector &usbPorts); | Obtains the USB port descriptor list. |
### How to Use
The following uses bulk transfer as an example to illustrate the development procedure.
int32_t ret = g_usbClient.RequestRight(device.GetName());
```
4. Open a camera device.
```cpp
USBDevicePipe pip;
int32_t et = g_usbClient.OpenDevice(device, pip);
```
5. Configure the USB interface.
```cpp
// interface indicates an interface of the USB device in deviceList.
ret = g_usbClient.ClaimInterface(pip, interface, true);
```
6. Perform data transfer.
```cpp
// pipe indicates the pipe for data transfer after the USB device is opened. endpoint indicates the endpoint for data transfer on the USB device. vdata indicates the binary data block to be transferred or read. timeout indicates the timeout duration of data transfer.