提交 ecb3d4da 编写于 作者: G ge-yafang

Merge branch 'OpenHarmony-3.1-Release' of https://gitee.com/ge-yafang/docs...

Merge branch 'OpenHarmony-3.1-Release' of https://gitee.com/ge-yafang/docs into OpenHarmony-3.1-Release
...@@ -20,7 +20,6 @@ ...@@ -20,7 +20,6 @@
- Development - Development
- [Ability Development](ability/Readme-EN.md) - [Ability Development](ability/Readme-EN.md)
- [UI Development](ui/Readme-EN.md) - [UI Development](ui/Readme-EN.md)
- Basic Feature Development
- [Common Event and Notification](notification/Readme-EN.md) - [Common Event and Notification](notification/Readme-EN.md)
- [Window Manager](windowmanager/Readme-EN.md) - [Window Manager](windowmanager/Readme-EN.md)
- [WebGL](webgl/Readme-EN.md) - [WebGL](webgl/Readme-EN.md)
......
...@@ -3,17 +3,14 @@ ...@@ -3,17 +3,14 @@
## Widget Overview ## Widget Overview
A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application. A widget is a set of UI components used to display important information or operations for an application. It provides users with direct access to a desired application service, without requiring them to open the application.
A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive features such as opening a UI page or sending a message. The widget host is responsible for displaying the widget. A widget displays brief information about an application on the UI of another application (host application, currently system applications only) and provides basic interactive functions such as opening a UI page or sending a message.
Basic concepts: Basic concepts:
- Widget provider - Widget provider: an atomic service that controls what and how content is displayed in a widget and interacts with users.
The widget provider is an atomic service that provides the content to be displayed. It controls the display content, component layout, and component click events of a widget. - Widget host: an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget host - Widget Manager: a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
The widget host is an application that displays the widget content and controls the position where the widget is displayed in the host application.
- Widget Manager > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
The Widget Manager is a resident agent that manages widgets added to the system and provides functions such as periodic widget update.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated. > The widget host and provider do not keep running all the time. The Widget Manager starts the widget provider to obtain widget information when a widget is added, deleted, or updated.
You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager. You only need to develop widget content as the widget provider. The system automatically handles the work done by the widget host and Widget Manager.
...@@ -25,7 +22,7 @@ The widget provider controls the widget content to display, component layout, an ...@@ -25,7 +22,7 @@ The widget provider controls the widget content to display, component layout, an
Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations: Form ability development refers to the development conducted by the widget provider based on the [Feature Ability (FA) model](fa-brief.md). As a widget provider, you need to carry out the following operations:
- Develop the lifecycle callbacks in **LifecycleForm**. - Develop the lifecycle callbacks in **LifecycleForm**.
- Create a **FormBindingData** object. - Create a **FormBindingData** instance.
- Update a widget through **FormProvider**. - Update a widget through **FormProvider**.
- Develop the widget UI page. - Develop the widget UI page.
...@@ -41,9 +38,9 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**. ...@@ -41,9 +38,9 @@ The table below describes the lifecycle callbacks provided **LifecycleForm**.
| onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.| | onCastToNormal(formId: string): void | Called to notify the widget provider that a temporary widget has been converted to a normal one.|
| onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. | | onUpdate(formId: string): void | Called to notify the widget provider that a widget has been updated. |
| onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. | | onVisibilityChange(newStatus: { [key: string]: number }): void | Called to notify the widget provider of the change of widget visibility. |
| onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process the widget event. | | onEvent(formId: string, message: string): void | Called to instruct the widget provider to receive and process a widget event. |
| onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. | | onDestroy(formId: string): void | Called to notify the widget provider that a **Form** instance (widget) has been destroyed. |
| onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a specified widget. | | onAcquireFormState?(want: Want): formInfo.FormState | Called when the widget provider receives the status query result of a widget. |
For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md). For details about the **FormProvider** APIs, see [FormProvider](../reference/apis/js-apis-formprovider.md).
...@@ -76,7 +73,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li ...@@ -76,7 +73,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
export default { export default {
onCreate(want) { onCreate(want) {
console.log('FormAbility onCreate'); console.log('FormAbility onCreate');
// Persistently store widget information for subsequent use, such as widget instance retrieval and update. // Persistently store widget information for subsequent use, such as during widget instance retrieval or update.
let obj = { let obj = {
"title": "titleOnCreate", "title": "titleOnCreate",
"detail": "detailOnCreate" "detail": "detailOnCreate"
...@@ -89,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li ...@@ -89,7 +86,7 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
console.log('FormAbility onCastToNormal'); console.log('FormAbility onCastToNormal');
}, },
onUpdate(formId) { onUpdate(formId) {
// To support scheduled update, periodic update, or update requested by the widget host for a widget, override this method for data update. // To support scheduled update, periodic update, or update requested by the widget host, override this method for widget data update.
console.log('FormAbility onUpdate'); console.log('FormAbility onUpdate');
let obj = { let obj = {
"title": "titleOnUpdate", "title": "titleOnUpdate",
...@@ -119,11 +116,11 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li ...@@ -119,11 +116,11 @@ To create a widget in the FA model, you need to implement the lifecycles of **Li
} }
``` ```
### Configuring config.json for the Form Ability ### Configuring the Widget Configuration File
Configure the **config.json** file for the **Form** ability. Configure the **config.json** file for the widget.
- The **js** module in the **config.json** file provides the JavaScript resources of the **Form** ability. The internal field structure is described as follows: - The **js** module in the **config.json** file provides the JavaScript resources of the widget. The internal field structure is described as follows:
| Field| Description | Data Type| Default | | Field| Description | Data Type| Default |
| -------- | ------------------------------------------------------------ | -------- | ------------------------ | | -------- | ------------------------------------------------------------ | -------- | ------------------------ |
...@@ -156,12 +153,12 @@ Configure the **config.json** file for the **Form** ability. ...@@ -156,12 +153,12 @@ Configure the **config.json** file for the **Form** ability.
| isDefault | Whether the widget is a default one. Each ability has only one default widget.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean | No | | isDefault | Whether the widget is a default one. Each ability has only one default widget.<br>**true**: The widget is the default one.<br>**false**: The widget is not the default one.| Boolean | No |
| type | Type of the widget. Available values are as follows:<br>**JS**: indicates a JavaScript-programmed widget. | String | No | | type | Type of the widget. Available values are as follows:<br>**JS**: indicates a JavaScript-programmed widget. | String | No |
| colorMode | Color mode of the widget. Available values are as follows:<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| | colorMode | Color mode of the widget. Available values are as follows:<br>**auto**: The widget adopts the auto-adaptive color mode.<br>**dark**: The widget adopts the dark color mode.<br>**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)|
| supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>1 * 2: indicates a grid with one row and two columns.<br>2 * 2: indicates a grid with two rows and two columns.<br>2 * 4: indicates a grid with two rows and four columns.<br>4 * 4: indicates a grid with four rows and four columns.| String array| No | | supportDimensions | Grid styles supported by the widget. Available values are as follows:<br>**1 * 2**: indicates a grid with one row and two columns.<br>**2 * 2**: indicates a grid with two rows and two columns.<br>**2 * 4**: indicates a grid with two rows and four columns.<br>**4 * 4**: indicates a grid with four rows and four columns.| String array| No |
| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | | defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No |
| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No | | updateEnabled | Whether the widget can be updated periodically. Available values are as follows:<br>**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.<br>**false**: The widget cannot be updated periodically.| Boolean | No |
| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) |
| updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.<br>If the value is **0**, this field does not take effect.<br>If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) |
| formConfigAbility | Indicates the link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | | formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) |
| formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) |
| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. | String | No |
| metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) | | metaData | Metadata of the widget. This field contains the array of the **customizeData** field. | Object | Yes (initial value: left empty) |
...@@ -198,7 +195,7 @@ Configure the **config.json** file for the **Form** ability. ...@@ -198,7 +195,7 @@ Configure the **config.json** file for the **Form** ability.
``` ```
### Widget Data Persistence ### Persistently Store Widget Data
Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget. Mostly, the widget provider is started only when it needs to obtain information about a widget. The Widget Manager supports multi-instance management and uses the widget ID to identify an instance. If the widget provider supports widget data modification, it must persistently store the data based on the widget ID, so that it can access the data of the target widget when obtaining, updating, or starting a widget.
...@@ -210,6 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information ...@@ -210,6 +207,7 @@ Mostly, the widget provider is started only when it needs to obtain information
let formName = want.parameters["ohos.extra.param.key.form_name"]; let formName = want.parameters["ohos.extra.param.key.form_name"];
let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"]; let tempFlag = want.parameters["ohos.extra.param.key.form_temporary"];
// Persistently store widget information for subsequent use, such as widget instance retrieval and update. // Persistently store widget information for subsequent use, such as widget instance retrieval and update.
// The storeFormInfo API is not implemented here. For details about the implementation, see "FA Model Widget" provided in "Samples".
storeFormInfo(formId, formName, tempFlag, want); storeFormInfo(formId, formName, tempFlag, want);
let obj = { let obj = {
...@@ -225,9 +223,11 @@ You should override **onDestroy** to delete widget data. ...@@ -225,9 +223,11 @@ You should override **onDestroy** to delete widget data.
```javascript ```javascript
onDestroy(formId) { onDestroy(formId) {
// Delete widget data.
deleteFormInfo(formId);
console.log('FormAbility onDestroy'); console.log('FormAbility onDestroy');
// You need to implement the code for deleting the persistent widget instance.
// The deleteFormInfo API is not implemented here. For details, see "Widget Host" provided in "Samples".
deleteFormInfo(formId);
} }
``` ```
...@@ -235,16 +235,16 @@ For details about the persistence method, see [Lightweight Data Store Developmen ...@@ -235,16 +235,16 @@ For details about the persistence method, see [Lightweight Data Store Developmen
Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one. Note that the **Want** passed by the widget host to the widget provider contains a temporary flag, indicating whether the requested widget is a temporary one.
Normal widget: a widget that will be persistently used by the widget host - Normal widget: a widget that will be persistently used by the widget host
Temporary widget: a widget that is temporarily used by the widget host - Temporary widget: a widget that is temporarily used by the widget host
Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets. Data of a temporary widget is not persistently stored. If the widget framework is killed and restarted, data of a temporary widget will be deleted. However, the widget provider is not notified of which widget is deleted, and still keeps the data. Therefore, the widget provider should implement data clearing. In addition, the widget host may convert a temporary widget into a normal one. If the conversion is successful, the widget provider should process the widget ID and store the data persistently. This prevents the widget provider from deleting persistent data when clearing temporary widgets.
### Developing the Widget UI Page ### Developing the Widget UI Page
You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget. You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programmed widget.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI. > Currently, only the JavaScript-based web-like development paradigm can be used to develop the widget UI.
- HML: - HML:
...@@ -326,10 +326,8 @@ Now you've got a widget shown below. ...@@ -326,10 +326,8 @@ Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
## Development Example ## Samples
The following sample is provided to help you better understand how to develop a widget on the FA model:
[FormAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
This sample provides a widget. Users can create, update, and delete widgets on the home screen of their devices or by using their own widget host. This sample also implements widget information persistence by using lightweight data storage. The following samples are provided to help you better understand how to develop a widget on the FA model:
- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher)
...@@ -8,21 +8,27 @@ The following figure shows the ability call process. ...@@ -8,21 +8,27 @@ The following figure shows the ability call process.
![stage-call](figures/stage-call.png) ![stage-call](figures/stage-call.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> The startup mode of the callee must be **singleton**.
> Currently, only system applications and Service Extension abilities can use the **Call** APIs to access the callee.
## Available APIs ## Available APIs
The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller). The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller).
**Table 1** Ability call APIs **Table 1** Ability call APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|Promise\<Caller> startAbilityByCall(want: Want)|Obtains the caller interface of the specified ability, and if the specified ability is not started, starts the ability in the background.| |startAbilityByCall(want: Want): Promise\<Caller>|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.|
|void on(method: string, callback: CalleeCallBack)|Callee.on: callback invoked when the callee registers a method.| |on(method: string, callback: CaleeCallBack): void|Callback invoked when the callee registers a method.|
|void off(method: string)|Callee.off: callback invoked when the callee deregisters a method.| |off(method: string): void|Callback invoked when the callee deregisters a method.|
|Promise\<void> call(method: string, data: rpc.Sequenceable)|Caller.call: sends agreed sequenceable data to the callee.| |call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee.|
|Promise\<rpc.MessageParcel> callWithResult(method: string, data: rpc.Sequenceable)|Caller.callWithResult: sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| |callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.|
|void release()|Caller.release: releases the caller interface.| |release(): void|Releases the caller interface.|
|void onRelease(callback: OnReleaseCallBack)|Caller.onRelease: registers a callback that is invoked when the caller is disconnected.| |onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.|
## How to Develop ## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. For details about the complete project code, see [Samples](#samples).
### Creating a Callee ### Creating a Callee
For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener. For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener.
1. Configure the ability startup mode. 1. Configure the ability startup mode.
...@@ -51,7 +57,7 @@ import Ability from '@ohos.application.Ability' ...@@ -51,7 +57,7 @@ import Ability from '@ohos.application.Ability'
``` ```
3. Define the agreed sequenceable data. 3. Define the agreed sequenceable data.
The data formats sent and received by the caller and callee must be consistent. In the following example, the data consists of numbers and strings. The sample code is as follows: The data formats sent and received by the caller and callee must be consistent. In the following example, the data consists of numbers and strings. The sample code snippet is as follows:
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0
...@@ -77,7 +83,7 @@ export default class MySequenceable { ...@@ -77,7 +83,7 @@ export default class MySequenceable {
``` ```
4. Implement **Callee.on** and **Callee.off**. 4. Implement **Callee.on** and **Callee.off**.
The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **CalleeSortMethod** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns them. You need to implement processing based on service requirements. The sample code is as follows: The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows:
```ts ```ts
const TAG: string = '[CalleeAbility]' const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
...@@ -121,7 +127,7 @@ import Ability from '@ohos.application.Ability' ...@@ -121,7 +127,7 @@ import Ability from '@ohos.application.Ability'
``` ```
2. Obtain the caller interface. 2. Obtain the caller interface.
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller interface of the ability. The following example uses **this.context** to obtain the **context** attribute of the **Ability** instance, uses **startAbilityByCall** to start the callee, obtain the caller interface, and register the **onRelease** listener of the caller. You need to implement processing based on service requirements. The sample code is as follows: The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller interface of the ability. The following example uses **this.context** to obtain the **context** attribute of the **Ability** instance, uses **startAbilityByCall** to start the callee, obtain the caller interface, and register the **onRelease** listener of the caller. You need to implement processing based on service requirements. The sample code snippet is as follows:
```ts ```ts
async onButtonGetCaller() { async onButtonGetCaller() {
try { try {
...@@ -142,7 +148,7 @@ async onButtonGetCaller() { ...@@ -142,7 +148,7 @@ async onButtonGetCaller() {
console.error(TAG + 'get caller failed with ' + error) console.error(TAG + 'get caller failed with ' + error)
}) })
``` ```
In the cross-device scenario, you need to specify the ID of the peer device. The sample code is as follows: In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows:
```ts ```ts
let TAG = '[MainAbility] ' let TAG = '[MainAbility] '
var caller = undefined var caller = undefined
...@@ -166,7 +172,7 @@ context.startAbilityByCall({ ...@@ -166,7 +172,7 @@ context.startAbilityByCall({
console.error(TAG + 'get remote caller failed with ' + error) console.error(TAG + 'get remote caller failed with ' + error)
}) })
``` ```
Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code is as follows: Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows:
```ts ```ts
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass; var dmClass;
...@@ -184,7 +190,7 @@ function getRemoteDeviceId() { ...@@ -184,7 +190,7 @@ function getRemoteDeviceId() {
} }
} }
``` ```
In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code is as follows: In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows:
```ts ```ts
let context = this.context let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'] let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
...@@ -196,7 +202,7 @@ context.requestPermissionsFromUser(permissions).then((data) => { ...@@ -196,7 +202,7 @@ context.requestPermissionsFromUser(permissions).then((data) => {
``` ```
3. Send agreed sequenceable data. 3. Send agreed sequenceable data.
The sequenceable data can be sent to the callee in either of the following ways: without a return value or obtaining data returned by the callee. The method and sequenceable data must be consistent with those of the callee. The following example describes how to invoke the **Call** API to send data to the callee. The sample code is as follows: The sequenceable data can be sent to the callee with or without a return value. The method and sequenceable data must be consistent with those of the callee. The following example describes how to invoke the **Call** API to send data to the callee. The sample code snippet is as follows:
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
async onButtonCall() { async onButtonCall() {
...@@ -209,7 +215,7 @@ async onButtonCall() { ...@@ -209,7 +215,7 @@ async onButtonCall() {
} }
``` ```
In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code is as follows: In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows:
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = '' originMsg: string = ''
...@@ -231,7 +237,7 @@ async onButtonCallWithResult(originMsg, backMsg) { ...@@ -231,7 +237,7 @@ async onButtonCallWithResult(originMsg, backMsg) {
``` ```
4. Release the caller interface. 4. Release the caller interface.
When the caller interface is no longer required, call the **release** API to release it. The sample code is as follows: When the caller interface is no longer required, call the **release** API to release it. The sample code snippet is as follows:
```ts ```ts
try { try {
this.caller.release() this.caller.release()
...@@ -242,9 +248,6 @@ try { ...@@ -242,9 +248,6 @@ try {
} }
``` ```
## Development Example ## Samples
The following sample is provided to help you better understand how to develop an ability call in the stage model: The following sample is provided to help you better understand how to develop an ability call in the stage model:
- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
[StageCallAbility](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
In this sample, the **AbilityStage** APIs are implemented in the **AbilityStage.ts** file in the **Application** directory, the **Ability** APIs are implemented in the **MainAbility** directory, and **pages/index** is the pages of the ability. Another ability and callee are implemented in the **CalleeAbility** directory, and its pages are the content configured in **pages/second**. The **MainAbility** functions as the caller, and the **CalleeAbility** functions as the callee. After starting the **CalleeAbility**, the **MainAbility** obtains the caller interface, processes the string entered by the user, and transfers the processed string to the **CalleeAbility**. The **CalleeAbility** refreshes the page based on the received data and returns the result to the **MainAbility**.
...@@ -54,7 +54,7 @@ They are organized as follows: ...@@ -54,7 +54,7 @@ They are organized as follows:
- [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md) - [Component Reference (JavaScript-based Web-like Development Paradigm)](reference/arkui-js/Readme-EN.md)
- [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md) - [Component Reference (TypeScript-based Declarative Development Paradigm)](reference/arkui-ts/Readme-EN.md)
- APIs - APIs
- [JS and TS APIs](reference/apis/Readme-CN.md) - [JS and TS APIs](reference/apis/Readme-EN.md)
- Native APIs - Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Node_API](reference/native-lib/third_party_napi/napi.md)
......
...@@ -9,16 +9,13 @@ You can set your application to call the **ReminderRequest** class to create sch ...@@ -9,16 +9,13 @@ You can set your application to call the **ReminderRequest** class to create sch
**reminderAgent** encapsulates the methods for publishing and canceling reminders. **reminderAgent** encapsulates the methods for publishing and canceling reminders.
**Table 1** Major APIs in reminderAgent **Table 1** Major APIs in reminderAgent
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\<number>): void;<br>function publishReminder(reminderReq: ReminderRequest): Promise\<number>; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. | | function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback\<number>): void;<br>function publishReminder(reminderReq: ReminderRequest): Promise\<number>; | Publishes a scheduled reminder.<br>The maximum number of valid notifications (excluding expired ones that will not pop up again) is 30 for one application and 2000 for the entire system. |
| function cancelReminder(reminderId: number, callback: AsyncCallback\<void>): void;<br/>function cancelReminder(reminderId: number): Promise\<void>; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.) | | function cancelReminder(reminderId: number, callback: AsyncCallback\<void>): void;<br/>function cancelReminder(reminderId: number): Promise\<void>; | Cancels a specified reminder. (The value of **reminderId** is obtained from the return value of **publishReminder**.) |
| function getValidReminders(callback: AsyncCallback<Array\<ReminderRequest>>): void;<br/>function getValidReminders(): Promise<Array\<ReminderRequest>>; | Obtains all valid reminders set by the current application. | | function getValidReminders(callback: AsyncCallback<Array\<ReminderRequest>>): void;<br/>function getValidReminders(): Promise<Array\<ReminderRequest>>; | Obtains all valid reminders set by the current application. |
| function cancelAllReminders(callback: AsyncCallback\<void>): void;<br/>function cancelAllReminders(): Promise\<void>; | Cancels all reminders set by the current application. | | function cancelAllReminders(callback: AsyncCallback\<void>): void;<br/>function cancelAllReminders(): Promise\<void>; | Cancels all reminders set by the current application. |
| function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\<void>): void;<br/>function addNotificationSlot(slot: NotificationSlot): Promise<void>; | Registers a NotificationSlot instance to be used by the reminder. | | function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback\<void>): void;<br/>function addNotificationSlot(slot: NotificationSlot): Promise\<void>; | Registers a NotificationSlot instance to be used by the reminder. |
| function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\<void>): void;function removeNotificationSlot(slotType: notification.SlotType): Promise\<void>; | Removes a NotificationSlot instance of a specified type. | | function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback\<void>): void;function removeNotificationSlot(slotType: notification.SlotType): Promise\<void>; | Removes a NotificationSlot instance of a specified type. |
**ActionButtonType** enumerates types of buttons displayed in a reminder notification. **ActionButtonType** enumerates types of buttons displayed in a reminder notification.
......
...@@ -41,7 +41,7 @@ If a service needs to be continued when the application or service module is run ...@@ -41,7 +41,7 @@ If a service needs to be continued when the application or service module is run
backgroundTaskManager.getRemainingDelayTime(id).then( res => { backgroundTaskManager.getRemainingDelayTime(id).then( res => {
console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
}).catch( err => { }).catch( err => {
console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.data); console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
}); });
``` ```
...@@ -74,7 +74,7 @@ console.info("The actualDelayTime is: " + time); ...@@ -74,7 +74,7 @@ console.info("The actualDelayTime is: " + time);
backgroundTaskManager.getRemainingDelayTime(id).then( res => { backgroundTaskManager.getRemainingDelayTime(id).then( res => {
console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
}).catch( err => { }).catch( err => {
console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.data); console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
}); });
// Cancel the suspension delay. // Cancel the suspension delay.
......
# IPC & RPC Development<a name="EN-US_TOPIC_0000001103710988"></a> # IPC & RPC Development
## When to Use<a name="section18502174174019"></a> ## When to Use
IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices. IPC/RPC enables a proxy and a stub that run on different processes to communicate with each other, regardless of whether they run on the same or different devices.
## Available APIs<a name="section1633115419401"></a> ## Available APIs
**Table 1** Native IPC APIs **Table 1** Native IPC APIs
<a name="table178849240013"></a> | Class/Interface | Function | Description |
<table><thead align="left"><tr id="row6884924608"><th class="cellrowborder" valign="top" width="14.12141214121412%" id="mcps1.2.4.1.1"><p id="p98846241706"><a name="p98846241706"></a><a name="p98846241706"></a>Class/Interface</p> | --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
</th> | IRemoteBroker | sptr\<IRemoteObject> AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. |
<th class="cellrowborder" valign="top" width="52.54525452545254%" id="mcps1.2.4.1.2"><p id="p1488482414020"><a name="p1488482414020"></a><a name="p1488482414020"></a>Function</p> | IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. |
</th> | IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. |
<th class="cellrowborder" valign="top" width="33.33333333333333%" id="mcps1.2.4.1.3"><p id="p388516244016"><a name="p388516244016"></a><a name="p388516244016"></a>Description</p>
</th> ## How to Develop
</tr>
</thead>
<tbody><tr id="row15885824402"><td class="cellrowborder" valign="top" width="14.12141214121412%" headers="mcps1.2.4.1.1 "><p id="p08859241008"><a name="p08859241008"></a><a name="p08859241008"></a>IRemoteBroker</p>
</td>
<td class="cellrowborder" valign="top" width="52.54525452545254%" headers="mcps1.2.4.1.2 "><p id="p388572412010"><a name="p388572412010"></a><a name="p388572412010"></a>sptr&lt;IRemoteObject&gt; AsObject()</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p13885724405"><a name="p13885724405"></a><a name="p13885724405"></a>Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of <strong id="b18927631105113"><a name="b18927631105113"></a><a name="b18927631105113"></a>IRemoteBroker</strong>. If you call this method on the stub, the <strong id="b7932163110519"><a name="b7932163110519"></a><a name="b7932163110519"></a>RemoteObject</strong> is returned; if you call this method on the proxy, the proxy object is returned.</p>
</td>
</tr>
<tr id="row138859241808"><td class="cellrowborder" valign="top" width="14.12141214121412%" headers="mcps1.2.4.1.1 "><p id="p1888515245012"><a name="p1888515245012"></a><a name="p1888515245012"></a>IRemoteStub</p>
</td>
<td class="cellrowborder" valign="top" width="52.54525452545254%" headers="mcps1.2.4.1.2 "><p id="p1388516240011"><a name="p1388516240011"></a><a name="p1388516240011"></a>virtual int OnRemoteRequest(uint32_t code, MessageParcel &amp;data, MessageParcel &amp;reply, MessageOption &amp;option)</p>
</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p1188582414016"><a name="p1188582414016"></a><a name="p1188582414016"></a>Called to process a request from the proxy and return the result. Derived classes need to override this method.</p>
</td>
</tr>
<tr id="row108856241904"><td class="cellrowborder" valign="top" width="14.12141214121412%" headers="mcps1.2.4.1.1 "><p id="p6885924609"><a name="p6885924609"></a><a name="p6885924609"></a>IRemoteProxy</p>
</td>
<td class="cellrowborder" valign="top" width="52.54525452545254%" headers="mcps1.2.4.1.2 ">&nbsp;&nbsp;</td>
<td class="cellrowborder" valign="top" width="33.33333333333333%" headers="mcps1.2.4.1.3 "><p id="p688592413018"><a name="p688592413018"></a><a name="p688592413018"></a>Service proxy classes are derived from the <strong id="b169739356519"><a name="b169739356519"></a><a name="b169739356519"></a>IRemoteProxy</strong> class.</p>
</td>
</tr>
</tbody>
</table>
## How to Develop<a name="section4207112818418"></a>
**Using Native APIs** **Using Native APIs**
...@@ -60,7 +34,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ...@@ -60,7 +34,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
2. Define and implement service provider **TestAbilityStub**. 2. Define and implement service provider **TestAbilityStub**.
This class is related to the IPC framework and needs to inherit **IRemoteStub<ITestAbility\>**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy. This class is related to the IPC framework and needs to inherit **IRemoteStub\<ITestAbility>**. You need to override **OnRemoteRequest** on the stub to receive requests from the proxy.
``` ```
class TestAbilityStub : public IRemoteStub<ITestAbility> { class TestAbilityStub : public IRemoteStub<ITestAbility> {
...@@ -100,7 +74,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ...@@ -100,7 +74,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
4. Define and implement **TestAbilityProxy**. 4. Define and implement **TestAbilityProxy**.
This class is implemented on the proxy and inherits **IRemoteProxy<ITestAbility\>**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub. This class is implemented on the proxy and inherits **IRemoteProxy\<ITestAbility>**. You can call **SendRequest** to send a request to the stub and expose the capabilities provided by the stub.
``` ```
class TestAbilityProxy : public IRemoteProxy<ITestAbility> { class TestAbilityProxy : public IRemoteProxy<ITestAbility> {
...@@ -157,5 +131,3 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ...@@ -157,5 +131,3 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat
sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(sdid, deviceId); // deviceId identifies a device. sptr<IRemoteObject> remoteObject = samgr->GetSystemAbility(sdid, deviceId); // deviceId identifies a device.
sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy. sptr<TestAbilityProxy> proxy(new TestAbilityProxy(remoteObject)); // Construct a proxy.
``` ```
\ No newline at end of file
# Audio Capture Development # Audio Capture Development
--- ## When to Use
## ***Note***:
1. This document applies to JavaScript. You can use the APIs provided by **AudioCapturer** to record raw audio files.
---
## **Summary** ### State Check
This guide will show how a JS application can use AudioCapturer to record the audio.
Applications can use the APIs provided in this document to record raw audio files. During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioCapturer** instance. This is because some operations can be performed only when the audio capturer is in a given state. If the application performs an operation when the audio capturer is not in the given state, the system may throw an exception or generate other undefined behavior.
## **AudioCapturer Framework** For details about the APIs, see [AudioCapturer in Audio Management](../reference/apis/js-apis-audio.md).
The AudioCapturer interface is one of the most important components of the audio framework.
### **Audio Capturing:** **Figure 1** Audio capturer state
The AudioCapturer framework provides APIs for capturing raw audio files.
![](figures/audio-capturer-state.png)
## **Usage**
Here's an example of how to use AudioCapturer to capture a raw audio file. ## How to Develop
1. Use **createAudioCapturer()** to create an AudioCapturer instance. Capturer parameters can be set in **audioCapturerOptions**.\
This instance can be used to record, control, and obtain the recording status, as well as to register a callback for notifications. 1. Use **createAudioCapturer()** to create an **AudioCapturer** instance.
```
Set parameters of the **AudioCapturer** instance in **audioCapturerOptions**. This instance is used to capture audio, control and obtain the recording status, and register a callback for notification.
```js
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
...@@ -39,10 +42,10 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -39,10 +42,10 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
var state = audioRenderer.state; var state = audioRenderer.state;
``` ```
2. (Optional) Subscribe to audio capturer state change events using the **on('stateChange')** API. 2. (Optional) Use **on('stateChange')** to subscribe to audio renderer state changes.
If an application wants to take some action based on the state updates in capturer, the application can subscribe to the state change event. If an application needs to perform some operations when the audio renderer state is updated, the application can subscribe to the state changes. For more events that can be subscribed to, see [Audio Management](../reference/apis/js-apis-audio.md).
There are more events that applications can subscribe to, such as 'markReach' and 'periodReach'. Refer to [Audio](../reference/apis/js-apis-audio.md) for more details.
``` ```js
audioCapturer.on('stateChange',(state) => { audioCapturer.on('stateChange',(state) => {
console.info('AudioCapturerLog: Changed State to : ' + state) console.info('AudioCapturerLog: Changed State to : ' + state)
switch (state) { switch (state) {
...@@ -68,31 +71,33 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -68,31 +71,33 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
break; break;
} }
}); });
``` ```
3. Call the **start()** function on the AudioCapturer instance to start/resume the recording task.\ 3. Use **start()** to start audio recording.
The capturer state will be STATE_RUNNING once the start is complete. The application can then begin reading buffers.
``` The capturer state will be **STATE_RUNNING** once the audio capturer is started. The application can then begin reading buffers.
```js
await audioCapturer.start(); await audioCapturer.start();
if (audioCapturer.state == audio.AudioState.STATE_RUNNING) { if (audioCapturer.state == audio.AudioState.STATE_RUNNING) {
console.info('AudioRecLog: Capturer started'); console.info('AudioRecLog: Capturer started');
} else { } else {
console.info('AudioRecLog: Capturer start failed'); console.info('AudioRecLog: Capturer start failed');
} }
``` ```
4. Obtain the minimum buffer size to read using the **getBufferSize()** API. 4. Use **getBufferSize()** to obtain the minimum buffer size to read.
```
```js
var bufferSize = await audioCapturer.getBufferSize(); var bufferSize = await audioCapturer.getBufferSize();
console.info('AudioRecLog: buffer size: ' + bufferSize); console.info('AudioRecLog: buffer size: ' + bufferSize);
``` ```
5. Read the captured audio data and convert it to a byte stream. Call the **read()** API repeatedly to read the data 5. Read the captured audio data and convert it to a byte stream. Call **read()** repeatedly to read the data until the application wants to stop the recording.
until the application wants to stop the recording. The following example shows how to write recorded data into a file.
``` The following example shows how to write recorded data into a file.
```js
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
const path = '/data/data/.pulse_dir/capture_js.wav'; const path = '/data/data/.pulse_dir/capture_js.wav';
...@@ -123,7 +128,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -123,7 +128,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
numBuffersToCapture--; numBuffersToCapture--;
} }
``` ```
6. Once the recording is complete, call the **stop()** API on the AudioCapturer instance to stop the recording.
6. Once the recording is complete, call **stop()** to stop the recording.
``` ```
await audioCapturer.stop(); await audioCapturer.stop();
if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { if (audioCapturer.state == audio.AudioState.STATE_STOPPED) {
...@@ -133,8 +140,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -133,8 +140,9 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
} }
``` ```
7. After the recording task is complete, call the **release()** API on the AudioCapturer instance to release the stream resources. 7. After the task is complete, call **release()** to release related resources.
```
```js
await audioCapturer.release(); await audioCapturer.release();
if (audioCapturer.state == audio.AudioState.STATE_RELEASED) { if (audioCapturer.state == audio.AudioState.STATE_RELEASED) {
console.info('AudioRecLog: Capturer released'); console.info('AudioRecLog: Capturer released');
...@@ -142,11 +150,3 @@ Here's an example of how to use AudioCapturer to capture a raw audio file. ...@@ -142,11 +150,3 @@ Here's an example of how to use AudioCapturer to capture a raw audio file.
console.info('AudioRecLog: Capturer release failed'); console.info('AudioRecLog: Capturer release failed');
} }
``` ```
## **Importance of State Check**
Application developers should keep in mind that an AudioCapturer is state-based.
That is, the AudioCapturer has an internal state that the application must always check when calling recorder control APIs, because some operations are only acceptable while the capturer is in a given state.\
The system may throw an error/exception or generate other undefined behaviour if the application performs an operation while capturer is in an improper state.
## **Other APIs**
See [AudioCapturer in the Audio API](../reference/apis/js-apis-audio.md) for more useful APIs like **getAudioTime**, **getCapturerInfo** and **getStreamInfo**.
# Audio Rendering Development # Audio Rendering Development
--- ## When to Use
## ***Note***:
1. This document applies to JavaScript. **AudioRenderer** provides APIs for rendering audio files and controlling playback. It also supports audio interruption. You can use the APIs provided by **AudioRenderer** to play audio files in output devices and manage playback tasks.
---
## **Summary** ### Audio Interruption
This guide will show you how to use AudioRenderer to create an audio player app.
You can use the APIs provided in this document to play audio files in output devices and manage playback tasks. When an audio stream with a higher priority needs to be played, the audio renderer interrupts the stream with a lower priority. For example, if a call comes in when the user is listening to music, the music playback, which is the lower priority stream, is paused. For details, see [How to Develop](#how-to-develop).
## **AudioRenderer Framework** ### State Check
The AudioRenderer interface is one of the most important components of the audio framework.
### **Audio Rendering:** During application development, you are advised to use **on('stateChange')** to subscribe to state changes of the **AudioRenderer** instance. This is because some operations can be performed only when the audio renderer is in a given state. If the application performs an operation when the audio renderer is not in the given state, the system may throw an exception or generate other undefined behavior.
The AudioRenderer framework provides APIs for playing audio files and controlling the playback.
### **Audio Interruption:** **Figure 1** Audio renderer state
When a higher priority stream wants to play, the AudioRenderer framework interrupts the lower priority stream.\
For example, if a call is arrived when you listen to music, the music playback, which is the lower priority stream, is paused.\ ![](figures/audio-renderer-state.png)
With the sample code below, we'll look at how AudioInterrupt works in detail.\
<br/> ### Asynchronous Operations
Please see [AudioRenderer in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8) for a list of supported audio stream types and formats, such as AudioSampleFormat, AudioChannel, AudioSampleFormat, and AudioEncodingType.
To ensure that the UI thread is not blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions. For more information, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
## **Usage**
Here's an example of how to use AudioRenderer to play a raw audio file.
1. Use **createAudioRenderer** to create an AudioRenderer instance. Renderer parameters can be set in **audioRendererOptions**.\ ## How to Develop
This object can be used to play, control, and obtain the status of the playback, as well as receive callback notifications.
``` 1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.
Set parameters of the audio renderer in **audioCapturerOptions**. This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.
```js
var audioStreamInfo = { var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1, channels: audio.AudioChannel.CHANNEL_1,
...@@ -46,48 +49,15 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -46,48 +49,15 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
``` ```
2. Subscribe to audio interruption events using the **on** API.\ 2. Use **on('interrupt')** to subscribe to audio interruption events.
Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.\
In some cases, the framework takes forced actions like pausing and ducking, and notifies the app using **InterruptEvent**. In other cases, the app can take action. In this situation, the app can choose to act on the **InterruptEvent** or ignore it. When the app is interrupted by forced action, it should handle the state, update the user interface, and so on.
In case of audio interrupts, the app may encounter write failures. Interrupt unaware apps can check the renderer state using the **audioRenderer.state** API before writing audio data, whereas interrupt aware apps will have more details accessible via this listener.\
<br/>
The following information will be provided by the Interrupt Event Notification:
1) **eventType:** Whether the interruption has begun or ended.
| Value | Description |
| :------------------- | :-------------------------------------------- |
| INTERRUPT_TYPE_BEGIN | Indicates that the interruption has started. |
| INTERRUPT_TYPE_END | Indicates that the interruption has finished. |
2) **forceType:** Whether the framework has already taken action or if the app is being suggested to take action.
| Value | Description | Stream-A is interrupted when Stream-B with a higher or equal priority requests to become active and use the output device.
| :-------------- | :------------------------------------------------------------------ |
| INTERRUPT_FORCE | The audio state has been changed by the framework. |
| INTERRUPT_SHARE | The app can decide whether or not to respond to the InterruptEvent. |
3) **hintType:** The kind of action taken or to be taken. In some cases, the audio renderer performs forcible operations such as pausing and ducking, and notifies the application through **InterruptEvent**. In other cases, the application can choose to act on the **InterruptEvent** or ignore it.
| Value | Description | In the case of audio interruption, the application may encounter write failures. To avoid such failures, interruption unaware applications can use **audioRenderer.state** to check the renderer state before writing audio data. The applications can obtain more details by subscribing to the audio interruption events. For details, see [InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9).
| :-------------------- | :--------------------------- |
| INTERRUPT_HINT_PAUSE | Pausing the playback. |
| INTERRUPT_HINT_RESUME | Resuming the playback. |
| INTERRUPT_HINT_STOP | Stopping the playback. |
| INTERRUPT_HINT_DUCK | Ducking the stream volume. |
| INTERRUPT_HINT_UNDUCK | Unducking the stream volume. |
4) **Some actions are exclusively forced or shared**, which means that they are performed by either the framework or the app.\ ```js
For instance, when a call is received while a music stream is ongoing, the framework forces the music stream to pause. When the call is finished, the framework will not forcibly resume the music stream. Instead, it will alert the app to resume the playback.
| Action | Description |
| :-------------------- | :-------------------------------------------------------------------------------- |
| INTERRUPT_HINT_RESUME | INTERRUPT_SHARE is always the forceType. It can only be done by the app. |
| INTERRUPT_HINT_DUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. |
| INTERRUPT_HINT_UNDUCK | INTERRUPT_FORCE is always the forceType. It will always be done by the framework. |
```
audioRenderer.on('interrupt', (interruptEvent) => { audioRenderer.on('interrupt', (interruptEvent) => {
console.info('InterruptEvent Received'); console.info('InterruptEvent Received');
console.info('InterruptType: ' + interruptEvent.eventType); console.info('InterruptType: ' + interruptEvent.eventType);
...@@ -133,12 +103,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -133,12 +103,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
}); });
``` ```
4. Call the **start()** function on the AudioRenderer instance to start/resume the playback task.\ 3. Use **start()** to start audio rendering.
The renderer state will be STATE_RUNNING once the start is complete. You can then begin writing buffers.
``` The renderer state will be **STATE_RUNNING** once the audio renderer is started. The application can then begin reading buffers.
```js
async function startRenderer() { async function startRenderer() {
var state = audioRenderer.state; var state = audioRenderer.state;
// state should be prepared, paused or stopped. // The state should be prepared, paused, or stopped.
if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED ||
state != audio.AudioState.STATE_STOPPED) { state != audio.AudioState.STATE_STOPPED) {
console.info('Renderer is not in a correct state to start'); console.info('Renderer is not in a correct state to start');
...@@ -154,11 +126,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -154,11 +126,13 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
console.error('Renderer start failed'); console.error('Renderer start failed');
} }
} }
```
5. Make **write** calls to start rendering the buffers.
Read the audio data to be played into a buffer. Call the write function repeatedly to write data.
``` ```
4. Call **write()** to write data to the buffer.
Read the audio data to be played to the buffer. Call **write()** repeatedly to write the data to the buffer.
```js
async function writeBuffer(buf) { async function writeBuffer(buf) {
var state = audioRenderer.state; var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) { if (state != audio.AudioState.STATE_RUNNING) {
...@@ -201,8 +175,9 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -201,8 +175,9 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
} , 30); // interval to be set based on audio file format } , 30); // interval to be set based on audio file format
``` ```
6. (Optional) Call the **pause()** or **stop()** function on the AudioRenderer instance. 5. (Optional) Call **pause()** or **stop()** to pause or stop rendering.
```
```js
async function pauseRenderer() { async function pauseRenderer() {
var state = audioRenderer.state; var state = audioRenderer.state;
if (state != audio.AudioState.STATE_RUNNING) { if (state != audio.AudioState.STATE_RUNNING) {
...@@ -235,12 +210,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -235,12 +210,14 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
} else { } else {
console.error('Renderer stop failed'); console.error('Renderer stop failed');
} }
} }
``` ```
7. After the playback task is complete, call the **release()** function on the AudioRenderer instance to release resources.\ 6. After the task is complete, call **release()** to release related resources.
AudioRenderer can use a lot of system resources. As a result, whenever the resources are no longer required, they must be released. To ensure that any system resources allocated to it are appropriately released, you should always call **release()**.
``` **AudioRenderer** uses a large number of system resources. Therefore, ensure that the resources are released after the task is complete.
```js
async function releaseRenderer() { async function releaseRenderer() {
if (state_ == RELEASED || state_ == NEW) { if (state_ == RELEASED || state_ == NEW) {
console.info('Resourced already released'); console.info('Resourced already released');
...@@ -257,18 +234,6 @@ Here's an example of how to use AudioRenderer to play a raw audio file. ...@@ -257,18 +234,6 @@ Here's an example of how to use AudioRenderer to play a raw audio file.
} }
} }
``` ```
## **Importance of State Check:**
You should also keep in mind that an AudioRenderer is state-based.
That is, the AudioRenderer has an internal state that you must always check when calling playback control APIs, because some operations are only acceptable while the renderer is in a given state.\
The system may throw an error/exception or generate other undefined behaviour if you perform an operation while in the improper state.\
## **Asynchronous Operations:**
Most of the AudioRenderer calls are asynchronous. As a result, the UI thread will not be blocked.\
For each API, the framework provides both callback and promises functions.\
In the example, promise functions are used for simplicity. [AudioRender in the Audio API](../reference/apis/js-apis-audio.md#audiorenderer8)
provides reference for both callback and promise.
## **Other APIs:**
See [Audio](../reference/apis/js-apis-audio.md) for more useful APIs like getAudioTime, drain, and getBufferSize.
# Native APIs # Native APIs
- [Using Native APIs in Application Projects](napi-guidelines.md) - [Using Native APIs in Application Projects](napi-guidelines.md)
- [Drawing Development](drawing-guidelines.md)
- [Raw File Development](rawfile-guidelines.md) - [Raw File Development](rawfile-guidelines.md)
# Drawing Development
## When to Use
The Native Drawing module provides APIs for drawing 2D graphics and text. The following scenarios are common for drawing development:
* Drawing 2D graphics
* Drawing and painting text
## Available APIs
| API| Description|
| -------- | -------- |
| OH_Drawing_BitmapCreate (void) | Creates a bitmap object.|
| OH_Drawing_BitmapBuild (OH_Drawing_Bitmap *, const uint32_t width, const uint32_t height, const OH_Drawing_BitmapFormat *) | Initializes the width and height of a bitmap object and sets the pixel format for the bitmap.|
| OH_Drawing_CanvasCreate (void) | Creates a canvas object.|
| OH_Drawing_CanvasBind (OH_Drawing_Canvas *, OH_Drawing_Bitmap *) | Binds a bitmap to a canvas so that the content drawn on the canvas is output to the bitmap (this process is called CPU rendering).|
| OH_Drawing_CanvasAttachBrush (OH_Drawing_Canvas *, const OH_Drawing_Brush *) | Attaches a brush to a canvas so that the canvas will use the style and color of the brush to fill in a shape.|
| OH_Drawing_CanvasAttachPen (OH_Drawing_Canvas *, const OH_Drawing_Pen *) | Attaches a pen to a canvas so that the canvas will use the style and color of the pen to outline a shape.|
| OH_Drawing_CanvasDrawPath (OH_Drawing_Canvas *, const OH_Drawing_Path *) | Draws a path.|
| OH_Drawing_PathCreate (void) | Creates a path object.|
| OH_Drawing_PathMoveTo (OH_Drawing_Path *, float x, float y) | Sets the start point of a path.|
| OH_Drawing_PathLineTo (OH_Drawing_Path *, float x, float y) | Draws a line segment from the last point of a path to the target point. |
| OH_Drawing_PathClose (OH_Drawing_Path *) | Closes a path. A line segment from the start point to the last point of the path is added.|
| OH_Drawing_PenCreate (void) | Creates a pen object.|
| OH_Drawing_PenSetAntiAlias (OH_Drawing_Pen *, bool) | Checks whether anti-aliasing is enabled for a pen. If anti-aliasing is enabled, edges will be drawn with partial transparency.|
| OH_Drawing_PenSetWidth (OH_Drawing_Pen *, float width) | Sets the thickness for a pen. This thickness determines the width of the outline of a shape.|
| OH_Drawing_BrushCreate (void) | Creates a brush object.|
| OH_Drawing_BrushSetColor (OH_Drawing_Brush *, uint32_t color) | Sets the color for a brush. The color will be used by the brush to fill in a shape.|
| OH_Drawing_CreateTypographyStyle (void) | Creates a `TypographyStyle` object.|
| OH_Drawing_CreateTextStyle (void) | Creates a `TextStyle` object.|
| OH_Drawing_TypographyHandlerAddText (OH_Drawing_TypographyCreate *, const char *) | Sets the text content.|
| OH_Drawing_TypographyPaint (OH_Drawing_Typography *, OH_Drawing_Canvas *, double, double) | Paints text on the canvas.|
## Development Procedure for 2D Graphics Drawing
The following steps describe how to use the canvas and brush of the Native Drawing module to draw a 2D graphics.
1. **Create a bitmap object.** Use `OH_Drawing_BitmapCreate` in `drawing_bitmap.h` to create a bitmap object (named `cBitmap` in this example), and use `OH_Drawing_BitmapBuild` to specify its length, width, and pixel format.
```c++
// Create a bitmap object.
OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate();
// Define the pixel format of the bitmap.
OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUYE};
// Set the pixel format for the bitmap.
OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat);
```
2. **Create a canvas object.** Use `OH_Drawing_CanvasCreate` in `drawing_canvas.h` to create a canvas object (named `cCanvas` in this example), and use `OH_Drawing_CanvasBind` to bind `cBitmap` to this canvas. The content drawn on the canvas will be output to the bound `cBitmap` object.
```c++
// Create a canvas object.
OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate();
// Bind the bitmap to the canvas. The content drawn on the canvas will be output to the bound bitmap memory.
OH_Drawing_CanvasBind(cCanvas, cBitmap);
// Use white to clear the canvas.
OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
```
3. **Construct a shape.** Use the APIs provided in `drawing_path.h` to draw a pentagram `cPath`.
```c++
int len = 300;
float aX = 500;
float aY = 500;
float dX = aX - len * std::sin(18.0f);
float dY = aY + len * std::cos(18.0f);
float cX = aX + len * std::sin(18.0f);
float cY = dY;
float bX = aX + (len / 2.0);
float bY = aY + std::sqrt((cX - dX) * (cX - dX) + (len / 2.0) * (len / 2.0));
float eX = aX - (len / 2.0);
float eY = bY;
// Create a path object and use the APIs to draw a pentagram.
OH_Drawing_Path* cPath = OH_Drawing_PathCreate();
// Specify the start point of the path.
OH_Drawing_PathMoveTo(cPath, aX, aY);
// Draw a line segment from the last point of a path to the target point.
OH_Drawing_PathLineTo(cPath, bX, bY);
OH_Drawing_PathLineTo(cPath, cX, cY);
OH_Drawing_PathLineTo(cPath, dX, dY);
OH_Drawing_PathLineTo(cPath, eX, eY);
// Close the path. Now the path is drawn.
OH_Drawing_PathClose(cPath);
```
4. **Set the brush and pen styles.** Use `OH_Drawing_PenCreate` in `drawing_pen.h` to create a pen (named `cPen` in this example), and set the attributes such as the anti-aliasing, color, and thickness. The pen is used to outline a shape. Use `OH_Drawing_BrushCreate` in `drawing_brush.h` to create a brush (named `cBrush` in this example), and set the brush color. The brush is used to fill in a shape. Use `OH_Drawing_CanvasAttachPen` and `OH_Drawing_CanvasAttachBrush` in `drawing_canvas.h` to attach the pen and brush to the canvas.
```c++
// Create a pen object and set the anti-aliasing, color, and thickness.
OH_Drawing_Pen* cPen = OH_Drawing_PenCreate();
OH_Drawing_PenSetAntiAlias(cPen, true);
OH_Drawing_PenSetColor(cPen, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0x00, 0x00));
OH_Drawing_PenSetWidth(cPen, 10.0);
OH_Drawing_PenSetJoin(cPen, LINE_ROUND_JOIN);
// Attach the pen to the canvas.
OH_Drawing_CanvasAttachPen(cCanvas, cPen);
// Create a brush object and set the color.
OH_Drawing_Brush* cBrush = OH_Drawing_BrushCreate();
OH_Drawing_BrushSetColor(cBrush, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0xFF, 0x00));
// Attach the brush to the canvas.
OH_Drawing_CanvasAttachBrush(cCanvas, cBrush);
```
5. **Draw a shape.** Use `OH_Drawing_CanvasDrawPath` in `drawing_canvas.h` to draw a pentagram on the canvas. Call the corresponding APIs to destroy the objects when they are no longer needed.
```c++
// Draw a pentagram on the canvas. The outline of the pentagram is drawn by the pen, and the color is filled in by the brush.
OH_Drawing_CanvasDrawPath(cCanvas, cPath);
// Destroy the created objects when they are no longer needed.
OH_Drawing_BrushDestory(cBrush);
OH_Drawing_PenDestory(cPen);
OH_Drawing_PathDestory(cPath);
```
6. **Obtain pixel data.** Use `OH_Drawing_BitmapGetPixels` in `drawing_bitmap.h` to obtain the pixel address of the bitmap bound to the canvas. The memory to which the address points contains the pixel data of the drawing on the canvas.
```c++
// Obtain the pixel address after drawing. The memory to which the address points contains the pixel data of the drawing on the canvas.
void* bitmapAddr = OH_Drawing_BitmapGetPixels(cBitmap);
auto ret = memcpy_s(addr, addrSize, bitmapAddr, addrSize);
if (ret != EOK) {
LOGI("memcpy_s failed");
}
// Destroy the canvas object.
OH_Drawing_CanvasDestory(cCanvas);
// Destroy the bitmap object.
OH_Drawing_BitmapDestory(cBitmap);
```
## Development Procedure for Text Drawing and Display
The following steps describe how to use the text drawing and display feature of the Native Drawing module.
1. **Create a canvas and a bitmap.**
```c++
// Create a bitmap.
OH_Drawing_Bitmap* cBitmap = OH_Drawing_BitmapCreate();
OH_Drawing_BitmapFormat cFormat {COLOR_FORMAT_RGBA_8888, ALPHA_FORMAT_OPAQUE};
OH_Drawing_BitmapBuild(cBitmap, width, height, &cFormat);
// Create a canvas.
OH_Drawing_Canvas* cCanvas = OH_Drawing_CanvasCreate();
OH_Drawing_CanvasBind(cCanvas, cBitmap);
OH_Drawing_CanvasClear(cCanvas, OH_Drawing_ColorSetArgb(0xFF, 0xFF, 0xFF, 0xFF));
```
2. **Set the typography style.**
```c++
// Set the typography attributes such as left to right (LTR) for the text direction and left-aligned for the text alignment mode.
OH_Drawing_TypographyStyle* typoStyle = OH_Drawing_CreateTypographyStyle();
OH_Drawing_SetTypographyTextDirection(typoStyle, TEXT_DIRECTION_LTR);
OH_Drawing_SetTypographyTextAlign(typoStyle, TEXT_ALIGN_LEFT);
```
3. **Set the text style.**
```c++
// Set the text color, for example, black.
OH_Drawing_TextStyle* txtStyle = OH_Drawing_CreateTextStyle();
OH_Drawing_SetTextStyleColor(txtStyle, OH_Drawing_ColorSetArgb(0xFF, 0x00, 0x00, 0x00));
// Set text attributes such as the font size and weight.
double fontSize = 30;
OH_Drawing_SetTextStyleFontSize(txtStyle, fontSize);
OH_Drawing_SetTextStyleFontWeight(txtStyle, FONT_WEIGHT_400);
OH_Drawing_SetTextStyleBaseLine(txtStyle, TEXT_BASELINE_ALPHABETIC);
OH_Drawing_SetTextStyleFontHeight(txtStyle, 1);
// Set the font families.
const char* fontFamilies[] = {"Roboto"};
OH_Drawing_SetTextStyleFontFamilies(txtStyle, 1, fontFamilies);
OH_Drawing_SetTextStyleFontStyle(txtStyle, FONT_STYLE_NORMAL);
OH_Drawing_SetTextStyleLocale(txtStyle, "en");
```
4. **Generate the final text display effect.**
```c++
OH_Drawing_TypographyCreate* handler = OH_Drawing_CreateTypographyHandler(typoStyle,
OH_Drawing_CreateFontCollection());
OH_Drawing_TypographyHandlerPushTextStyle(handler, txtStyle);
// Set the text content.
const char* text = "OpenHarmony\n";
OH_Drawing_TypographyHandlerAddText(handler, text);
OH_Drawing_TypographyHandlerPopTextStyle(handler);
OH_Drawing_Typography* typography = OH_Drawing_CreateTypography(handler);
// Set the maximum width.
double maxWidth = 800.0;
OH_Drawing_TypographyLayout(typography, maxWidth);
// Set the start position for text display.
double position[2] = {10.0, 15.0};
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]);
```
## Samples
The following samples are provided to help you better understand how to use the Native Drawing module:
* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp)
* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp)
...@@ -4,7 +4,7 @@ ...@@ -4,7 +4,7 @@
## When to Use ## When to Use
This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. The table below describes the APIs. This document describes how to use the native Rawfile APIs to manage raw file directories and files in OpenHarmony. You can use the APIs to traverse, open, search for, read, and close raw files.
## Available APIs ## Available APIs
...@@ -16,14 +16,14 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -16,14 +16,14 @@ This document describes how to use the native Rawfile APIs to manage raw file di
| const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file. | | const char *OH_ResourceManager_GetRawFileName(RawDir *rawDir, int index) | Obtains the name of a raw file. |
| RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file. | | RawFile *OH_ResourceManager_OpenRawFile(const NativeResourceManager *mgr, const char *fileName) | Opens a raw file. |
| long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a raw file. | | long OH_ResourceManager_GetRawFileSize(RawFile *rawFile) | Obtains the size of a raw file. |
| int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a data read/write position in a raw file based on the specified offset. | | int OH_ResourceManager_SeekRawFile(const RawFile *rawFile, long offset, int whence) | Seeks a read/write position in a raw file based on the specified offset. |
| long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset. | | long OH_ResourceManager_GetRawFileOffset(const RawFile *rawFile) | Obtains the offset. |
| int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file. | | int OH_ResourceManager_ReadRawFile(const RawFile *rawFile, void *buf, size_t length) | Reads a raw file. |
| void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a raw file to release resources. | | void OH_ResourceManager_CloseRawFile(RawFile *rawFile) | Closes a raw file to release resources. |
| void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a raw file directory to release resources. | | void OH_ResourceManager_CloseRawDir(RawDir *rawDir) | Closes a raw file directory to release resources. |
| bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file description (FD) of a raw file. | | bool OH_ResourceManager_GetRawFileDescriptor(const RawFile *rawFile, RawFileDescriptor &descriptor) | Obtains the file descriptor (FD) of a raw file. |
| bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file. | | bool OH_ResourceManager_ReleaseRawFileDescriptor(const RawFileDescriptor &descriptor) | Releases the FD of a raw file. |
| void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases native resource manager resources. | | void OH_ResourceManager_ReleaseNativeResourceManager(NativeResourceManager *resMgr) | Releases the native resource manager. |
## How to Develop ## How to Develop
...@@ -38,7 +38,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -38,7 +38,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
2. Call **OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)** to obtain a **NativeResourceManager** instance. 2. Call **OH_ResourceManager_InitNativeResourceManager(napi_env env, napi_value jsResMgr)** to obtain a **NativeResourceManager** instance.
```js ```js
// Call the JS API to pass the JS resource manager. // Import the JS resource manager from the JS head file and pass it to the C++ file.
import resManager from '@ohos.resourceManager' import resManager from '@ohos.resourceManager'
import rawfileTest from 'librawFileTest.so' import rawfileTest from 'librawFileTest.so'
resManager.getResourceManager().then(resmgr => { resManager.getResourceManager().then(resmgr => {
...@@ -49,7 +49,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -49,7 +49,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
``` ```
```c++ ```c++
// The C++ API obtains and parses the parameters passed by the JS API. // Obtain and parse the parameters in the C++ file.
NativeResourceManager* nativeResourceManager = nullptr; NativeResourceManager* nativeResourceManager = nullptr;
std::string path; std::string path;
if (i == 0 && valueType == napi_string) { if (i == 0 && valueType == napi_string) {
...@@ -57,7 +57,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -57,7 +57,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
...... ......
path = buf.data(); path = buf.data();
} else if (i == 1 && valueType == napi_object) { } else if (i == 1 && valueType == napi_object) {
// Parse the second parameter, which is the resource manager. // Parse the second parameter, which is the JS resource manager.
nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]); nativeResourceManager = OH_ResourceManager_InitNativeResourceManager(env, argv[i]);
} }
``` ```
...@@ -80,7 +80,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -80,7 +80,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file based on the specified index. 5. Call **OH_ResourceManager_GetRawFileName** to obtain the name of the raw file with the specified index.
```c++ ```c++
for (int index = 0; index < count; index++) { for (int index = 0; index < count; index++) {
...@@ -90,7 +90,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -90,7 +90,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance based on the specified file name. 6. Call **OH_ResourceManager_OpenRawFile** to obtain a **RawFile** instance with the specified file name.
```c++ ```c++
RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str()); RawFile* rawFile = OH_ResourceManager_OpenRawFile(nativeResourceManager, fileName.c_str());
...@@ -106,7 +106,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -106,7 +106,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
8. Call **OH_ResourceManager_SeekRawFile** to seek a data read/write position in the raw file based on the specified offset. 8. Call **OH_ResourceManager_SeekRawFile** to seek a read/write position in the raw file based on the specified offset.
```c++ ```c++
int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0); int position = OH_ResourceManager_SeekRawFile(rawFile, 10, 0);
...@@ -124,7 +124,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -124,7 +124,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
10. Call **OH_ResourceManager_ReadRawFile** to read a raw file. 10. Call **OH_ResourceManager_ReadRawFile** to read the raw file.
```c++ ```c++
std::unique_ptr<char[]> mediaData = std::make_unique<char[]>(rawFileSize); std::unique_ptr<char[]> mediaData = std::make_unique<char[]>(rawFileSize);
...@@ -149,7 +149,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di ...@@ -149,7 +149,7 @@ This document describes how to use the native Rawfile APIs to manage raw file di
13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain **RawFileDescriptor** of the raw file. 13. Call **OH_ResourceManager_GetRawFileDescriptor** to obtain the FD of the raw file.
```c++ ```c++
RawFileDescriptor descriptor; RawFileDescriptor descriptor;
......
...@@ -25,13 +25,13 @@ You can create a subscriber object to subscribe to a common event to obtain the ...@@ -25,13 +25,13 @@ You can create a subscriber object to subscribe to a common event to obtain the
### How to Develop ### How to Develop
1. Import the **commonEvent** module. 1. Import the **commonEvent** module.
```javascript ```js
import commonEvent from '@ohos.commonEvent'; import commonEvent from '@ohos.commonEvent';
``` ```
2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo). 2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo).
```javascript ```js
private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription. private subscriber = null // Used to save the created subscriber object for subsequent subscription and unsubscription.
// Subscriber information // Subscriber information
...@@ -42,7 +42,7 @@ var subscribeInfo = { ...@@ -42,7 +42,7 @@ var subscribeInfo = {
3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription. 3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription.
```javascript ```js
// Callback for subscriber creation. // Callback for subscriber creation.
commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
if (err.code) { if (err.code) {
...@@ -57,7 +57,7 @@ commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => { ...@@ -57,7 +57,7 @@ commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata). 4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata).
```javascript ```js
// Callback for common event subscription. // Callback for common event subscription.
if (this.subscriber != null) { if (this.subscriber != null) {
commonEvent.subscribe(this.subscriber, (err, data) => { commonEvent.subscribe(this.subscriber, (err, data) => {
...@@ -74,7 +74,7 @@ if (this.subscriber != null) { ...@@ -74,7 +74,7 @@ if (this.subscriber != null) {
} }
``` ```
## Public Event Publishing Development ## Common Event Publishing Development
### When to Use ### When to Use
You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process. You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process.
...@@ -89,13 +89,13 @@ You can use the **publish** APIs to publish a custom common event, which can car ...@@ -89,13 +89,13 @@ You can use the **publish** APIs to publish a custom common event, which can car
#### Development for Publishing a Common Event #### Development for Publishing a Common Event
1. Import the **commonEvent** module. 1. Import the **commonEvent** module.
```javascript ```js
import commonEvent from '@ohos.commonEvent'; import commonEvent from '@ohos.commonEvent';
``` ```
2. Pass in the common event name and callback, and publish the event. 2. Pass in the common event name and callback, and publish the event.
```javascript ```js
// Publish a common event. // Publish a common event.
commonEvent.publish("event", (err) => { commonEvent.publish("event", (err) => {
if (err.code) { if (err.code) {
...@@ -109,13 +109,13 @@ commonEvent.publish("event", (err) => { ...@@ -109,13 +109,13 @@ commonEvent.publish("event", (err) => {
#### Development for Publishing a Common Event with Given Attributes #### Development for Publishing a Common Event with Given Attributes
1. Import the **commonEvent** module. 1. Import the **commonEvent** module.
```javascript ```js
import commonEvent from '@ohos.commonEvent' import commonEvent from '@ohos.commonEvent'
``` ```
2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata). 2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata).
```javascript ```js
// Attributes of a common event. // Attributes of a common event.
var options = { var options = {
code: 1, // Result code of the common event code: 1, // Result code of the common event
...@@ -125,7 +125,7 @@ var options = { ...@@ -125,7 +125,7 @@ var options = {
3. Pass in the common event name, attributes of the common event, and callback, and publish the event. 3. Pass in the common event name, attributes of the common event, and callback, and publish the event.
```javascript ```js
// Publish a common event. // Publish a common event.
commonEvent.publish("event", options, (err) => { commonEvent.publish("event", options, (err) => {
if (err.code) { if (err.code) {
...@@ -149,14 +149,14 @@ You can use the **unsubscribe** API to unsubscribe from a common event. ...@@ -149,14 +149,14 @@ You can use the **unsubscribe** API to unsubscribe from a common event.
### How to Develop ### How to Develop
1. Import the **commonEvent** module. 1. Import the **commonEvent** module.
```javascript ```js
import commonEvent from '@ohos.commonEvent'; import commonEvent from '@ohos.commonEvent';
``` ```
2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development). 2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development).
3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. 3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event.
```javascript ```js
if (this.subscriber != null) { if (this.subscriber != null) {
commonEvent.unsubscribe(this.subscriber, (err) => { commonEvent.unsubscribe(this.subscriber, (err) => {
if (err.code) { if (err.code) {
......
...@@ -45,9 +45,9 @@ If the notification function of an application is disabled, it cannot send notif ...@@ -45,9 +45,9 @@ If the notification function of an application is disabled, it cannot send notif
| API | Description | | API | Description |
| ------------------------------------------------------------ | ---------------- | | ------------------------------------------------------------ | ---------------- |
| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback<void>): void | Subscribes to a notification with the subscription information specified.| | subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\<void>): void | Subscribes to a notification with the subscription information specified.|
| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Subscribes to all notifications. | | subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | Subscribes to all notifications. |
| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Unsubscribes from a notification. | | unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\<void>): void | Unsubscribes from a notification. |
The subscription APIs support subscription to all notifications or notifications from specific applications. The subscription APIs support subscription to all notifications or notifications from specific applications.
...@@ -69,10 +69,10 @@ The subscription APIs support subscription to all notifications or notifications ...@@ -69,10 +69,10 @@ The subscription APIs support subscription to all notifications or notifications
| API | Description | | API | Description |
| ------------------------------------------------------------ | ------------------------ | | ------------------------------------------------------------ | ------------------------ |
| publish(request: NotificationRequest, callback: AsyncCallback<void>): void | Publishes a notification. | | publish(request: NotificationRequest, callback: AsyncCallback\<void>): void | Publishes a notification. |
| publish(request: NotificationRequest, userId: number, callback: AsyncCallback<void>): void | Publishes a notification to the specified user. | | publish(request: NotificationRequest, userId: number, callback: AsyncCallback\<void>): void | Publishes a notification to the specified user. |
| cancel(id: number, label: string, callback: AsyncCallback<void>): void | Cancels a specified notification. | | cancel(id: number, label: string, callback: AsyncCallback\<void>): void | Cancels a specified notification. |
| cancelAll(callback: AsyncCallback<void>): void; | Cancels all notifications published by the application.| | cancelAll(callback: AsyncCallback\<void>): void; | Cancels all notifications published by the application.|
The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user. The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user.
......
...@@ -4,26 +4,26 @@ ...@@ -4,26 +4,26 @@
### System Capabilities and APIs ### System Capabilities and APIs
SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each system capability corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs can be provided in the IDE for association. SysCap is short for System Capability. It refers to a standalone feature in the operating system, for example, Bluetooth, Wi-Fi, NFC, or camera. Each SysCap corresponds to a set of bound APIs, whose availability depends on the support of the target device. Such a set of APIs are provided in DevEco Studio for association.
![image-20220326064841782](figures/image-20220326064841782.png) ![image-20220326064841782](figures/image-20220326064841782.png)
### Supported Capability Set, Associated Capability Set, and Required Capability Set ### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set
The supported capability set, associated capability set, and required capability set are collections of system capabilities. The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps.
The supported capability set covers the device capabilities, and the required capability set covers the application capabilities. If the capability set required by application A is a subset of the capability set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed. The supported SysCap set covers the device capabilities, and the required SysCap set covers the application capabilities. If the SysCap set required by application A is a subset of the SysCap set supported by device N, application A can be distributed to device N for installation and running. Otherwise, application A cannot be distributed.
The associated capability set covers the system capabilities of associated APIs that the IDE offers during application development. The associated SysCap set covers the system capabilities of associated APIs that the IDE offers during application development.
![image-20220326064913834](figures/image-20220326064913834.png) ![image-20220326064913834](figures/image-20220326064913834.png)
### Devices and Supported Capability Sets ### Devices and Supported SysCap Sets
Each device provides a capability set that matches its hardware capability. Each device provides a SysCap set that matches its hardware capability.
The SDK classifies devices into general devices and custom devices. The general devices' supported capability set is defined by OpenHarmony, and the custom devices' is defined by device vendors. The SDK classifies devices into general devices and custom devices. The general devices' supported SysCap set is defined by OpenHarmony, and the custom devices' is defined by device vendors.
![image-20220326064955505](figures/image-20220326064955505.png) ![image-20220326064955505](figures/image-20220326064955505.png)
...@@ -31,7 +31,7 @@ The SDK classifies devices into general devices and custom devices. The general ...@@ -31,7 +31,7 @@ The SDK classifies devices into general devices and custom devices. The general
### Mapping Between Devices and SDK Capabilities ### Mapping Between Devices and SDK Capabilities
The SDK provides a full set of APIs for the IDE. The IDE identifies the supported capability set based on the devices supported by the project, filters the APIs contained in the capability set, and provides the supported APIs for association (to autocomplete input). The SDK provides a full set of APIs for the IDE. DevEco Studio identifies the supported SysCap set based on the devices supported by the project, filters the APIs contained in the SysCap set, and provides the supported APIs for association (to autocomplete input).
![image-20220326065043006](figures/image-20220326065043006.png) ![image-20220326065043006](figures/image-20220326065043006.png)
...@@ -49,11 +49,11 @@ Right-click the project directory and choose **Import Product Compatibility ID** ...@@ -49,11 +49,11 @@ Right-click the project directory and choose **Import Product Compatibility ID**
### Configuring the Associated Capability Set and Required Capability Set ### Configuring the Associated SysCap Set and Required SysCap Set
The IDE automatically configures the associated capability set and required capability set based on the settings supported by the created project. You can modify the capability sets when necessary. DevEco Studio automatically configures the associated SysCap set and required SysCap set based on the settings supported by the created project. You can modify these SysCap sets when necessary.
You can add APIs to the associated capability set in the IDE by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them. You can add APIs to the associated SysCap set in DevEco Studio by adding system capabilities. However, note that these APIs may not be supported on the device. Therefore, check whether these APIs are supported before using them.
Exercise caution when modifying the required capability set. Incorrect modifications may result in the application being unable to be distributed to the target device. Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device.
``` ```
/* syscap.json */ /* syscap.json */
...@@ -74,15 +74,15 @@ Exercise caution when modifying the required capability set. Incorrect modificat ...@@ -74,15 +74,15 @@ Exercise caution when modifying the required capability set. Incorrect modificat
... ...
] ]
}, },
development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated capability set. */ development: { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */
addedSysCaps: [ addedSysCaps: [
"SystemCapability.Location.Location.Lite", "SystemCapability.Location.Location.Lite",
... ...
] ]
}, },
production: { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */ production: { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */
addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required capability set with addedSysCaps set and removedSysCaps set. addedSysCaps: [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set.
removedSysCaps: [] // When the required capability set is a capability subset of a device, the application can be distributed to the device. removedSysCaps: [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device.
} }
} }
``` ```
...@@ -91,7 +91,7 @@ Exercise caution when modifying the required capability set. Incorrect modificat ...@@ -91,7 +91,7 @@ Exercise caution when modifying the required capability set. Incorrect modificat
### Single-Device Application Development ### Single-Device Application Development
By default, the associated capability set and required system capability set of the application are the same as the supported system capability set of the device. Exercise caution when modifying the required capability set. By default, the associated SysCap set and required SysCap set of the application are the same as the supported SysCap set of the device. Exercise caution when modifying the required SysCap set.
![image-20220326065124911](figures/image-20220326065124911.png) ![image-20220326065124911](figures/image-20220326065124911.png)
...@@ -99,7 +99,7 @@ By default, the associated capability set and required system capability set of ...@@ -99,7 +99,7 @@ By default, the associated capability set and required system capability set of
### Cross-Device Application Development ### Cross-Device Application Development
By default, the associated capability set of an application is the union of multiple devices' supported capability sets, while the required capability set is the intersection of the devices' supported capability sets. By default, the associated SysCap set of an application is the union of multiple devices' supported SysCap sets, while the required SysCap set is the intersection of the devices' supported SysCap sets.
![image-20220326065201867](figures/image-20220326065201867.png) ![image-20220326065201867](figures/image-20220326065201867.png)
...@@ -133,9 +133,9 @@ if (geolocation) { ...@@ -133,9 +133,9 @@ if (geolocation) {
### Checking the Differences Between Devices with the Same Capability ### Checking the Differences Between Devices with a Specific SysCap
The performance of a system capability may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability. The performance of a SysCap may vary by device type. For example, a tablet is superior to a smart wearable device in terms of the camera capability.
``` ```
import userAuth from '@ohos.userIAM.userAuth'; import userAuth from '@ohos.userIAM.userAuth';
...@@ -162,7 +162,7 @@ The device SysCaps in product solutions vary according to the component combinat ...@@ -162,7 +162,7 @@ The device SysCaps in product solutions vary according to the component combinat
![image-20220326072448840](figures/image-20220326072448840.png) ![image-20220326072448840](figures/image-20220326072448840.png)
1. A set of OpenHarmony source code consists of optional and mandatory components. Different components have different system capabilities. In other words, different components represent different SysCaps. 1. A set of OpenHarmony source code consists of optional and mandatory components. Different components represent different SysCaps.
2. In a normalized released SDK, APIs are mapped to SysCap sets. 2. In a normalized released SDK, APIs are mapped to SysCap sets.
...@@ -170,10 +170,10 @@ The device SysCaps in product solutions vary according to the component combinat ...@@ -170,10 +170,10 @@ The device SysCaps in product solutions vary according to the component combinat
4. The components configured for a product can be OpenHarmony components or proprietary components developed by a third party. Since there is mapping between components and SysCap, the SysCap set of the product can be obtained after all components are assembled. 4. The components configured for a product can be OpenHarmony components or proprietary components developed by a third party. Since there is mapping between components and SysCap, the SysCap set of the product can be obtained after all components are assembled.
5. The SysCap set is encoded to generate the PCID. You can import the PCID to the IDE and decode it into SysCap. During development, compatibility processing is performed to mitigate the SysCap differences of devices. 5. The SysCap set is encoded to generate the PCID. You can import the PCID to DevEco Studio and decode it into SysCaps. During development, compatibility processing is performed to mitigate the SysCap differences of devices.
6. System parameters deployed on devices contain the SysCap set. The system provides native interfaces and application interfaces for components and applications to check whether a specific SysCap is available. 6. System parameters deployed on devices contain the SysCap set. The system provides native interfaces and application interfaces for components and applications to check whether a specific SysCap is available.
7. During application development, the SysCap required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap required by the application and compares it with the SysCap of the device. If the SysCap required by the application is met, the application can be installed. 7. During application development, the SysCap set required by the application is encoded into the Required Product Compatibility ID (RPCID) and written into the application installation package. During application installation, the package manager decodes the RPCID to obtain the SysCap set required by the application and compares it with the SysCap set supported by the device. If the SysCap set required by the application is met, the application can be installed on the device.
8. When an application is running on a device, the **canIUse** API can be used to query whether the device is compatible with a specific SysCap. 8. When an application is running on a device, the **canIUse** API can be used to query whether the device is compatible with a specific SysCap.
...@@ -112,6 +112,7 @@ ...@@ -112,6 +112,7 @@
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.settings](js-apis-settings.md) - [@ohos.settings](js-apis-settings.md)
- [@ohos.data.storage](js-apis-data-storage.md)
- data/rdb/[resultSet](js-apis-data-resultset.md) - data/rdb/[resultSet](js-apis-data-resultset.md)
- File Management - File Management
...@@ -141,6 +142,9 @@ ...@@ -141,6 +142,9 @@
- [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.bluetooth](js-apis-bluetooth.md)
- [@ohos.connectedTag](js-apis-connectedTag.md) - [@ohos.connectedTag](js-apis-connectedTag.md)
- [@ohos.nfc.cardEmulation](js-apis-cardEmulation.md)
- [@ohos.nfc.controller](js-apis-nfcController.md)
- [@ohos.nfc.tag](js-apis-nfcTag.md)
- [@ohos.rpc](js-apis-rpc.md) - [@ohos.rpc](js-apis-rpc.md)
- [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifi](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md) - [@ohos.wifiext](js-apis-wifiext.md)
...@@ -214,7 +218,6 @@ ...@@ -214,7 +218,6 @@
- APIs No Longer Maintained - APIs No Longer Maintained
- [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.bytrace](js-apis-bytrace.md)
- [@ohos.data.storage](js-apis-data-storage.md)
- [@system.app](js-apis-system-app.md) - [@system.app](js-apis-system-app.md)
- [@system.battery](js-apis-system-battery.md) - [@system.battery](js-apis-system-battery.md)
- [@system.bluetooth](js-apis-system-bluetooth.md) - [@system.bluetooth](js-apis-system-bluetooth.md)
......
...@@ -143,7 +143,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { ...@@ -143,7 +143,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => {
## bundle.getAllBundleInfo ## bundle.getAllBundleInfo
getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise<Array\<BundleInfo>> getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise\<Array\<BundleInfo>>
Obtains the information of all available bundles of a specified user in the system. This API uses a promise to return the result. Obtains the information of all available bundles of a specified user in the system. This API uses a promise to return the result.
...@@ -166,7 +166,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -166,7 +166,7 @@ SystemCapability.BundleManager.BundleFramework
| Type | Description | | Type | Description |
| --------------------------- | -------------------------- | | --------------------------- | -------------------------- |
| Promise<Array\<[BundleInfo](js-apis-bundle-BundleInfo.md)>> | Promise used to return the information of all available bundles.| | Promise\<Array\<[BundleInfo](js-apis-bundle-BundleInfo.md)>> | Promise used to return the information of all available bundles.|
**Example** **Example**
...@@ -185,7 +185,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) ...@@ -185,7 +185,7 @@ bundle.getAllBundleInfo(bundleFlag, userId)
## bundle.getAllBundleInfo ## bundle.getAllBundleInfo
getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback<Array\<BundleInfo>>): void getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback\<Array\<BundleInfo>>): void
Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result.
...@@ -220,7 +220,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { ...@@ -220,7 +220,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => {
## bundle.getAllBundleInfo ## bundle.getAllBundleInfo
getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback<Array\<BundleInfo>>): void getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback\<Array\<BundleInfo>>): void
Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result.
...@@ -238,7 +238,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -238,7 +238,7 @@ SystemCapability.BundleManager.BundleFramework
| ---------- | --------------------------------- | ---- | --------------------------------------- | | ---------- | --------------------------------- | ---- | --------------------------------------- |
| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| | bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.|
| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. |
| callback | AsyncCallback<Array\<[BundleInfo](js-apis-bundle-BundleInfo.md)>> | Yes | Callback used to return the information of all available bundles. | | callback | AsyncCallback\<Array\<[BundleInfo](js-apis-bundle-BundleInfo.md)>> | Yes | Callback used to return the information of all available bundles. |
**Example** **Example**
...@@ -276,7 +276,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -276,7 +276,7 @@ SystemCapability.BundleManager.BundleFramework
| ----------- | ------------- | ---- | --------------------------------------- | | ----------- | ------------- | ---- | --------------------------------------- |
| bundleName | string | Yes | Bundle name of the application. | | bundleName | string | Yes | Bundle name of the application. |
| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.| | bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. The value must be greater than or equal to 0.|
| options | [BundleOptions](#bundleoptions)| No | Includes **userId**. | | options | [BundleOptions](#bundleoptions) | No | Includes **userId**. |
**Return value** **Return value**
...@@ -495,7 +495,7 @@ bundle.getAllApplicationInfo(bundleFlags, (err, data) => { ...@@ -495,7 +495,7 @@ bundle.getAllApplicationInfo(bundleFlags, (err, data) => {
## bundle.getBundleArchiveInfo ## bundle.getBundleArchiveInfo
getBundleArchiveInfo(hapFilePath: string, bundleFlags: number) : Promise<BundleInfo> getBundleArchiveInfo(hapFilePath: string, bundleFlags: number) : Promise\<BundleInfo>
Obtains information about the bundles contained in a HAP file. This API uses a promise to return the result. Obtains information about the bundles contained in a HAP file. This API uses a promise to return the result.
...@@ -508,7 +508,7 @@ SystemCapability.BundleManager.BundleFramework ...@@ -508,7 +508,7 @@ SystemCapability.BundleManager.BundleFramework
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | ------------ | | ---------- | ------ | ---- | ------------ |
| hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.|
| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than 0.| | bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than or equal to 0.|
**Return value** **Return value**
| Type | Description | | Type | Description |
...@@ -530,7 +530,7 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags) ...@@ -530,7 +530,7 @@ bundle.getBundleArchiveInfo(hapFilePath, bundleFlags)
## bundle.getBundleArchiveInfo ## bundle.getBundleArchiveInfo
getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback<BundleInfo>) : void getBundleArchiveInfo(hapFilePath: string, bundleFlags: number, callback: AsyncCallback\<BundleInfo>) : void
Obtains information about the bundles contained in a HAP file. This API uses an asynchronous callback to return the result. Obtains information about the bundles contained in a HAP file. This API uses an asynchronous callback to return the result.
...@@ -543,8 +543,8 @@ SystemCapability.BundleManager.BundleFramework ...@@ -543,8 +543,8 @@ SystemCapability.BundleManager.BundleFramework
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------ | ---- | ------------ | | ---------- | ------ | ---- | ------------ |
| hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| | hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.|
| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than 0.| | bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than or equal to 0.|
| callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. The value must be greater than 0.| | callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles.|
**Example** **Example**
......
# Context Module # Context
## Modules to Import ## Modules to Import
...@@ -925,9 +925,9 @@ Describes the HAP module information. ...@@ -925,9 +925,9 @@ Describes the HAP module information.
| iconId | number | Yes | No | Module icon ID. | | iconId | number | Yes | No | Module icon ID. |
| backgroundImg | string | Yes | No | Module background image. | | backgroundImg | string | Yes | No | Module background image. |
| supportedModes | number | Yes | No | Modes supported by the module. | | supportedModes | number | Yes | No | Modes supported by the module. |
| reqCapabilities | Array<string> | Yes | No | Capabilities required for module running.| | reqCapabilities | Array\<string> | Yes | No | Capabilities required for module running.|
| deviceTypes | Array<string> | Yes | No | An array of supported device types.| | deviceTypes | Array\<string> | Yes | No | An array of supported device types.|
| abilityInfo | Array\<AbilityInfo> | Yes | No | Ability information. | | abilityInfo | Array\\<AbilityInfo> | Yes | No | Ability information. |
| moduleName | string | Yes | No | Module name. | | moduleName | string | Yes | No | Module name. |
| mainAbilityName | string | Yes | No | Name of the entrance ability. | | mainAbilityName | string | Yes | No | Name of the entrance ability. |
| installationFree | boolean | Yes | No | When installation-free is supported. | | installationFree | boolean | Yes | No | When installation-free is supported. |
......
# AbilityManager # AbilityManager
> **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. > 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.
> >
......
# AbilityStageContext # AbilityStageContext
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Implements the context of an ability stage. This module is inherited from [Context](js-apis-application-context.md). Implements the context of an ability stage. This module is inherited from [Context](js-apis-application-context.md).
## Modules to Import
```js
import AbilityStage from '@ohos.application.AbilityStage';
```
## Usage ## Usage
The ability stage context is obtained through an **AbilityStage** instance. The ability stage context is obtained through an **AbilityStage** instance.
```js ```js
import AbilityStage from '@ohos.application.AbilityStage'; import AbilityStage from '@ohos.application.AbilityStage';
class MyAbilityStage extends AbilityStage { class MyAbilityStage extends AbilityStage {
......
# AbilityRunningInfo # AbilityRunningInfo
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **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. > 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.
Provides ability running information. Provides ability running information.
## Modules to Import
```js
import abilitymanager from '@ohos.application.abilityManager';
```
## Usage ## Usage
The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**. The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**.
```js ```js
import abilitymanager from '@ohos.application.abilityManager'; import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => { abilitymanager.getAbilityRunningInfos((err,data) => {
......
# Animation # Animator
>![](../../public_sys-resources/icon-note.gif) **NOTE:** > **NOTE**<br>
>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import
**requestAnimationFrame**: none
**cancelAnimationFrame**: none
**createAnimator**: ## Modules to Import
``` ```
import animator from '@ohos.animator'; import animator from '@ohos.animator';
``` ```
## Required Permissions
None
## requestAnimationFrame
requestAnimationFrame\(handler\[, \[ ...args\]\]\): number
Requests an animation frame.
- Parameters
| Name | Type | Mandatory | Description |
| ------- | ----------- | --------- | ------------------------------------------------------------ |
| handler | Function | Yes | Handler used to request a frame. When **requestAnimationFrame** calls the **handler**, the timestamp is passed to the first parameter to indicate the time when **requestAnimationFrame** starts to execute the callback. |
| ...args | Array\<any> | No | Additional parameter, which is passed to the **handler** as a parameter during function callback. |
- Return values
| Type | Description |
| ------ | ----------- |
| number | Request ID. |
- Example
```
<!-- xxx.hml -->
<div class="container">
<button type="capsule" class="btn" onclick="beginAnimation">beginAnimation</button>
</div>
```
```
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.btn{
width: 300px;
margin-top: 40px;
}
```
```
/* xxx.js */
export default {
data: {
requestId: 0,
startTime: 0,
},
beginAnimation() {
cancelAnimationFrame(this.requestId);
this.requestId = requestAnimationFrame(this.runAnimation);
},
runAnimation(timestamp) {
if (this.startTime == 0) {
this.startTime = timestamp;
}
var elapsed = timestamp - this.startTime;
if (elapsed < 500) {
console.log('callback handler timestamp: ' + timestamp);
this.requestId = requestAnimationFrame(this.runAnimation);
}
}
}
```
## cancelAnimationFrame
cancelAnimationFrame\(requestId: number\): void
Cancels the animation frame request.
- Parameters
| Name | Type | Mandatory | Description |
| --------- | ------ | --------- | ------------------------ |
| requestId | number | Yes | ID of the frame request. |
- Example
```
<!-- xxx.hml -->
<div class="container">
<button type="capsule" class="btn" onclick="beginAnimation">beginAnimation</button>
<button type="capsule" class="btn" onclick="beginAnimation">stopAnimation</button>
</div>
```
```
/* xxx.css */
.container {
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
}
.btn{
width: 300px;
margin-top: 40px;
}
```
```
/* xxx.js */
export default {
data: {
requestId: 0,
startTime: 0,
},
beginAnimation() {
cancelAnimationFrame(this.requestId);
this.requestId = requestAnimationFrame(this.runAnimation);
},
runAnimation(timestamp) {
if (this.startTime == 0) {
this.startTime = timestamp;
}
var elapsed = timestamp - this.startTime;
if (elapsed < 500) {
console.log('callback handler timestamp: ' + timestamp);
this.requestId = requestAnimationFrame(this.runAnimation);
}
},
stopAnimation() {
cancelAnimationFrame(this.requestId);
}
}
```
## createAnimator ## createAnimator
createAnimator\(options\[...\]\): void createAnimator(options: AnimatorOptions): AnimatorResult
Creates an animation object.
- Parameters
| Name | Type | Mandatory | Description | Creates an **Animator** object.
| ------- | ------ | --------- | ------------------------------------------------------------ |
| options | Object | Yes | Attributes of the **Animator** to be created. For details, see the options table. |
- Description of options **System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name | Type | Mandatory | Description | **Parameters**
| ---------- | ------ | --------- | ------------------------------------------------------------ | | Name| Type| Mandatory| Description|
| duration | number | No | Duration for playing an animation, in milliseconds. The default value is **0**. | | -------- | -------- | -------- | -------- |
| easing | string | No | Animation easing curve. The default value is **ease**. | | options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.|
| delay | number | No | Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay. |
| fill | string | No | Animation start/stop mode. The default value is **none**. |
| direction | string | No | Animation playback mode. The default value is **normal**. |
| iterations | number | No | Number of times that an animation is played. The default value is **1**. If this parameter is set to **0**, the animation is not played. If this parameter is set to **-1**, the animation is played for an unlimited number of times. |
| begin | number | No | Start point of the animation easing. If this parameter is not set, the default value **0** is used. |
| end | number | No | End point of the animation easing. If this parameter is not set, the default value **1** is used. |
- animator interfaces **Return value**
| Type| Description|
| -------- | -------- |
| [AnimatorResult](#animatorresult) | Animator result.|
| Name | Type | Description | **Example**
| ------- | ------- | ------------------------------------------------------------ |
| update | options | Updates the animation parameters. The input parameters are the same as those of **createAnimator**. |
| play | - | Starts an animation. |
| finish | - | Ends an animation. |
| pause | - | Pauses an animation. |
| cancel | - | Cancels an animation. |
| reverse | - | Reverses an animation. |
- **animator** supported events:
| Name | Type | Description |
| ------ | ------ | ----------------------------------- |
| frame | number | The frame is requested. |
| cancel | - | The animation is forcibly canceled. |
| finish | - | The animation playback is complete. |
| repeat | - | The animation replays. |
- Example
``` ```
<!-- hml --> <!-- hml -->
...@@ -246,3 +77,164 @@ Creates an animation object. ...@@ -246,3 +77,164 @@ Creates an animation object.
} }
} }
``` ```
## AnimatorResult
Defines the animator result.
### update
update(options: AnimatorOptions): void
Updates this animator.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.|
**Example**
```
animator.update(options);
```
### play
play(): void
Plays this animation.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.play();
```
### finish
finish(): void
Ends this animation.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.finish();
```
### pause
pause(): void
Pauses this animation.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.pause();
```
### cancel
cancel(): void
Cancels this animation.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.cancel();
```
### reverse
reverse(): void
Plays this animation in reverse order.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.reverse();
```
### onframe
onframe: (progress: number) => void
Called when a frame is received.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| progress | number | Yes| Current progress of the animation.|
**Example**
```
animator.onframe();
```
### onfinish
onfinish: () => void
Called when this animation is finished.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.onfinish();
```
### oncancel
oncancel: () => void
Called when this animation is canceled.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.oncancel();
```
### onrepeat
onrepeat: () => void
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
```
animator.onrepeat();
```
Called when this animation repeats.
## AnimatorOptions
Defines animator options.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.|
| easing | string | Yes| Animation interpolation curve. The default value is **ease**.|
| delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.|
| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that after the animation is executed, the target will retain the state (defined by the last keyframe) it is in when the animation ends.|
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.|
| iterations | number | Yes| Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.|
| begin | number | Yes| Start point of the animation interpolation. If this parameter is not set, the default value **0** is used.|
| end | number | Yes| End point of the animation interpolation. If this parameter is not set, the default value **1** is used.|
# App Account Management # App Account Management
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -26,7 +26,7 @@ Creates an **AppAccountManager** instance. ...@@ -26,7 +26,7 @@ Creates an **AppAccountManager** instance.
**Example** **Example**
```js ```js
var appAccountManager = account.createAppAccountManager(); const appAccountManager = account_appAccount.createAppAccountManager();
``` ```
## AppAccountManager ## AppAccountManager
...@@ -387,7 +387,7 @@ Checks whether an app account allows application data synchronization. This meth ...@@ -387,7 +387,7 @@ Checks whether an app account allows application data synchronization. This meth
### setAccountCredential ### setAccountCredential
setAccountCredential(name: string, credentialType: string, credential: string, callback: AsyncCallback&lt;void&gt;): void setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback&lt;void&gt;): void
Sets a credential for an app account. This method uses an asynchronous callback to return the result. Sets a credential for an app account. This method uses an asynchronous callback to return the result.
......
# MissionInfo # MissionInfo
> **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. > 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.
## Modules to Import ## Modules to Import
......
# appManager # appManager
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -25,9 +26,9 @@ Checks whether this application is undergoing a stability test. This API uses an ...@@ -25,9 +26,9 @@ Checks whether this application is undergoing a stability test. This API uses an
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| | callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -49,9 +50,9 @@ Checks whether this application is undergoing a stability test. This API uses a ...@@ -49,9 +50,9 @@ Checks whether this application is undergoing a stability test. This API uses a
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| | Promise&lt;boolean&gt; | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -75,9 +76,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -75,9 +76,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| | Promise&lt;boolean&gt; | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -99,9 +100,9 @@ Checks whether this application is running on a RAM constrained device. This API ...@@ -99,9 +100,9 @@ Checks whether this application is running on a RAM constrained device. This API
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| | callback | AsyncCallback&lt;boolean&gt; | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.|
**Example** **Example**
...@@ -122,9 +123,9 @@ Obtains the memory size of this application. This API uses a promise to return t ...@@ -122,9 +123,9 @@ Obtains the memory size of this application. This API uses a promise to return t
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Size of the application memory.| | Promise&lt;number&gt; | Size of the application memory.|
**Example** **Example**
...@@ -146,9 +147,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -146,9 +147,9 @@ Obtains the memory size of this application. This API uses an asynchronous callb
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;number&gt; | No| Size of the application memory.| | callback | AsyncCallback&lt;number&gt; | No| Size of the application memory.|
**Example** **Example**
...@@ -160,7 +161,7 @@ Obtains the memory size of this application. This API uses an asynchronous callb ...@@ -160,7 +161,7 @@ Obtains the memory size of this application. This API uses an asynchronous callb
``` ```
## appManager.getProcessRunningInfos<sup>8+</sup> ## appManager.getProcessRunningInfos<sup>8+</sup>
getProcessRunningInfos(): Promise<Array\<ProcessRunningInfo>>; getProcessRunningInfos(): Promise\<Array\<ProcessRunningInfo>>;
Obtains information about the running processes. This API uses a promise to return the result. Obtains information about the running processes. This API uses a promise to return the result.
...@@ -168,9 +169,9 @@ Obtains information about the running processes. This API uses a promise to retu ...@@ -168,9 +169,9 @@ Obtains information about the running processes. This API uses a promise to retu
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise<Array\<ProcessRunningInfo>> | Promise used to return the process information.| | Promise\<Array\<ProcessRunningInfo>> | Promise used to return the process information.|
**Example** **Example**
...@@ -184,7 +185,7 @@ Obtains information about the running processes. This API uses a promise to retu ...@@ -184,7 +185,7 @@ Obtains information about the running processes. This API uses a promise to retu
## appManager.getProcessRunningInfos<sup>8+</sup> ## appManager.getProcessRunningInfos<sup>8+</sup>
getProcessRunningInfos(callback: AsyncCallback<Array\<ProcessRunningInfo>>): void; getProcessRunningInfos(callback: AsyncCallback\<Array\<ProcessRunningInfo>>): void;
Obtains information about the running processes. This API uses an asynchronous callback to return the result. Obtains information about the running processes. This API uses an asynchronous callback to return the result.
...@@ -192,9 +193,9 @@ Obtains information about the running processes. This API uses an asynchronous c ...@@ -192,9 +193,9 @@ Obtains information about the running processes. This API uses an asynchronous c
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| callback | AsyncCallback<Array\<ProcessRunningInfo>> | No| Callback used to return the process information.| | callback | AsyncCallback\<Array\<ProcessRunningInfo>> | No| Callback used to return the process information.|
**Example** **Example**
......
# Audio Management # Audio Management
> **NOTE**<br/> > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> >
> API version 9 is a canary release for trial use. The APIs of this version may be unstable. > API version 9 is a canary release for trial use. The APIs of this version may be unstable.
...@@ -544,7 +545,7 @@ Describes the callback invoked for audio interruption or focus gain events. ...@@ -544,7 +545,7 @@ Describes the callback invoked for audio interruption or focus gain events.
| ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ | | ---------- | ------------------------------------------- | ---- | ------------------------------------------------------------ |
| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event.| | actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event.|
| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | | type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. |
| hint | [InterruptHint](interrupthint) | No | Hint provided along with the audio interruption event. | | hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. |
| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released.| | activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released.|
## VolumeEvent<sup>8+</sup> ## VolumeEvent<sup>8+</sup>
...@@ -2656,7 +2657,7 @@ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, yo ...@@ -2656,7 +2657,7 @@ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, yo
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| :---- | :------------------------- | :--- | :--- | :--------------- | | :---- | :------------------------- | :--- | :--- | :--------------- |
| state<sup>8+</sup> | [AudioState](#audiostate8) | Yes| No | Audio capturer state.| | state<sup>8+</sup> | [AudioState](#audiostate8) | Yes | No | Audio capturer state.|
**Example** **Example**
......
...@@ -67,10 +67,10 @@ Obtains the remaining duration before the application is suspended. This API use ...@@ -67,10 +67,10 @@ Obtains the remaining duration before the application is suspended. This API use
```js ```js
let id = 1; let id = 1;
backgroundTaskManager.getRemainingDelayTime(id, (err, res) => { backgroundTaskManager.getRemainingDelayTime(id, (err, res) => {
if(err.data === 0) { if(err) {
console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code);
} else { } else {
console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.data); console.log('callback => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
} }
}) })
``` ```
...@@ -100,7 +100,7 @@ Obtains the remaining duration before the application is suspended. This API use ...@@ -100,7 +100,7 @@ Obtains the remaining duration before the application is suspended. This API use
backgroundTaskManager.getRemainingDelayTime(id).then( res => { backgroundTaskManager.getRemainingDelayTime(id).then( res => {
console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res));
}).catch( err => { }).catch( err => {
console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.data); console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code);
}) })
``` ```
......
# Bluetooth # Bluetooth
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
> The Bluetooth module provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. Provides Classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.
## Modules to Import ## Modules to Import
...@@ -223,7 +223,7 @@ Obtains the connection status of a profile. ...@@ -223,7 +223,7 @@ Obtains the connection status of a profile.
**Example** **Example**
```js ```js
let result = bluetooth.getProfileConnState(PROFILE_A2DP_SOURCE); let result = bluetooth.getProfileConnState(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
``` ```
...@@ -364,7 +364,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de ...@@ -364,7 +364,7 @@ Sets the Bluetooth scan mode so that the device can be discovered by a remote de
```js ```js
// The device can be discovered and connected only when the discoverable and connectable mode is used. // The device can be discovered and connected only when the discoverable and connectable mode is used.
let result = bluetooth.setBluetoothScanMode(ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100); let result = bluetooth.setBluetoothScanMode(bluetooth.ScanMode.SCAN_MODE_CONNECTABLE_GENERAL_DISCOVERABLE, 100);
``` ```
...@@ -456,7 +456,7 @@ Sets the device pairing confirmation. ...@@ -456,7 +456,7 @@ Sets the device pairing confirmation.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------- | ---- | -------------------------------- | | ------ | ------- | ---- | -------------------------------- |
| device | string | Yes | Address of the target remote device, for example, XX:XX:XX:XX:XX:XX.| | device | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.|
| accept | boolean | Yes | Whether to accept the pairing request. The value **true** means to accept the pairing request, and the value **false** means the opposite. | | accept | boolean | Yes | Whether to accept the pairing request. The value **true** means to accept the pairing request, and the value **false** means the opposite. |
**Return value** **Return value**
...@@ -729,7 +729,7 @@ bluetooth.off('stateChange', onReceiveEvent); ...@@ -729,7 +729,7 @@ bluetooth.off('stateChange', onReceiveEvent);
``` ```
## bluetooth.sppListen<sup>8+</sup><a name="sppListen<"></a> ## bluetooth.sppListen<sup>8+</sup><a name="sppListen"></a>
sppListen(name: string, option: SppOption, callback: AsyncCallback&lt;number&gt;): void sppListen(name: string, option: SppOption, callback: AsyncCallback&lt;number&gt;): void
...@@ -782,6 +782,14 @@ Listens for a connection to be made to this socket from the client and accepts i ...@@ -782,6 +782,14 @@ Listens for a connection to be made to this socket from the client and accepts i
**Example** **Example**
```js ```js
let serverNumber = -1;
function serverSocket(code, number) {
console.log('bluetooth error code: ' + code.code);
if (code.code == 0) {
console.log('bluetooth serverSocket Number: ' + number);
serverNumber = number;
}
}
let clientNumber = -1; let clientNumber = -1;
function acceptClientSocket(code, number) { function acceptClientSocket(code, number) {
console.log('bluetooth error code: ' + code.code); console.log('bluetooth error code: ' + code.code);
...@@ -847,6 +855,14 @@ Closes the listening socket of the server. ...@@ -847,6 +855,14 @@ Closes the listening socket of the server.
**Example** **Example**
```js ```js
let serverNumber = -1;
function serverSocket(code, number) {
console.log('bluetooth error code: ' + code.code);
if (code.code == 0) {
console.log('bluetooth serverSocket Number: ' + number);
serverNumber = number;
}
}
bluetooth.sppCloseServerSocket(serverNumber); bluetooth.sppCloseServerSocket(serverNumber);
``` ```
...@@ -869,6 +885,15 @@ Closes the client socket. ...@@ -869,6 +885,15 @@ Closes the client socket.
**Example** **Example**
```js ```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
bluetooth.sppCloseClientSocket(clientNumber); bluetooth.sppCloseClientSocket(clientNumber);
``` ```
...@@ -897,6 +922,15 @@ Writes data to the remote device through the socket. ...@@ -897,6 +922,15 @@ Writes data to the remote device through the socket.
**Example** **Example**
```js ```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
let arrayBuffer = new ArrayBuffer(8); let arrayBuffer = new ArrayBuffer(8);
let data = new Uint8Array(arrayBuffer); let data = new Uint8Array(arrayBuffer);
data[0] = 123; data[0] = 123;
...@@ -932,6 +966,15 @@ No value is returned. ...@@ -932,6 +966,15 @@ No value is returned.
**Example** **Example**
```js ```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
function dataRead(dataBuffer) { function dataRead(dataBuffer) {
let data = new Uint8Array(dataBuffer); let data = new Uint8Array(dataBuffer);
console.log('bluetooth data is: ' + data[0]); console.log('bluetooth data is: ' + data[0]);
...@@ -963,6 +1006,15 @@ No value is returned. ...@@ -963,6 +1006,15 @@ No value is returned.
**Example** **Example**
```js ```js
let clientNumber = -1;
function clientSocket(code, number) {
if (code.code != 0) {
return;
}
console.log('bluetooth serverSocket Number: ' + number);
// The obtained clientNumber is used as the socket ID for subsequent read/write operations on the client.
clientNumber = number;
}
bluetooth.off('sppRead', clientNumber); bluetooth.off('sppRead', clientNumber);
``` ```
...@@ -1218,7 +1270,7 @@ No value is returned. ...@@ -1218,7 +1270,7 @@ No value is returned.
| | | | | |
| ------------------- | ------------- | | ------------------- | ------------- |
| Type | Description | | Type | Description |
| Array&lt;string&gt; | List of addresses of the connected devices. | | Array&lt;string&gt; | Addresses of the connected devices. |
### getDeviceState<sup>8+</sup><a name="getDeviceState"></a> ### getDeviceState<sup>8+</sup><a name="getDeviceState"></a>
...@@ -1236,14 +1288,12 @@ Obtains the connection status of the profile. ...@@ -1236,14 +1288,12 @@ Obtains the connection status of the profile.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the target device.| | device | string | Yes | Address of the target device.|
|
**Return value** **Return value**
| | | | | |
| ------------------------------------------------- | ----------------------- | | ------------------------------------------------- | ----------------------- |
| Type | Description | | Type | Description |
| [ProfileConnectionState](#profileconnectionstate) | Profile connection state obtained. | | [ProfileConnectionState](#profileconnectionState) | Profile connection state obtained. |
## A2dpSourceProfile ## A2dpSourceProfile
...@@ -1251,7 +1301,7 @@ Obtains the connection status of the profile. ...@@ -1251,7 +1301,7 @@ Obtains the connection status of the profile.
Before using a method of **A2dpSourceProfile**, you need to create an instance of this class by using the **getProfile()** method. Before using a method of **A2dpSourceProfile**, you need to create an instance of this class by using the **getProfile()** method.
### connect<sup>8+</sup><a name="connect"></a> ### connect<sup>8+</sup><a name="a2dp-connect"></a>
connect(device: string): boolean connect(device: string): boolean
...@@ -1278,12 +1328,12 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. ...@@ -1278,12 +1328,12 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE) let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE)
let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX');
``` ```
### disconnect<sup>8+</sup><a name="disconnect"></a> ### disconnect<sup>8+</sup><a name="a2dp-disconnect"></a>
disconnect(device: string): boolean disconnect(device: string): boolean
...@@ -1310,7 +1360,7 @@ Disconnects an A2DP connection. ...@@ -1310,7 +1360,7 @@ Disconnects an A2DP connection.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1397,7 +1447,7 @@ Obtains the playing status of a device. ...@@ -1397,7 +1447,7 @@ Obtains the playing status of a device.
**Example** **Example**
```js ```js
let a2dpSrc = bluetooth.getProfile(PROFILE_A2DP_SOURCE); let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1407,7 +1457,7 @@ let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); ...@@ -1407,7 +1457,7 @@ let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX');
Before using a method of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using the **getProfile()** method. Before using a method of **HandsFreeAudioGatewayProfile**, you need to create an instance of this class by using the **getProfile()** method.
### connect<sup>8+</sup><a name="connect"></a> ### connect<sup>8+</sup><a name="hfp-connect"></a>
connect(device: string): boolean connect(device: string): boolean
...@@ -1434,12 +1484,12 @@ Sets up a Hands-free Profile (HFP) connection of a device. ...@@ -1434,12 +1484,12 @@ Sets up a Hands-free Profile (HFP) connection of a device.
**Example** **Example**
```js ```js
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX'); let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX');
``` ```
### disconnect<sup>8+</sup><a name="disconnect"></a> ### disconnect<sup>8+</sup><a name="hfp-disconnect"></a>
disconnect(device: string): boolean disconnect(device: string): boolean
...@@ -1465,7 +1515,7 @@ Disconnects the HFP connection of a device. ...@@ -1465,7 +1515,7 @@ Disconnects the HFP connection of a device.
**Example** **Example**
```js ```js
let hfpAg = bluetooth.getProfile(PROFILE_HANDS_FREE_AUDIO_GATEWAY); let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY);
let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX');
``` ```
...@@ -1665,7 +1715,7 @@ cccV[0] = 1; ...@@ -1665,7 +1715,7 @@ cccV[0] = 1;
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors}; characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', let characteristicN = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptorsN}; characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
characteristics[0] = characteristic; characteristics[0] = characteristic;
// Create a gattService instance. // Create a gattService instance.
...@@ -1757,8 +1807,11 @@ Notifies the connected client device when a characteristic value changes. ...@@ -1757,8 +1807,11 @@ Notifies the connected client device when a characteristic value changes.
**Example** **Example**
```js ```js
let arrayBufferC = new ArrayBuffer(8);
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB', let notifyCharacteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: notifyCcc.characteristicValue, confirm: false}; characteristicUuid: '00001821-0000-1000-8000-00805F9B34FB', characteristicValue: characteristic.characteristicValue, confirm: false};
let server = bluetooth.BLE.createGattServer(); let server = bluetooth.BLE.createGattServer();
server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic); server.notifyCharacteristicChanged('XX:XX:XX:XX:XX:XX', notifyCharacteristic);
``` ```
...@@ -1984,7 +2037,7 @@ Subscribes to the descriptor read request events. ...@@ -1984,7 +2037,7 @@ Subscribes to the descriptor read request events.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | --------------------------------- | | -------- | ---------------------------------------- | ---- | --------------------------------- |
| type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.| | type | string | Yes | Event type. The value **descriptorRead** indicates a descriptor read request event.|
| callback | Callback&lt;[DescriptorReadReq](#descriptorreadreq)&gt; | Yes | Callback invoked to return a descriptor read request from the GATT client. | | callback | Callback&lt;[DescriptorReadReq](#descriptorreadreq)&gt; | Yes | Callback invoked to return a descriptor read request event from the GATT client. |
**Return value** **Return value**
...@@ -2334,7 +2387,7 @@ Obtains all services of the remote BLE device. This method uses a promise to ret ...@@ -2334,7 +2387,7 @@ Obtains all services of the remote BLE device. This method uses a promise to ret
// Promise // Promise
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.connect(); device.connect();
let services = device.getServices(); var services = device.getServices();
console.log("bluetooth services size is ", services.length); console.log("bluetooth services size is ", services.length);
for (let i = 0; i < services.length; i++) { for (let i = 0; i < services.length; i++) {
...@@ -2672,8 +2725,11 @@ Sets the function of notifying the GATT client when the characteristic value of ...@@ -2672,8 +2725,11 @@ Sets the function of notifying the GATT client when the characteristic value of
**Example** **Example**
```js ```js
let arrayBufferC = new ArrayBuffer(8);
let characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.setNotifyCharacteristicChanged(notifyCcc, false); device.setNotifyCharacteristicChanged(characteristic, false);
``` ```
......
# Standard NFC Card Emulation
Implements Near-Field Communication (NFC) card emulation.
> **NOTE**<br>
> 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.
## **Modules to Import**
```
import cardEmulation from '@ohos.nfc.cardEmulation';
```
## cardEmulation.isSupported
isSupported(feature: number): boolean
Checks whether a certain type of card emulation is supported.
**System capability**: SystemCapability.Communication.NFC
**Return value**
| **Type**| **Description**|
| -------- | -------- |
| boolean | Returns **true** if the card emulation is supported; returns **false** otherwise.|
## HceService
Implements Host-based Card Emulation (HCE). Before calling any API in **HceService**, you must use **new cardEmulation.HceService()** to create an **HceService** instance.
### startHCE
startHCE(aidList: string[]): boolean
Starts HCE.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | -------- | ---- | ----------------------- |
| aidList | string[] | Yes | Application ID (AID) list to be registered for card emulation.|
### stopHCE
stopHCE(): boolean
Stops HCE.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC
### on
on(type: "hceCmd", callback: AsyncCallback<number[]>): void;
Subscribes to messages from the peer device after **startHCE()**.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | -------------------------------------------- |
| type | string | Yes | Event type to subscribe to. The value is **hceCmd**. |
| callback | AsyncCallback<number[]> | Yes | Callback invoked to return the subscribed event. The input parameter is a data array that complies with the Application Protocol Data Unit (APDU).|
### sendResponse
sendResponse(responseApdu: number[]): void;
Sends a response to the peer device.
**Required permissions**: ohos.permission.NFC_CARD_EMULATION
**System capability**: SystemCapability.Communication.NFC
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | -------- | ---- | -------------------------------------------------- |
| responseApdu | number[] | Yes | Data to send, which is an array that complies with the APDU.|
**Example**
```js
var hceService = new cardEmulation.HceService();
hceService.startHCE([
"F0010203040506", "A0000000041010"
])
hceService.stopHCE();
hceService.on("hceCmd", (err, res) => {
if(err.data === 0) {
console.log('callback => Operation hceCmd succeeded. Data: ' + JSON.stringify(res));
hceService.sendResponse([0x00,0xa4,0x04,0x00,
0x0e,0x32,0x50,0x41,0x59,0x2e,0x53,0x59,0x53,0x2e,0x44,0x44,
0x46,0x30,0x31,0x00]);
} else {
console.log('callback => Operation hceCmd failed. Cause: ' + err.data);
}
})
```
# DataAbilityHelper Module (JavaScript SDK APIs) # DataAbilityHelper
> ![icon-note.gif](public_sys-resources/icon-note.gif)**NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -553,7 +554,7 @@ DAHelper.insert( ...@@ -553,7 +554,7 @@ DAHelper.insert(
## DataAbilityHelper.batchInsert ## DataAbilityHelper.batchInsert
batchInsert(uri: string, valuesBuckets: Array\<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void batchInsert(uri: string, valuesBuckets: Array<rdb.ValuesBucket>, callback: AsyncCallback\<number>): void
Inserts multiple data records into the database. This API uses an asynchronous callback to return the result. Inserts multiple data records into the database. This API uses an asynchronous callback to return the result.
...@@ -881,7 +882,7 @@ Calls the extended API of the Data ability. This API uses a promise to return th ...@@ -881,7 +882,7 @@ Calls the extended API of the Data ability. This API uses a promise to return th
| Type| Description| | Type| Description|
|------ | ------- | |------ | ------- |
|Promise<[PacMap](#pacmap)> | Promise used to return the result.| |Promise\<[PacMap](#pacmap)> | Promise used to return the result.|
**Example** **Example**
......
# EventHub # EventHub
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
>
> The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Implements event subscription, unsubscription, and triggering. Implements event subscription, unsubscription, and triggering.
## Modules to Import
```js
import Ability from '@ohos.application.Ability'
```
## Usage ## Usage
Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance.
```js ```js
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
...@@ -34,10 +38,10 @@ Subscribes to an event. ...@@ -34,10 +38,10 @@ Subscribes to an event.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| event | string | Yes| Event name.| | event | string | Yes| Event name.|
| callback | Function | Yes| Callback invoked when the event is triggered.| | callback | Function | Yes| Callback invoked when the event is triggered.|
**Example** **Example**
...@@ -72,10 +76,10 @@ Unsubscribes from an event. If **callback** is specified, this API unsubscribes ...@@ -72,10 +76,10 @@ Unsubscribes from an event. If **callback** is specified, this API unsubscribes
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| event | string | Yes| Event name.| | event | string | Yes| Event name.|
| callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| | callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.|
**Example** **Example**
...@@ -110,10 +114,10 @@ Triggers an event. ...@@ -110,10 +114,10 @@ Triggers an event.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| event | string | Yes| Event name.| | event | string | Yes| Event name.|
| ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| | ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.|
**Example** **Example**
......
...@@ -120,7 +120,7 @@ Creates an **AudioRecorder** instance to control audio recording. ...@@ -120,7 +120,7 @@ Creates an **AudioRecorder** instance to control audio recording.
**Example** **Example**
```js ```js
let audiorecorder = media.createAudioRecorder(); let audioRecorder = media.createAudioRecorder();
``` ```
## media.createVideoRecorder<sup>9+</sup> ## media.createVideoRecorder<sup>9+</sup>
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册