提交 72b8ac9f 编写于 作者: S shawn_he

update doc

Signed-off-by: Nshawn_he <shawn.he@huawei.com>
上级 fb702abd
# Development of Application Recovery
# Application Recovery Development
## When to Use
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).
### Available APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| enableAppRecovery(restart?: RestartFlag, saveOccasion?: SaveOccasionFlag, saveMode?: SaveModeFlag) : void; | Enables the application recovery function. |
| 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.|
| API | Description |
| ------------------------------------------------------------ | ---------------------------------------------------- |
| 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.
![Fault rectification process](./figures/fault_rectification.png)
It is recommended that you call [errorManager](../reference/apis/js-apis-application-errorManager.md) to process the exception. After the processing is complete, you can call the status saving API and restart the application.
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.
| Fault | Fault Listening| Status Saving| Automatic Restart| Log Query|
| ------------------------------------------------------------ | -------- | -------- | -------- | -------- |
| [JS_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Supported | Supported | Supported | Supported |
| [APP_FREEZE](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported | Not supported | Supported | Supported |
| [CPP_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Not supported | Not supported | Not supported | Supported |
| Fault | Fault Listening | State Saving| Automatic Restart| Log Query|
| ----------|--------- |--------- |--------- |--------- |
| [JS_CRASH](../reference/apis/js-apis-faultLogger.md#faulttype) | Supported|Supported|Supported|Supported|
| [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.
......@@ -78,11 +103,23 @@ export default class MyAbilityStage extends AbilityStage {
appRecovery.SaveModeFlag.SAVE_WITH_FILE);
}
}
```
### 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';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
```
#### Actively Saving Status and Restoring Data
#### Actively Saving the Application State and Restoring Data
- Define and register the [ErrorObserver](../reference/apis/js-apis-application-errorManager.md#errorobserver) callback.
- Define and register the [ErrorObserver](../reference/apis/js-apis-inner-application-errorObserver.md) callback.
```ts
var registerId = -1;
......@@ -108,7 +145,7 @@ import AbilityConstant from '@ohos.app.ability.AbilityConstant';
}
onWindowStageCreate(windowStage) {
// Main window is created. Set a main page for this ability.
// Main window is created, set main page for this ability
console.log("[Demo] EntryAbility onWindowStageCreate")
globalThis.registerObserver = (() => {
......@@ -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";
return AbilityConstant.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**.
```ts
storage: LocalStorage
......@@ -150,11 +187,11 @@ onCreate(want, launchParam) {
}
```
- Deregister **ErrorObserver callback**.
- Unregister the **ErrorObserver** callback.
```ts
onWindowStageDestroy() {
// Main window is destroyed to release UI resources.
// Main window is destroyed, release UI related resources
console.log("[Demo] EntryAbility onWindowStageDestroy")
globalThis.unRegisterObserver = (() => {
......@@ -165,9 +202,9 @@ onWindowStageDestroy() {
}
```
#### Passively Saving Status and Restoring Data
#### 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.
```ts
export default class EntryAbility extends Ability {
......@@ -184,7 +221,7 @@ export default class EntryAbility extends Ability {
}
onSaveState(state, wantParams) {
// Save application data.
// Ability has called to save app data
console.log("[Demo] EntryAbility onSaveState")
wantParams["myData"] = "my1234567";
return AbilityConstant.onSaveResult.ALL_AGREE;
......
......@@ -14,110 +14,6 @@ To subscribe to the call status, use [`observer.on('callStateChange')`](js-apis-
import call from '@ohos.telephony.call';
```
## call.dial<sup>(deprecated)</sup>
dial\(phoneNumber: string, callback: AsyncCallback<boolean\>\): void
Initiates a call. This API uses an asynchronous callback to return the result.
>**NOTE**
>
>This parameter is supported since API version 6 and deprecated since API version 9. You are advised to use [dialCall](#calldialcall9).
**Required Permissions**: ohos.permission.PLACE_CALL
**System capability**: SystemCapability.Telephony.CallManager
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ---------------------------- | ---- | --------------------------------------- |
| phoneNumber | string | Yes | Phone number. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.<br>- **true**: success<br>- **false**: failure|
**Example**
```js
call.dial("138xxxxxxxx", (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## call.dial<sup>(deprecated)</sup>
dial\(phoneNumber: string, options: DialOptions, callback: AsyncCallback<boolean\>\): void
Initiates a call. You can set call options as needed. This API uses an asynchronous callback to return the result.
>**NOTE**
>
>This parameter is supported since API version 6 and deprecated since API version 9. You are advised to use [dialCall](#calldialcall9).
**Required Permissions**: ohos.permission.PLACE_CALL
**System capability**: SystemCapability.Telephony.CallManager
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ---------------------------- | ---- | --------------------------------------- |
| phoneNumber | string | Yes | Phone number. |
| options | [DialOptions](#dialoptions) | Yes | Call option, which indicates whether the call is a voice call or video call. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.<br>- **true**: success<br>- **false**: failure|
**Example**
```js
call.dial("138xxxxxxxx", {
extras: false
}, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## call.dial<sup>(deprecated)</sup>
dial\(phoneNumber: string, options?: DialOptions\): Promise<boolean\>
Initiates a call. You can set call options as needed. This API uses a promise to return the result.
>**NOTE**
>
>This parameter is supported since API version 6 and deprecated since API version 9. You are advised to use [dialCall](#calldialcall9).
**Required Permissions**: ohos.permission.PLACE_CALL
**System capability**: SystemCapability.Telephony.CallManager
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | --------------------------- | ---- | -------------------------------------- |
| phoneNumber | string | Yes | Phone number. |
| options | [DialOptions](#dialoptions) | No | Call option, which indicates whether the call is a voice call or video call.|
**Return value**
| Type | Description |
| ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result.<br>- **true**: success<br>- **false**: failure|
**Example**
```js
let promise = call.dial("138xxxxxxxx", {
extras: false
});
promise.then(data => {
console.log(`dial success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
console.error(`dial fail, promise: err->${JSON.stringify(err)}`);
});
```
## call.dialCall<sup>9+</sup>
dialCall\(phoneNumber: string, callback: AsyncCallback<void\>\): void
......@@ -260,6 +156,107 @@ promise.then(() => {
});
```
## call.dial<sup>(deprecated)</sup>
dial\(phoneNumber: string, callback: AsyncCallback<boolean\>\): void
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.
**Required Permissions**: ohos.permission.PLACE_CALL
**System capability**: SystemCapability.Telephony.CallManager
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ---------------------------- | ---- | --------------------------------------- |
| phoneNumber | string | Yes | Phone number. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.<br>- **true**: success<br>- **false**: failure|
**Example**
```js
call.dial("138xxxxxxxx", (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## call.dial<sup>(deprecated)</sup>
dial\(phoneNumber: string, options: DialOptions, callback: AsyncCallback<boolean\>\): void
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.
**Required Permissions**: ohos.permission.PLACE_CALL
**System capability**: SystemCapability.Telephony.CallManager
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | ---------------------------- | ---- | --------------------------------------- |
| phoneNumber | string | Yes | Phone number. |
| options | [DialOptions](#dialoptions) | Yes | Call option, which indicates whether the call is a voice call or video call. |
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback used to return the result.<br>- **true**: success<br>- **false**: failure|
**Example**
```js
call.dial("138xxxxxxxx", {
extras: false
}, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
});
```
## call.dial<sup>(deprecated)</sup>
dial\(phoneNumber: string, options?: DialOptions\): Promise<boolean\>
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.
**Required Permissions**: ohos.permission.PLACE_CALL
**System capability**: SystemCapability.Telephony.CallManager
**Parameters**
| Name | Type | Mandatory| Description |
| ----------- | --------------------------- | ---- | -------------------------------------- |
| phoneNumber | string | Yes | Phone number. |
| options | [DialOptions](#dialoptions) | No | Call option, which indicates whether the call is a voice call or video call.|
**Return value**
| Type | Description |
| ---------------------- | ------------------------------------------------------------ |
| Promise&lt;boolean&gt; | Promise used to return the result.<br>- **true**: success<br>- **false**: failure|
**Example**
```js
let promise = call.dial("138xxxxxxxx", {
extras: false
});
promise.then(data => {
console.log(`dial success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
console.error(`dial fail, promise: err->${JSON.stringify(err)}`);
});
```
## call.makeCall<sup>7+</sup>
......@@ -2387,7 +2384,7 @@ Subscribes to **callDetailsChange** events. This API uses an asynchronous callba
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------- | ---- | -------------------------- |
| type | string | Yes | Event type. This field has a fixed value of **callDetailsChange**.|
| type | string | Yes | Call event change. This field has a fixed value of **callDetailsChange**.|
| callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | Yes | Callback used to return the result. |
**Error codes**
......@@ -2427,7 +2424,7 @@ Subscribes to **callEventChange** events. This API uses an asynchronous callback
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | -------------------------- |
| 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
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------ | ---- | -------------------------- |
| type | string | Yes | Event type. The field has a fixed value of **callDisconnectedCause**.|
| type | string | Yes | Call disconnection cause. This field has a fixed value of **callDisconnectedCause**.|
| callback | Callback<[DisconnectedDetails](#disconnecteddetails9)> | Yes | Callback used to return the result. |
**Error codes**
......@@ -2507,7 +2504,7 @@ Subscribes to **mmiCodeResult** events. This API uses an asynchronous callback t
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | --------------------- |
| type | string | Yes | Event type. The field has a fixed value of **mmiCodeResult**.|
| type | string | Yes | MMI code result. This field has a fixed value of **mmiCodeResult**.|
| callback | Callback<[MmiCodeResults](#mmicoderesults9)> | Yes | Callback used to return the result. |
**Error codes**
......@@ -2547,7 +2544,7 @@ Unsubscribes from **callDetailsChange** events. This API uses an asynchronous ca
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------------------------- | ---- | ---------------------------------- |
| type | string | Yes | Event type. The field has a fixed value of **callDetailsChange**.|
| type | string | Yes | Call details change. This field has a fixed value of **callDetailsChange**.|
| callback | Callback<[CallAttributeOptions](#callattributeoptions7)> | No | Callback used to return the result. |
**Error codes**
......@@ -2587,7 +2584,7 @@ Unsubscribes from **callEventChange** events. This API uses an asynchronous call
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ---------------------------------- |
| type | string | Yes | Event type. The field has a fixed value of **callEventChange**.|
| type | string | Yes | Call event change. This field has a fixed value of **callEventChange**.|
| callback | Callback<[CallEventOptions](#calleventoptions8)> | No | Callback used to return the result. |
**Error codes**
......@@ -2627,7 +2624,7 @@ Unsubscribes from **callDisconnectedCause** events. This API uses an asynchronou
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------------------- | ---- | ------------------- |
| type | string | Yes | Event type. The field has a fixed value of **callDisconnectedCause**.|
| type | string | Yes | Call disconnection cause. This field has a fixed value of **callDisconnectedCause**.|
| callback | Callback<[DisconnectedDetails](#disconnecteddetails9)> | No | Callback used to return the result. |
**Error codes**
......@@ -2667,7 +2664,7 @@ Unsubscribes from **mmiCodeResult** events. This API uses an asynchronous callba
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------ | ---- | ----------- |
| type | string | Yes | Event type. The field has a fixed value of **mmiCodeResult**.|
| type | string | Yes | MMI code result. This field has a fixed value of **mmiCodeResult**.|
| callback | Callback<[MmiCodeResults](#mmicoderesults9)> | No | Callback used to return the result. |
**Error codes**
......
......@@ -122,7 +122,9 @@ try {
addRule(rule: bigint): void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hichecker.addCheckRule](#hicheckeraddcheckrule9) instead.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hichecker.addCheckRule](#hicheckeraddcheckrule9).
Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules.
......@@ -149,7 +151,9 @@ hichecker.addRule(
removeRule(rule: bigint): void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hichecker.removeCheckRule](#hicheckerremovecheckrule9) instead.
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hichecker.removeCheckRule](#hicheckerremovecheckrule9).
Removes one or more rules. The removed rules will become ineffective.
......@@ -200,7 +204,9 @@ hichecker.getRule(); // return 1n;
contains(rule: bigint): boolean
> **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.
......
# @ohos.hidebug (HiDebug)
# @ohos.hidebug (Debug)
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.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
| Type | Description |
| Type | Description |
| ------ | --------------------------- |
| bigint | Total heap memory size of the application, in KB.|
**Example**
```js
let nativeHeapSize = hidebug.getNativeHeapSize();
```
## hidebug.getNativeHeapAllocatedSize
getNativeHeapAllocatedSize(): bigint
Obtains the allocated heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
......@@ -58,15 +52,12 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
let nativeHeapAllocatedSize = hidebug.getNativeHeapAllocatedSize();
```
## hidebug.getNativeHeapFreeSize
getNativeHeapFreeSize(): bigint
Obtains the free heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
......@@ -80,7 +71,6 @@ This API is defined but not implemented in OpenHarmony 3.1 Release.
let nativeHeapFreeSize = hidebug.getNativeHeapFreeSize();
```
## hidebug.getPss
getPss(): bigint
......@@ -100,7 +90,6 @@ Obtains the size of the physical memory actually used by the application process
let pss = 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
let privateDirty = hidebug.getPrivateDirty();
......@@ -163,76 +151,6 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
let cpuUsage = 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead.
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| 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`.|
**Example**
```js
hidebug.dumpHeapData("heap-20220216");
```
## hidebug.getServiceDump<sup>9+<sup>
getServiceDump(serviceid : number, fd : number, args : Array\<string>) : void
......@@ -360,3 +278,71 @@ try {
console.info(error.message)
}
```
## 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead.
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| 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`.|
**Example**
```js
hidebug.dumpHeapData("heap-20220216");
```
# @ohos.net.http (Data Request)
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
import http from '@ohos.net.http';
```
## Example
## Examples
```js
// Import the http namespace.
// Import the HTTP namespace.
import http from '@ohos.net.http';
// Each httpRequest corresponds to an HTTP request task and cannot be reused.
......@@ -27,7 +27,7 @@ httpRequest.on('headersReceive', (header) => {
console.info('header: ' + JSON.stringify(header));
});
httpRequest.request(
// Customize EXAMPLE_URL on your own. It is up to you whether to add parameters to the URL.
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
......@@ -112,7 +112,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Error codes**
| Code | Error Message |
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -164,7 +164,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
**Error codes**
| Code | Error Message |
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -231,7 +231,7 @@ httpRequest.request("EXAMPLE_URL",
request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
Initiates an HTTP request to a given URL. This API uses a promise to return the result.
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
......@@ -255,7 +255,7 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the
**Error codes**
| Code | Error Message |
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -332,7 +332,7 @@ httpRequest.destroy();
### request2<sup>10+</sup>
request2(url: string, callback: AsyncCallback\<void\>): void
request2(url: string, callback: AsyncCallback\<number\>): void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
......@@ -345,11 +345,11 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
| Name | Type | Mandatory| Description |
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. |
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<[number](#responsecode)\> | Yes | Callback used to return the result. |
**Error codes**
| Code | Error Message |
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -366,9 +366,9 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
**Example**
```js
httpRequest.request2("EXAMPLE_URL", (err) => {
httpRequest.request2("EXAMPLE_URL", (err, data) => {
if (!err) {
console.info("request2 OK!");
console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
}
......@@ -377,7 +377,7 @@ httpRequest.request2("EXAMPLE_URL", (err) => {
### request2<sup>10+</sup>
request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\<void\>): void
request2(url: string, options: HttpRequestOptions, callback: AsyncCallback\<number\>): void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result, which is a streaming response.
......@@ -391,11 +391,11 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
| -------- | ---------------------------------------------- | ---- | ----------------------------------------------- |
| url | string | Yes | URL for initiating an HTTP request. |
| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).|
| callback | AsyncCallback\<void\> | Yes | Callback used to return the result. |
| callback | AsyncCallback\<[number](#responsecode)\> | Yes | Callback used to return the result. |
**Error codes**
| Code | Error Message |
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -444,9 +444,9 @@ httpRequest.request2("EXAMPLE_URL",
},
readTimeout: 60000,
connectTimeout: 60000
}, (err) => {
}, (err, data) => {
if (!err) {
console.info("request2 OK!");
console.info("request2 OK! ResponseCode is " + JSON.stringify(data));
} else {
console.info("request2 ERROR : err = " + JSON.stringify(err));
}
......@@ -454,7 +454,7 @@ httpRequest.request2("EXAMPLE_URL",
```
### request2<sup>10+</sup>
request2(url: string, options? : HttpRequestOptions): Promise\<void\>
request2(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.
......@@ -473,11 +473,11 @@ Initiates an HTTP request containing specified options to a given URL. This API
| Type | Description |
| :------------------------------------- | :-------------------------------- |
| Promise\<void\> | Promise used to return the result.|
| Promise\<[number](#responsecode)\> | Promise used to return the result.|
**Error codes**
| Code | Error Message |
| ID | Error Message |
|---------|-------------------------------------------------------|
| 401 | Parameter error. |
| 201 | Permission denied. |
......@@ -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", {
'Content-Type': 'application/json'
}
});
promise.then(() => {
console.info("request2 OK!");
promise.then((data) => {
console.info("request2 OK!" + JSON.stringify(data));
}).catch((err) => {
console.info("request2 ERROR : err = " + JSON.stringify(err));
});
......@@ -839,7 +839,7 @@ Enumerates the response codes for an HTTP request.
| Name | Value | Description |
| ----------------- | ---- | ------------------------------------------------------------ |
| OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. |
| OK | 200 | "OK." The request has been processed successfully. This return code is generally used for GET and POST requests. |
| CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. |
| ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. |
| NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. |
......@@ -1007,7 +1007,7 @@ Disables the cache and deletes the data in it. This API uses a promise to return
| Type | Description |
| --------------------------------- | ------------------------------------- |
| Promise\<void\> | Promise used to return the result.|
| Promise\<void\> | Promise used to return the result.|
**Example**
......
......@@ -294,8 +294,8 @@ let httpProxy = {
port: 8080,
exclusionList: exclusionArray
}
connection.setGlobalHttpProxy(httpProxy).then((error, data) => {
console.info(JSON.stringify(data));
connection.setGlobalHttpProxy(httpProxy).then(() => {
console.info("success");
}).catch(error=>{
console.info(JSON.stringify(error));
})
......@@ -436,8 +436,8 @@ Binds an application to the specified network, so that the application can acces
```js
connection.getDefaultNet().then(function (netHandle) {
connection.setAppNet(netHandle).then((error, data) => {
console.log(JSON.stringify(data))
connection.setAppNet(netHandle).then(() => {
console.log("success")
}).catch(error => {
console.log(JSON.stringify(error))
})
......@@ -1097,7 +1097,7 @@ getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>):
Resolves the host name by using the default network to obtain all IP addresses. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -1134,7 +1134,7 @@ getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Resolves the host name by using the default network to obtain all IP addresses. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -1639,7 +1639,7 @@ getAddressesByName(host: string, callback: AsyncCallback\<Array\<NetAddress>>):
Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -1678,7 +1678,7 @@ getAddressesByName(host: string): Promise\<Array\<NetAddress>>
Resolves the host name by using the corresponding network to obtain all IP addresses. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -1721,7 +1721,7 @@ getAddressByName(host: string, callback: AsyncCallback\<NetAddress>): void
Resolves the host name by using the corresponding network to obtain the first IP address. This API uses an asynchronous callback to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......@@ -1760,7 +1760,7 @@ getAddressByName(host: string): Promise\<NetAddress>
Resolves the host name by using the corresponding network to obtain the first IP address. This API uses a promise to return the result.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetManager.Core
......
......@@ -13,7 +13,7 @@ The Resource Manager module provides APIs to obtain information about applicatio
import resourceManager from '@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
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------------------- | ---- | ----------------------------- |
| bundleName | string | Yes | Bundle name of the target application. |
| bundleName | string | Yes | Bundle name of the application. |
| callback | AsyncCallback&lt;[ResourceManager](#resourcemanager)&gt; | 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
getMediaContent(resId: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -1658,7 +1658,7 @@ Obtains the string corresponding to the specified resource name. This API uses a
| Type | Description |
| --------------------- | ---------- |
| Promise&lt;string&gt; | Promise used to return the result.|
| Promise&lt;string&gt; | String corresponding to the resource name.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
......@@ -1770,7 +1770,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
getMediaByName(resName: string, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Global.ResourceManager
......@@ -2036,7 +2036,7 @@ Obtains the string corresponding to the specified resource ID. This API returns
| Type | Description |
| ------ | ----------- |
| string | String corresponding to the specified resource ID.|
| string | Promise used to return the result.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
......@@ -2075,7 +2075,7 @@ Obtains the string corresponding to the specified resource object. This API retu
| Type | Description |
| ------ | ---------------- |
| string | String corresponding to the resource object.|
| string | Promise used to return the result.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
......@@ -2119,7 +2119,7 @@ Obtains the string corresponding to the specified resource name. This API return
| Type | Description |
| ------ | ---------- |
| string | String corresponding to the resource name.|
| string | String corresponding to the specified resource name.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
......@@ -2395,6 +2395,142 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco
}
```
### getDrawableDescriptor<sup>10+</sup>
getDrawableDescriptor(resId: number, density?: number): DrawableDescriptor;
Obtains the **DrawableDescriptor** object based on the specified resource ID. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ----- | ------ | ---- | ----- |
| resId | number | Yes | Resource ID.|
| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
| Type | Description |
| ------ | ---------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the resource ID.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
**Error codes**
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
try {
this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`)
}
try {
this.context.resourceManager.getDrawableDescriptor($r('app.media.icon').id, 120);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`)
}
```
### getDrawableDescriptor<sup>10+</sup>
getDrawableDescriptor(resource: Resource, density?: number): DrawableDescriptor;
Obtains the **DrawableDescriptor** object based on the specified resource. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---- |
| resource | [Resource](#resource9) | Yes | Resource object.|
| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
| Type | Description |
| ------- | ----------------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the resource ID.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
**Error codes**
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001001 | If the resId invalid. |
| 9001002 | If the resource not found by resId. |
**Example**
```ts
let resource = {
bundleName: "com.example.myapplication",
moduleName: "entry",
id: $r('app.media.icon').id
};
try {
this.context.resourceManager.getDrawableDescriptor(resource);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`)
}
try {
this.context.resourceManager.getDrawableDescriptor(resource, 120);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`)
}
```
### getDrawableDescriptorByName<sup>10+</sup>
getDrawableDescriptorByName(resName: string, density?: number): DrawableDescriptor;
Obtains the **DrawableDescriptor** object based on the specified resource name. This API returns the result synchronously.
**System capability**: SystemCapability.Global.ResourceManager
**Parameters**
| Name | Type | Mandatory | Description |
| ------- | ------ | ---- | ---- |
| resName | string | Yes | Resource name.|
| [density](#screendensity) | number | No | Screen density. The default value is **0**.|
**Return value**
| Type | Description |
| ------ | --------- |
| DrawableDescriptor | **DrawableDescriptor** object corresponding to the resource ID.|
For details about the error codes, see [Resource Manager Error Codes](../errorcodes/errorcode-resource-manager.md).
**Error codes**
| ID| Error Message|
| -------- | ---------------------------------------- |
| 9001003 | If the resName invalid. |
| 9001004 | If the resource not found by resName. |
**Example**
```ts
try {
this.context.resourceManager.getDrawableDescriptorByName('icon');
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`)
}
try {
this.context.resourceManager.getDrawableDescriptorByName('icon', 120);
} catch (error) {
console.error(`getDrawableDescriptor failed, error code: ${error.code}, message: ${error.message}.`)
}
```
### getString<sup>(deprecated)</sup>
......@@ -2530,7 +2666,7 @@ This API is deprecated since API version 9. You are advised to use [getStringArr
getMedia(resId: number, callback: AsyncCallback&lt;Uint8Array&gt;): void
Obtains the content of the media file corresponding to the specified resource name. This API uses an asynchronous callback to return the result.
Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result.
This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9) instead.
......
......@@ -91,6 +91,19 @@ Sends an SMS message.
| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| options | [SendMessageOptions](#sendmessageoptions) | Yes | Options (including the callback) for sending an SMS message.|
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 8300001 | Invalid parameter value. |
| 8300002 | Operation failed. Cannot connect to service. |
| 8300003 | System internal error. |
| 8300999 | Unknown error code. |
**Example**
```js
......@@ -179,6 +192,8 @@ Sets the default slot ID of the SIM card used to send SMS messages. This API use
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -192,8 +207,8 @@ Sets the default slot ID of the SIM card used to send SMS messages. This API use
**Example**
```js
sms.setDefaultSmsSlotId(0, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
sms.setDefaultSmsSlotId(0, (err) => {
console.log(`callback: err->${JSON.stringify(err)}.`);
});
```
......@@ -224,6 +239,8 @@ Sets the default slot ID of the SIM card used to send SMS messages. This API use
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -238,9 +255,9 @@ Sets the default slot ID of the SIM card used to send SMS messages. This API use
```js
let promise = sms.setDefaultSmsSlotId(0);
promise.then(data => {
console.log(`setDefaultSmsSlotId success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
promise.then(() => {
console.log(`setDefaultSmsSlotId success.`);
}).catch((err) => {
console.error(`setDefaultSmsSlotId failed, promise: err->${JSON.stringify(err)}`);
});
```
......@@ -267,6 +284,8 @@ Sets the short message service center (SMSC) address. This API uses an asynchron
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -281,8 +300,8 @@ Sets the short message service center (SMSC) address. This API uses an asynchron
```js
let slotId = 0;
let smscAddr = '+861xxxxxxxxxx';
sms.setSmscAddr(slotId, smscAddr, (err,data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
sms.setSmscAddr(slotId, smscAddr, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -314,6 +333,8 @@ Sets the SMSC address. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -329,9 +350,9 @@ Sets the SMSC address. This API uses a promise to return the result.
let slotId = 0;
let smscAddr = '+861xxxxxxxxxx';
let promise = sms.setSmscAddr(slotId, smscAddr);
promise.then(data => {
console.log(`setSmscAddr success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
promise.then(() => {
console.log(`setSmscAddr success.`);
}).catch((err) => {
console.error(`setSmscAddr failed, promise: err->${JSON.stringify(err)}`);
});
```
......@@ -358,6 +379,8 @@ Obtains the SMSC address. This API uses an asynchronous callback to return the r
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -403,6 +426,8 @@ Obtains the SMSC address. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -464,6 +489,8 @@ Splits an SMS message into multiple segments. This API uses an asynchronous call
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -509,6 +536,8 @@ Splits an SMS message into multiple segments. This API uses a promise to return
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -551,6 +580,8 @@ Adds a SIM message. This API uses an asynchronous callback to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -569,8 +600,8 @@ let simMessageOptions = {
pdu: "xxxxxx",
status: sms.SimMessageStatus.SIM_MESSAGE_STATUS_READ
};
sms.addSimMessage(simMessageOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
sms.addSimMessage(simMessageOptions, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -601,6 +632,8 @@ Adds a SIM message. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -620,9 +653,9 @@ let simMessageOptions = {
status: sms.SimMessageStatus.SIM_MESSAGE_STATUS_READ
};
let promise = sms.addSimMessage(simMessageOptions);
promise.then(data => {
console.log(`addSimMessage success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
promise.then(() => {
console.log(`addSimMessage success.`);
}).catch((err) => {
console.error(`addSimMessage failed, promise: err->${JSON.stringify(err)}`);
});
```
......@@ -649,6 +682,8 @@ Deletes a SIM message. This API uses an asynchronous callback to return the resu
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -663,8 +698,8 @@ Deletes a SIM message. This API uses an asynchronous callback to return the resu
```js
let slotId = 0;
let msgIndex = 1;
sms.delSimMessage(slotId, msgIndex, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
sms.delSimMessage(slotId, msgIndex, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -696,6 +731,8 @@ Deletes a SIM message. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -711,9 +748,9 @@ Deletes a SIM message. This API uses a promise to return the result.
let slotId = 0;
let msgIndex = 1;
let promise = sms.delSimMessage(slotId, msgIndex);
promise.then(data => {
console.log(`delSimMessage success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
promise.then(() => {
console.log(`delSimMessage success.`);
}).catch((err) => {
console.error(`delSimMessage failed, promise: err->${JSON.stringify(err)}`);
});
```
......@@ -739,6 +776,8 @@ Updates a SIM message. This API uses an asynchronous callback to return the resu
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -758,8 +797,8 @@ let updateSimMessageOptions = {
pdu: "xxxxxxx",
smsc: "test"
};
sms.updateSimMessage(updateSimMessageOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
sms.updateSimMessage(updateSimMessageOptions, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -790,6 +829,8 @@ Updates a SIM message. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -810,9 +851,9 @@ let updateSimMessageOptions = {
smsc: "test"
};
let promise = sms.updateSimMessage(updateSimMessageOptions);
promise.then(data => {
console.log(`updateSimMessage success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
promise.then(() => {
console.log(`updateSimMessage success.`);
}).catch((err) => {
console.error(`updateSimMessage failed, promise: err->${JSON.stringify(err)}`);
});
```
......@@ -838,6 +879,8 @@ Obtains all SIM card messages. This API uses an asynchronous callback to return
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -883,6 +926,8 @@ Obtains all SIM card messages. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -925,6 +970,8 @@ Sets the cell broadcast configuration. This API uses an asynchronous callback to
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -944,8 +991,8 @@ let cbConfigOptions = {
endMessageId: 200,
ranType: sms.RanType.TYPE_GSM
};
sms.setCBConfig(cbConfigOptions, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
sms.setCBConfig(cbConfigOptions, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -976,6 +1023,8 @@ Sets the cell broadcast configuration. This API uses a promise to return the res
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -996,9 +1045,9 @@ let cbConfigOptions = {
ranType: sms.RanType.TYPE_GSM
};
let promise = sms.setCBConfig(cbConfigOptions);
promise.then(data => {
console.log(`setCBConfig success, promise: data->${JSON.stringify(data)}`);
}).catch(err => {
promise.then(() => {
console.log(`setCBConfig success.`);
}).catch((err) => {
console.error(`setCBConfig failed, promise: err->${JSON.stringify(err)}`);
});
```
......@@ -1024,6 +1073,8 @@ Obtains SMS message segment information. This API uses an asynchronous callback
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 401 | Parameter error. |
......@@ -1068,6 +1119,8 @@ Obtains SMS message segment information. This API uses a promise to return the r
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 401 | Parameter error. |
......@@ -1107,6 +1160,8 @@ Checks whether SMS is supported on IMS. This API uses an asynchronous callback t
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 401 | Parameter error. |
......@@ -1149,6 +1204,8 @@ This API uses an asynchronous callback to return the result. This API uses a pro
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 401 | Parameter error. |
......@@ -1187,9 +1244,10 @@ Obtains the SMS format supported by the IMS. This API uses an asynchronous callb
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 8300001 | Invalid parameter value. |
| 8300002 | Operation failed. Cannot connect to service. |
......@@ -1223,9 +1281,10 @@ Obtains the SMS format supported by the IMS. This API uses a promise to return t
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
| 401 | Parameter error. |
| 8300001 | Invalid parameter value. |
| 8300002 | Operation failed. Cannot connect to service. |
......@@ -1262,6 +1321,8 @@ Decodes MMS messages. This API uses an asynchronous callback to return the resul
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 401 | Parameter error. |
......@@ -1304,6 +1365,8 @@ Decodes MMS messages. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 401 | Parameter error. |
......@@ -1343,6 +1406,8 @@ MMS message code. This API uses an asynchronous callback to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 401 | Parameter error. |
......@@ -1393,6 +1458,8 @@ MMS message code. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 401 | Parameter error. |
......
# Socket Connection
# # @ohos.net.socket (Socket Connection)
The **socket** module implements data transfer over TCPSocket, UDPSocket, WebSocket, and TLSSocket connections.
......@@ -364,7 +364,7 @@ udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => {
setExtraOptions(options: UDPExtraOptions, callback: AsyncCallback\<void\>): void
Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result.
Sets other attributes of the UDPSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>This API can be called only after **bind** is successfully called.
......@@ -418,7 +418,7 @@ udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> {
setExtraOptions(options: UDPExtraOptions): Promise\<void\>
Sets other properties of the UDPSocket connection. This API uses a promise to return the result.
Sets other attributes of the UDPSocket connection. This API uses a promise to return the result.
>**NOTE**
>This API can be called only after **bind** is successfully called.
......@@ -522,7 +522,7 @@ let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
udp.on('message', callback);
// 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');
let callback2 = () =>{
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.
udp.off('close', callback2);
udp.off('close');
```
......@@ -646,7 +646,7 @@ let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
udp.on('error', callback);
// 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('error', callback);
udp.off('error');
```
......@@ -1426,7 +1426,7 @@ let callback = value =>{
console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo);
}
tcp.on('message', callback);
// 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');
let callback2 = () =>{
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.
tcp.off('close', callback2);
tcp.off('close');
```
......@@ -1550,7 +1550,7 @@ let callback = err =>{
console.log("on error, err:" + JSON.stringify(err));
}
tcp.on('error', callback);
// 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.
| Type | Description |
| --------------------------------------------------------------------- | --------------------- |
|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | Data and encoding format of the certificate.|
|[cert.EncodingBlob](js-apis-cert.md#datablob) | Data and encoding format of the certificate.|
......@@ -100,6 +100,8 @@ Sets the default slot of the SIM card used for mobile data. This API uses an asy
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -114,8 +116,8 @@ Sets the default slot of the SIM card used for mobile data. This API uses an asy
**Example**
```js
data.setDefaultCellularDataSlotId(0, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
data.setDefaultCellularDataSlotId(0, (err) => {
console.log(`callback: err->${JSON.stringify(err)}.`);
});
```
......@@ -145,6 +147,8 @@ Sets the default slot of the SIM card used for mobile data. This API uses a prom
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -160,8 +164,8 @@ Sets the default slot of the SIM card used for mobile data. This API uses a prom
```js
let promise = data.setDefaultCellularDataSlotId(0);
promise.then((data) => {
console.log(`setDefaultCellularDataSlotId success, promise: data->${JSON.stringify(data)}`);
promise.then(() => {
console.log(`setDefaultCellularDataSlotId success.`);
}).catch((err) => {
console.error(`setDefaultCellularDataSlotId fail, promise: err->${JSON.stringify(err)}`);
});
......@@ -279,6 +283,8 @@ Checks whether the cellular data service is enabled. This API uses an asynchrono
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -314,6 +320,8 @@ Checks whether the cellular data service is enabled. This API uses a promise to
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -353,6 +361,8 @@ Checks whether roaming is enabled for the cellular data service. This API uses a
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -394,6 +404,8 @@ Checks whether roaming is enabled for the cellular data service. This API uses a
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -434,6 +446,8 @@ Enables the cellular data service. This API uses an asynchronous callback to ret
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -446,8 +460,8 @@ Enables the cellular data service. This API uses an asynchronous callback to ret
**Example**
```js
data.enableCellularData((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
data.enableCellularData((err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -471,6 +485,8 @@ Enables the cellular data service. This API uses a promise to return the result.
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -484,8 +500,8 @@ Enables the cellular data service. This API uses a promise to return the result.
```js
let promise = data.enableCellularData();
promise.then((data) => {
console.log(`enableCellularData success, promise: data->${JSON.stringify(data)}`);
promise.then(() => {
console.log(`enableCellularData success.`);
}).catch((err) => {
console.error(`enableCellularData fail, promise: err->${JSON.stringify(err)}`);
});
......@@ -511,6 +527,8 @@ Disables the cellular data service. This API uses an asynchronous callback to re
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -523,8 +541,8 @@ Disables the cellular data service. This API uses an asynchronous callback to re
**Example**
```js
data.disableCellularData((err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
data.disableCellularData((err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -548,6 +566,8 @@ Disables the cellular data service. This API uses a promise to return the result
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -561,8 +581,8 @@ Disables the cellular data service. This API uses a promise to return the result
```js
let promise = data.disableCellularData();
promise.then((data) => {
console.log(`disableCellularData success, promise: data->${JSON.stringify(data)}`);
promise.then(() => {
console.log(`disableCellularData success.`);
}).catch((err) => {
console.error(`disableCellularData fail, promise: err->${JSON.stringify(err)}`);
});
......@@ -589,6 +609,8 @@ Enables the cellular data roaming service. This API uses an asynchronous callbac
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -601,8 +623,8 @@ Enables the cellular data roaming service. This API uses an asynchronous callbac
**Example**
```js
data.enableCellularDataRoaming(0, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
data.enableCellularDataRoaming(0, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -632,6 +654,8 @@ Enables the cellular data roaming service. This API uses a promise to return the
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -645,8 +669,8 @@ Enables the cellular data roaming service. This API uses a promise to return the
```js
let promise = data.enableCellularDataRoaming(0);
promise.then((data) => {
console.log(`enableCellularDataRoaming success, promise: data->${JSON.stringify(data)}`);
promise.then(() => {
console.log(`enableCellularDataRoaming success.`);
}).catch((err) => {
console.error(`enableCellularDataRoaming fail, promise: err->${JSON.stringify(err)}`);
});
......@@ -673,6 +697,8 @@ Disables the cellular data roaming service. This API uses an asynchronous callba
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -685,8 +711,8 @@ Disables the cellular data roaming service. This API uses an asynchronous callba
**Example**
```js
data.disableCellularDataRoaming(0, (err, data) => {
console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`);
data.disableCellularDataRoaming(0, (err) => {
console.log(`callback: err->${JSON.stringify(err)}`);
});
```
......@@ -716,6 +742,8 @@ Disables the cellular data roaming service. This API uses a promise to return th
**Error codes**
For details about the following error codes, see [Telephony Error Codes](../../reference/errorcodes/errorcode-telephony.md).
| ID| Error Message |
| -------- | -------------------------------------------- |
| 201 | Permission denied. |
......@@ -729,8 +757,8 @@ Disables the cellular data roaming service. This API uses a promise to return th
```js
let promise = data.disableCellularDataRoaming(0);
promise.then((data) => {
console.log(`disableCellularDataRoaming success, promise: data->${JSON.stringify(data)}`);
promise.then(() => {
console.log(`disableCellularDataRoaming success.`);
}).catch((err) => {
console.error(`disableCellularDataRoaming fail, promise: err->${JSON.stringify(err)}`);
});
......
......@@ -50,10 +50,6 @@
- [Sensor Overview](subsys-sensor-overview.md)
- [Sensor Usage Guidelines](subsys-sensor-guide.md)
- [Sensor Usage Example](subsys-sensor-demo.md)
- USB
- [USB Overview](subsys-usbservice-overview.md)
- [USB Usage Guidelines](subsys-usbservice-guide.md)
- [USB Usage Example](subsys-usbservice-demo.md)
- Application Framework
- [Application Framework Overview](subsys-application-framework-overview.md)
- [Setting Up a Development Environment](subsys-application-framework-envbuild.md)
......
# USB Usage Example<a name="EN-US_TOPIC_0000001092792986"></a>
```cpp
#include <cstdio>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <sys/time.h>
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iremote_object.h"
#include "iservice_registry.h"
#include "iusb_srv.h"
#include "string_ex.h"
#include "system_ability_definition.h"
#include "usb_common.h"
#include "usb_device.h"
#include "usb_errors.h"
#include "usb_request.h"
#include "usb_server_proxy.h"
#include "usb_srv_client.h"
const int32_t REQUESTYPE = ((1 << 7) | (0 << 5) | (0 & 0x1f));
const int32_t REQUESTCMD = 6;
const int32_t VALUE = (2 << 8) + 0;
const int32_t TIMEOUT = 5000;
const int32_t ITFCLASS = 10;
const int32_t PRAMATYPE = 2;
const int32_t BUFFERLENGTH = 21;
void GetType(OHOS::USB::USBEndpoint &tep, OHOS::USB::USBEndpoint &outEp, bool &outEpFlg)
{
if ((tep.GetType() == PRAMATYPE)) {
if (tep.GetDirection() == 0) {
outEp = tep;
outEpFlg = true;
}
}
}
bool SelectEndpoint(OHOS::USB::USBConfig config,
std::vector<OHOS::USB::UsbInterface> interfaces,
OHOS::USB::UsbInterface &interface,
OHOS::USB::USBEndpoint &outEp,
bool &outEpFlg)
{
for (int32_t i = 0; i < config.GetInterfaceCount(); ++i) {
OHOS::USB::UsbInterface tif = interfaces[i];
std::vector<OHOS::USB::USBEndpoint> mEndpoints = tif.GetEndpoints();
for (int32_t j = 0; j < tif.GetEndpointCount(); ++j) {
OHOS::USB::USBEndpoint tep = mEndpoints[j];
if ((tif.GetClass() == ITFCLASS) && (tif.GetSubClass() == 0) && (tif.GetProtocol() == PRAMATYPE)) {
GetType(tep, outEp, outEpFlg);
}
}
if (outEpFlg) {
interface = interfaces[i];
return true;
}
std::cout << std::endl;
}
return false;
}
int OpenDeviceTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::UsbDevice device, OHOS::USB::USBDevicePipe &pip)
{
int ret = Instran.RequestRight(device.GetName());
std::cout << "device RequestRight ret = " << ret << std::endl;
if (0 != ret) {
std::cout << "device RequestRight failed = " << ret << std::endl;
}
ret = Instran.OpenDevice(device, pip);
return ret;
}
int CtrTransferTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::USBDevicePipe &pip)
{
std::cout << "usb_device_test : << Control Transfer >> " << std::endl;
std::vector<uint8_t> vData;
const OHOS::USB::UsbCtrlTransfer tctrl = {REQUESTYPE, REQUESTCMD, VALUE, 0, TIMEOUT};
int ret = Instran.ControlTransfer(pip, tctrl, vData);
if (ret != 0) {
std::cout << "control message read failed width ret = " << ret << std::endl;
} else {
}
std::cout << "control message read success" << std::endl;
return ret;
}
int ClaimTest(OHOS::USB::UsbSrvClient &Instran,
OHOS::USB::USBDevicePipe &pip,
OHOS::USB::UsbInterface &interface,
bool interfaceFlg)
{
if (interfaceFlg) {
std::cout << "ClaimInterface InterfaceInfo:" << interface.ToString() << std::endl;
int ret = Instran.ClaimInterface(pip, interface, true);
if (ret != 0) {
std::cout << "ClaimInterface failed width ret = " << ret << std::endl;
} else {
std::cout << "ClaimInterface success" << std::endl;
}
}
return 0;
}
int BulkTransferTest(OHOS::USB::UsbSrvClient &Instran,
OHOS::USB::USBDevicePipe &pip,
OHOS::USB::USBEndpoint &outEp,
bool interfaceFlg,
bool outEpFlg)
{
if (interfaceFlg) {
std::cout << "usb_device_test : << Bulk transfer start >> " << std::endl;
if (outEpFlg) {
uint8_t buffer[50] = "hello world 123456789";
std::vector<uint8_t> vData(buffer, buffer + BUFFERLENGTH);
int ret = Instran.BulkTransfer(pip, outEp, vData, TIMEOUT);
if (ret != 0) {
std::cout << "Bulk transfer write failed width ret = " << ret << std::endl;
} else {
std::cout << "Bulk transfer write success" << std::endl;
}
return ret;
}
}
return 0;
}
int main(int argc, char **argv)
{
std::cout << "usb_device_test " << std::endl;
static OHOS::USB::UsbSrvClient &Instran = OHOS::USB::UsbSrvClient::GetInstance();
// GetDevices
std::vector<OHOS::USB::UsbDevice> deviceList;
int32_t ret = Instran.GetDevices(deviceList);
if (ret != 0) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
if (deviceList.empty()) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
OHOS::USB::UsbDevice device = deviceList[0];
std::vector<OHOS::USB::USBConfig> configs = device.GetConfigs();
OHOS::USB::USBConfig config = configs[0];
std::vector<OHOS::USB::UsbInterface> interfaces = config.GetInterfaces();
OHOS::USB::UsbInterface interface;
OHOS::USB::USBEndpoint outEp;
bool interfaceFlg = false;
bool outEpFlg = false;
interfaceFlg = SelectEndpoint(config, interfaces, interface, outEp, outEpFlg);
// OpenDevice
std::cout << "usb_device_test : << OpenDevice >> test begin -> " << std::endl;
OHOS::USB::USBDevicePipe pip;
ret = OpenDeviceTest(Instran, device, pip);
if (ret != 0) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
// ControlTransfer
CtrTransferTest(Instran, pip);
// ClaimInterface
ClaimTest(Instran, pip, interface, interfaceFlg);
// BulkTransferWrite
BulkTransferTest(Instran, pip, outEp, interfaceFlg, outEpFlg);
// CloseDevice
std::cout << "usb_device_test : << Close Device >> " << std::endl;
ret = Instran.Close(pip);
if (ret == 0) {
std::cout << "Close device failed width ret = " << ret << std::endl;
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
} else {
std::cout << "Close Device success" << std::endl;
}
return 0;
}
```
# USB Usage Guidelines<a name="EN-US_TOPIC_0000001077367159"></a>
The following procedure uses bulk transfer as an example.
## Procedure<a name="section18816105182315"></a>
1. Obtain a USB service instance.
```cpp
static OHOS::USB::UsbSrvClient &g_usbClient = OHOS::USB::UsbSrvClient::GetInstance();
```
2. Obtain the USB device list.
```cpp
std::vector<OHOS::USB::UsbDevice> deviceList;
int32_t ret = g_usbClient.GetDevices(deviceList);
```
3. Apply for device access permissions.
```cpp
int32_t ret = g_usbClient.RequestRight(device.GetName());
```
4. Open the USB device.
```cpp
USBDevicePipe pip;
int32_t et = g_usbClient.OpenDevice(device, pip);
```
5. Configure the USB interface.
```cpp
ret = g_usbClient.ClaimInterface(pip, interface, true); // **interface** indicates an interface of the USB device in **deviceList**.
```
6. Transfer data.
```cpp
srvClient.BulkTransfer(pipe, endpoint, vdata, timeout);
```
Parameter description:
- **pipe**: pipe for data transfer of the USB device opened.
- **endpoint**: endpoint for data transfer on the USB device.
- **vdata**: binary data block to be transferred or read.
- **timeout**: timeout duration of data transfer.
7. Close the USB device.
```cpp
ret = g_usbClient.Close(pip);
```
# USB
## Introduction
### Function Description
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.
### APIs
**Table 1** Host-specific APIs
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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. |
**Table 2** Device-specific APIs
| API | Description |
| -------------------------------------------------- | ------------------------------------------------------ |
| int32_t GetCurrentFunctions(int32_t &funcs); | Obtains the numeric mask combination for the current USB function list in Device mode. |
| int32_t SetCurrentFunctions(int32_t funcs); | Sets the current USB function list in Device mode. |
| int32_t UsbFunctionsFromString(std::string funcs); | Converts the string descriptor of a given USB function list to a numeric mask combination.|
| std::string UsbFunctionsToString(int32_t funcs); | Converts the numeric mask combination of a given USB function list to a string descriptor.|
**Table 3** Port-specific APIs
| API | Description |
| ------------------------------------------------------------ | -------------------------------------------------------- |
| 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.
1. Obtain a USB service instance.
```cpp
static OHOS::USB::UsbSrvClient &g_usbClient = OHOS::USB::UsbSrvClient::GetInstance();
```
2. Obtain the USB device list.
```cpp
std::vector<OHOS::USB::UsbDevice> deviceList;
int32_t ret = g_usbClient.GetDevices(deviceList);
```
3. Apply for device access permissions.
```cpp
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.
srvClient.BulkTransfer(pipe, endpoint, vdata, timeout);
```
7. Closes a device.
```cpp
ret = g_usbClient.Close(pip);
```
### Sample Code
```cpp
#include <cstdio>
#include <iostream>
#include <map>
#include <mutex>
#include <sstream>
#include <sys/time.h>
#include "if_system_ability_manager.h"
#include "ipc_skeleton.h"
#include "iremote_object.h"
#include "iservice_registry.h"
#include "iusb_srv.h"
#include "string_ex.h"
#include "system_ability_definition.h"
#include "usb_common.h"
#include "usb_device.h"
#include "usb_errors.h"
#include "usb_request.h"
#include "usb_server_proxy.h"
#include "usb_srv_client.h"
const int32_t REQUESTYPE = ((1 << 7) | (0 << 5) | (0 & 0x1f));
const int32_t REQUESTCMD = 6;
const int32_t VALUE = (2 << 8) + 0;
const int32_t TIMEOUT = 5000;
const int32_t ITFCLASS = 10;
const int32_t PRAMATYPE = 2;
const int32_t BUFFERLENGTH = 21;
void GetType(OHOS::USB::USBEndpoint &tep, OHOS::USB::USBEndpoint &outEp, bool &outEpFlg)
{
if ((tep.GetType() == PRAMATYPE)) {
if (tep.GetDirection() == 0) {
outEp = tep;
outEpFlg = true;
}
}
}
bool SelectEndpoint(OHOS::USB::USBConfig config,
std::vector<OHOS::USB::UsbInterface> interfaces,
OHOS::USB::UsbInterface &interface,
OHOS::USB::USBEndpoint &outEp,
bool &outEpFlg)
{
for (int32_t i = 0; i < config.GetInterfaceCount(); ++i) {
OHOS::USB::UsbInterface tif = interfaces[i];
std::vector<OHOS::USB::USBEndpoint> mEndpoints = tif.GetEndpoints();
for (int32_t j = 0; j < tif.GetEndpointCount(); ++j) {
OHOS::USB::USBEndpoint tep = mEndpoints[j];
if ((tif.GetClass() == ITFCLASS) && (tif.GetSubClass() == 0) && (tif.GetProtocol() == PRAMATYPE)) {
GetType(tep, outEp, outEpFlg);
}
}
if (outEpFlg) {
interface = interfaces[i];
return true;
}
std::cout << std::endl;
}
return false;
}
int OpenDeviceTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::UsbDevice device, OHOS::USB::USBDevicePipe &pip)
{
int ret = Instran.RequestRight(device.GetName());
std::cout << "device RequestRight ret = " << ret << std::endl;
if (0 != ret) {
std::cout << "device RequestRight failed = " << ret << std::endl;
}
ret = Instran.OpenDevice(device, pip);
return ret;
}
int CtrTransferTest(OHOS::USB::UsbSrvClient &Instran, OHOS::USB::USBDevicePipe &pip)
{
std::cout << "usb_device_test : << Control Transfer >> " << std::endl;
std::vector<uint8_t> vData;
const OHOS::USB::UsbCtrlTransfer tctrl = {REQUESTYPE, REQUESTCMD, VALUE, 0, TIMEOUT};
int ret = Instran.ControlTransfer(pip, tctrl, vData);
if (ret != 0) {
std::cout << "control message read failed width ret = " << ret << std::endl;
} else {
}
std::cout << "control message read success" << std::endl;
return ret;
}
int ClaimTest(OHOS::USB::UsbSrvClient &Instran,
OHOS::USB::USBDevicePipe &pip,
OHOS::USB::UsbInterface &interface,
bool interfaceFlg)
{
if (interfaceFlg) {
std::cout << "ClaimInterface InterfaceInfo:" << interface.ToString() << std::endl;
int ret = Instran.ClaimInterface(pip, interface, true);
if (ret != 0) {
std::cout << "ClaimInterface failed width ret = " << ret << std::endl;
} else {
std::cout << "ClaimInterface success" << std::endl;
}
}
return 0;
}
int BulkTransferTest(OHOS::USB::UsbSrvClient &Instran,
OHOS::USB::USBDevicePipe &pip,
OHOS::USB::USBEndpoint &outEp,
bool interfaceFlg,
bool outEpFlg)
{
if (interfaceFlg) {
std::cout << "usb_device_test : << Bulk transfer start >> " << std::endl;
if (outEpFlg) {
uint8_t buffer[50] = "hello world 123456789";
std::vector<uint8_t> vData(buffer, buffer + BUFFERLENGTH);
int ret = Instran.BulkTransfer(pip, outEp, vData, TIMEOUT);
if (ret != 0) {
std::cout << "Bulk transfer write failed width ret = " << ret << std::endl;
} else {
std::cout << "Bulk transfer write success" << std::endl;
}
return ret;
}
}
return 0;
}
int main(int argc, char **argv)
{
std::cout << "usb_device_test " << std::endl;
static OHOS::USB::UsbSrvClient &Instran = OHOS::USB::UsbSrvClient::GetInstance();
// GetDevices
std::vector<OHOS::USB::UsbDevice> deviceList;
int32_t ret = Instran.GetDevices(deviceList);
if (ret != 0) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
if (deviceList.empty()) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
OHOS::USB::UsbDevice device = deviceList[0];
std::vector<OHOS::USB::USBConfig> configs = device.GetConfigs();
OHOS::USB::USBConfig config = configs[0];
std::vector<OHOS::USB::UsbInterface> interfaces = config.GetInterfaces();
OHOS::USB::UsbInterface interface;
OHOS::USB::USBEndpoint outEp;
bool interfaceFlg = false;
bool outEpFlg = false;
interfaceFlg = SelectEndpoint(config, interfaces, interface, outEp, outEpFlg);
// OpenDevice
std::cout << "usb_device_test : << OpenDevice >> test begin -> " << std::endl;
OHOS::USB::USBDevicePipe pip;
ret = OpenDeviceTest(Instran, device, pip);
if (ret != 0) {
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
}
// ControlTransfer
CtrTransferTest(Instran, pip);
// ClaimInterface
ClaimTest(Instran, pip, interface, interfaceFlg);
// BulkTransferWrite
BulkTransferTest(Instran, pip, outEp, interfaceFlg, outEpFlg);
// CloseDevice
std::cout << "usb_device_test : << Close Device >> " << std::endl;
ret = Instran.Close(pip);
if (ret == 0) {
std::cout << "Close device failed width ret = " << ret << std::endl;
return OHOS::USB::UEC_SERVICE_INVALID_VALUE;
} else {
std::cout << "Close Device success" << std::endl;
}
return 0;
}
```
### Repositories Involved
[Driver subsystem](https://gitee.com/openharmony/docs/blob/master/en/readme/driver.md)
[drivers\_peripheral](https://gitee.com/openharmony/drivers_peripheral/blob/master/README_zh.md)
[drivers\_framework](https://gitee.com/openharmony/drivers_framework/blob/master/README_zh.md)
[drivers\_adapter](https://gitee.com/openharmony/drivers_adapter/blob/master/README_zh.md)
[drivers\_adapter\_khdf\_linux](https://gitee.com/openharmony/drivers_adapter_khdf_linux/blob/master/README_zh.md)
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册