提交 68843626 编写于 作者: D duangavin123

Signed-off-by: duangavin123 <duanxichao@huawei.com>

Merge branch 'master' of https://gitee.com/duangavin123_admin/docs
...@@ -198,6 +198,8 @@ zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease ...@@ -198,6 +198,8 @@ zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-display.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-display.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
...@@ -316,6 +318,8 @@ zh-cn/application-dev/reference/apis/js-apis-testRunner.md @HelloCrease ...@@ -316,6 +318,8 @@ zh-cn/application-dev/reference/apis/js-apis-testRunner.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-uitest.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-uitest.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @zengyawen
zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @HelloCrease
zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @HelloCrease
zh-cn/application-dev/quick-start/start-overview.md @ge-yafang zh-cn/application-dev/quick-start/start-overview.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang
......
...@@ -38,13 +38,13 @@ ...@@ -38,13 +38,13 @@
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filepath" name="en/contribute" desc="already checked"/> <filteritem type="filepath" name="en/contribute/.*" desc="already checked"/>
</filefilter> </filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies"> <filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filepath" name="en/contribute" desc="already checked"/> <filteritem type="filepath" name="en/contribute/.*" desc="already checked"/>
</filefilter> </filefilter>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies"> <filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
......
...@@ -22,9 +22,11 @@ ...@@ -22,9 +22,11 @@
- OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。
该已更新至OpenHarmony 3.1.1 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.1-release.md)了解版本详情。
- OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。 - OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。
该版本已更新至OpenHarmony 3.0.3 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.3-LTS.md)了解版本详情。 该版本已更新至OpenHarmony 3.0.5 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md)了解版本详情。
- OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。 - OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。
...@@ -47,4 +49,8 @@ OpenHarmony_v1.x_release:OpenHarmony 1.1.4 LTS稳定版本,点击[此处](zh ...@@ -47,4 +49,8 @@ OpenHarmony_v1.x_release:OpenHarmony 1.1.4 LTS稳定版本,点击[此处](zh
您可以对现有文档进行评价、简单更改、反馈文档质量问题、贡献您的原创内容,详细请参考[贡献文档](zh-cn/contribute/贡献文档.md) 您可以对现有文档进行评价、简单更改、反馈文档质量问题、贡献您的原创内容,详细请参考[贡献文档](zh-cn/contribute/贡献文档.md)
卓越贡献者将会在开发者社区文档贡献专栏表彰公示。 卓越贡献者将会在开发者社区文档贡献专栏表彰公示。
\ No newline at end of file
- 邮件列表:docs@openharmony.io
- Zulip群组:documentation_sig
\ No newline at end of file
...@@ -29,6 +29,3 @@ In addition, the following differences exist in the development process: ...@@ -29,6 +29,3 @@ In addition, the following differences exist in the development process:
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility)
...@@ -26,17 +26,3 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy** ...@@ -26,17 +26,3 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy**
An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other. An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other.
![fa-threading-model](figures/fa-threading-model.png) ![fa-threading-model](figures/fa-threading-model.png)
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [`DistributeCalc`: Distributed Calculator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc)
- [`DistributeGraffiti`: Distributed Graffiti (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti)
- [Remote FA Startup](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA)
- [Distributed News App](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo)
- [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)
- [Distributed Authentication (JS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH)
- [Distributed Game Controller (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication)
- [Distributed Mail System (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS)
- [Distributed Jigsaw Puzzle (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame)
- [Distributed Control (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS)
# Data Ability Development # Data Ability Development
## When to Use ## When to Use
A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices. A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices.
Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs. Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs.
## URI Introduction
A Uniform Resource Identifier (URI) is used to identify a specific data item, such as a table in the database or a file on the disk. URIs used in OpenHarmony comply with the commonly used URI standard. A URI consists of the components:
![fa-dataability-uri](figures/fa-dataability-uri.png)
- **scheme**: name of the scheme used by the Data ability. The value is fixed at **dataability**.
- **authority**: device ID. To access data on a remote device, set this component to the ID of the remote device. To access data on the local device, leave this component empty.
- **path**: location of the specific resource to access.
- **query**: query parameters.
- **fragment**: subordinate resources to access.
Example URIs:
- Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10*
- Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10*
> **NOTE**
>
> In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**.
## Available APIs ## Available APIs
**Table 1** Data ability lifecycle APIs **Table 1** Data ability lifecycle APIs
...@@ -129,7 +154,7 @@ The basic dependency packages include: ...@@ -129,7 +154,7 @@ The basic dependency packages include:
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb' import ohos_data_rdb from '@ohos.data.rdb'
var urivar = "dataability:///com.ix.DataAbility" var urivar = "dataability:///com.ix.DataAbility"
var DAHelper = featureAbility.acquireDataAbilityHelper( var DAHelper = featureAbility.acquireDataAbilityHelper(
urivar urivar
...@@ -283,9 +308,3 @@ The basic dependency packages include: ...@@ -283,9 +308,3 @@ The basic dependency packages include:
] ]
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop Data abilities:
- [`DataAbility`: Creation and Access of Data Abilities (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility)
...@@ -349,8 +349,3 @@ Now you've got a widget shown below. ...@@ -349,8 +349,3 @@ Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
## Samples
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)
...@@ -217,7 +217,3 @@ export default { ...@@ -217,7 +217,3 @@ export default {
}, },
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop a Page ability:
- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
...@@ -134,7 +134,7 @@ You can use either of the following methods to connect to a Service ability: ...@@ -134,7 +134,7 @@ You can use either of the following methods to connect to a Service ability:
```javascript ```javascript
import prompt from '@system.prompt' import prompt from '@system.prompt'
let mRemote; let mRemote;
function onConnectCallback(element, remote){ function onConnectCallback(element, remote){
console.log('onConnectLocalService onConnectDone element: ' + element); console.log('onConnectLocalService onConnectDone element: ' + element);
...@@ -161,13 +161,13 @@ You can use either of the following methods to connect to a Service ability: ...@@ -161,13 +161,13 @@ You can use either of the following methods to connect to a Service ability:
}).catch((e) => { }).catch((e) => {
console.log('sendRequest error:' + e); console.log('sendRequest error:' + e);
}); });
} }
function onDisconnectCallback(element){ function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect Callback') console.log('ConnectAbility onDisconnect Callback')
} }
function onFailedCallback(code){ function onFailedCallback(code){
console.log('ConnectAbility onFailed Callback') console.log('ConnectAbility onFailed Callback')
} }
...@@ -196,7 +196,7 @@ You can use either of the following methods to connect to a Service ability: ...@@ -196,7 +196,7 @@ You can use either of the following methods to connect to a Service ability:
```javascript ```javascript
import rpc from "@ohos.rpc"; import rpc from "@ohos.rpc";
let mMyStub; let mMyStub;
export default { export default {
onStart() { onStart() {
...@@ -424,9 +424,3 @@ export default { ...@@ -424,9 +424,3 @@ export default {
} }
}; };
``` ```
## Samples
The following samples are provided to help you better understand how to develop a Service ability:
- [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility)
- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
...@@ -317,7 +317,3 @@ struct Index { ...@@ -317,7 +317,3 @@ struct Index {
} }
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop an ability on the stage model:
- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
...@@ -247,7 +247,3 @@ try { ...@@ -247,7 +247,3 @@ try {
Logger.error(TAG, `caller release failed with ${error}`) Logger.error(TAG, `caller release failed with ${error}`)
} }
``` ```
## Samples
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)
...@@ -358,8 +358,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -358,8 +358,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
Now you've got a widget shown below. Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
## Samples
The following sample is provided to help you better understand how to develop a widget on the stage model:
- [`FormExtAbility`: Stage Model Widget (eTS, JS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility)
...@@ -50,7 +50,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -50,7 +50,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
onRemoteRequest(code, data, reply, option) { onRemoteRequest(code, data, reply, option) {
} }
} }
class ServiceExt extends ServiceExtensionAbility { class ServiceExt extends ServiceExtensionAbility {
console.log('onCreate, want:' + want.abilityName); console.log('onCreate, want:' + want.abilityName);
} }
...@@ -69,7 +69,3 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -69,7 +69,3 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
} }
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop Service Extension abilities:
- [`ServiceExtAbility`: Stage Extension Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
...@@ -71,7 +71,3 @@ httpRequest.request( ...@@ -71,7 +71,3 @@ httpRequest.request(
} }
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`Http`: HTTP Data Request (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Http)
...@@ -122,7 +122,3 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -122,7 +122,3 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close'); tcp.off('close');
}, 30 * 1000); }, 30 * 1000);
``` ```
## Samples
The following sample is provided to help you better understand how to develop the socket connection feature:
- [`Socket`: Socket Connection (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Socket)
# Preferences Development # Preferences Development
> **NOTE**
>
> This feature is supported since API Version 9. For the versions earlier than API Version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
## When to Use ## When to Use
Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs. Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs.
## Available APIs ## Available APIs
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md).
### Creating a Preferences Instance ### Creating a Preferences Instance
...@@ -26,7 +30,7 @@ Call the **put()** method to add or modify data in a **Preferences** instance. ...@@ -26,7 +30,7 @@ Call the **put()** method to add or modify data in a **Preferences** instance.
| Class | API | Description | | Class | API | Description |
| ------- | -------------------------------------------------- | ----------------------------------------------- | | ------- | -------------------------------------------------- | ----------------------------------------------- |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data of the number, string, and Boolean types.| | Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Reading Data ### Reading Data
...@@ -36,7 +40,7 @@ Call the **get()** method to read data from a **Preferences** instance. ...@@ -36,7 +40,7 @@ Call the **get()** method to read data from a **Preferences** instance.
| Class | API | Description | | Class | API | Description |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- | | ------- | ---------------------------------------------------------- | ----------------------------------------------- |
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Reads data of the number, string, and Boolean types.| | Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Storing Data Persistently ### Storing Data Persistently
...@@ -67,7 +71,7 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -67,7 +71,7 @@ Use the following APIs to delete a **Preferences** instance or data file.
| Package | API | Description | | Package | API | Description |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ | | ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise<void>; | Deletes a **Preferences** instance from the cache and deletes its file from the device.| | ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void>; | Deletes a **Preferences** instance from the cache and deletes its file from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory. | ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory.
## How to Develop ## How to Develop
...@@ -91,8 +95,8 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -91,8 +95,8 @@ Use the following APIs to delete a **Preferences** instance or data file.
```js ```js
promise.then((preferences) => { promise.then((preferences) => {
let getPromise = preferences.put('startup', 'auto') let putPromise = preferences.put('startup', 'auto')
getPromise.then(() => { putPromise.then(() => {
console.info("Put the value of startup successfully.") console.info("Put the value of startup successfully.")
}).catch((err) => { }).catch((err) => {
console.info("Failed to put the value of startup with err: " + err) console.info("Failed to put the value of startup with err: " + err)
......
...@@ -34,40 +34,52 @@ ...@@ -34,40 +34,52 @@
1. To obtain data from a type of sensor, configure the requested permissions in the **config.json** file. 1. To obtain data from a type of sensor, configure the requested permissions in the **config.json** file.
``` ```
"reqPermissions":[ "reqPermissions": [
{ {
"name":"ohos.permission.ACCELEROMETER", "name": "ohos.permission.ACCELEROMETER",
"reason"":"", "reason": "",
"usedScene":{ "usedScene": {
"ability": ["sensor.index.MainAbility",".MainAbility"], "ability": [
"when":"inuse" "sensor.index.MainAbility",
} ".MainAbility"
}, ],
{ "when": "inuse"
"name":"ohos.permission.GYROSCOPE", }
"reason"":"", },
"usedScene":{ {
"ability": ["sensor.index.MainAbility",".MainAbility"], "name": "ohos.permission.GYROSCOPE",
"when":"inuse" "reason": "",
} "usedScene": {
}, "ability": [
{ "sensor.index.MainAbility",
"name":"ohos.permission.ACTIVITY_MOTION", ".MainAbility"
"reason"":"ACTIVITY_MOTION_TEST", ],
"usedScene":{ "when": "inuse"
"ability": ["sensor.index.MainAbility",".MainAbility"], }
"when":"inuse" },
} {
}, "name": "ohos.permission.ACTIVITY_MOTION",
{ "reason": "ACTIVITY_MOTION_TEST",
"name":"ohos.permission.READ_HEALTH_DATA", "usedScene": {
"reason"":"HEALTH_DATA_TEST", "ability": [
"usedScene":{ "sensor.index.MainAbility",
"ability": ["sensor.index.MainAbility",".MainAbility"], ".MainAbility"
"when":"inuse" ],
} "when": "inuse"
}, }
] },
{
"name": "ohos.permission.READ_HEALTH_DATA",
"reason": "HEALTH_DATA_TEST",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
}
]
``` ```
2. Subscribe to data changes of a type of sensor. 2. Subscribe to data changes of a type of sensor.
...@@ -75,7 +87,7 @@ ...@@ -75,7 +87,7 @@
``` ```
import sensor from "@ohos.sensor" import sensor from "@ohos.sensor"
sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){ sensor.on(sensor.sensorType.SENSOR_TYPE_ACCELEROMETER,function(data){
console.info("Subscription succeeded. data = "+ data); // The call is successful, and the obtained sensor data is printed. console.info("Subscription succeeded. data = " + data); // The call is successful, and the obtained sensor data is printed.
} }
); );
``` ```
...@@ -123,8 +135,3 @@ ...@@ -123,8 +135,3 @@
console.error(error); console.error(error);
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop sensors:
- [`Sensor`: sensor (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor)
# Sensor Overview # Sensor Overview
Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the APIs provided by sensors, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications. Sensors in OpenHarmony are an abstraction of underlying sensor hardware. Your application can access the underlying sensor hardware via the sensors. Using the [Sensor](../reference/apis/js-apis-sensor.md) APIs, you can query sensors on your device, subscribe to sensor data, customize algorithms based on sensor data, and develop various sensor-based applications, such as compass, motion-controlled games, and fitness and health applications.
A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows: A sensor is a device to detect events or changes in an environment and send messages about the events or changes to another device (for example, a CPU). Generally, a sensor is composed of sensitive components and conversion components. Sensors are the cornerstone of the IoT. A unified sensor management framework is required to achieve data sensing at a low latency and low power consumption, thereby keeping up with requirements of "1+8+N" products or business in the Seamless AI Life Strategy. The sensor list is as follows:
| Type | Name | Description | Usage | | Type | Name | Description | Usage |
| --------------------------------------- | ------------------ | ------------------------------------------------------------ | ---------------------------------------- | | --------------------------------------- | --------- | ---------------------------------------- | -------------------- |
| SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status | | SENSOR_TYPE_ACCELEROMETER | Acceleration sensor | Measures the acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the motion status |
| SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation | | SENSOR_TYPE_ACCELEROMETER_UNCALIBRATED | Uncalibrated acceleration sensor| Measures the uncalibrated acceleration (including the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the acceleration bias estimation |
| SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis | | SENSOR_TYPE_LINEAR_ACCELERATION | Linear acceleration sensor | Measures the linear acceleration (excluding the gravity acceleration) applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Detecting the linear acceleration in each axis |
| SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity | | SENSOR_TYPE_GRAVITY | Gravity sensor | Measures the gravity acceleration applied to a device on three physical axes (X, Y, and Z), in the unit of m/s<sup>2</sup>.| Measuring the gravity |
| SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity | | SENSOR_TYPE_GYROSCOPE | Gyroscope sensor | Measures the rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the rotation angular velocity |
| SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity | | SENSOR_TYPE_GYROSCOPE_UNCALIBRATED | Uncalibrated gyroscope sensor| Measures the uncalibrated rotation angular velocity of a device on three physical axes (X, Y, and Z), in the unit of rad/s.| Measuring the bias estimation of the rotation angular velocity |
| SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device | | SENSOR_TYPE_SIGNIFICANT_MOTION | Significant motion sensor | Checks whether a device has a significant motion on three physical axes (X, Y, and Z). The value **0** means that the device does not have a significant motion, and **1** means the opposite.| Detecting significant motions of a device |
| SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step | | SENSOR_TYPE_PEDOMETER_DETECTION | Pedometer detection sensor | Detects whether a user takes a step. The value can be **0** (the user does not take a step) or **1** (the user takes a step).| Detecting whether a user takes a step |
| SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked | | SENSOR_TYPE_PEDOMETER | Pedometer sensor | Records the number of steps a user has walked. | Providing the number of steps a user has walked |
| SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature | | SENSOR_TYPE_AMBIENT_TEMPERATURE | Ambient temperature sensor | Measures the ambient temperature, in the unit of degree Celsius (°C). | Measuring the ambient temperature |
| SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass | | SENSOR_TYPE_MAGNETIC_FIELD | Magnetic field sensor | Measures the magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Creating a compass |
| SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation | | SENSOR_TYPE_MAGNETIC_FIELD_UNCALIBRATED | Uncalibrated magnetic field sensor | Measures the uncalibrated magnetic field on three physical axes (X, Y, and Z), in the unit of μT.| Measuring the magnetic field bias estimation |
| SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity | | SENSOR_TYPE_HUMIDITY | Humidity sensor | Measures the ambient relative humidity, in a percentage (%). | Monitoring the dew point, absolute humidity, and relative humidity |
| SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar. | Measuring the barometric pressure | | SENSOR_TYPE_BAROMETER | Barometer sensor | Measures the barometric pressure, in the unit of hPa or mbar.| Measuring the barometric pressure |
| SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad.| Providing the three orientation angles of the screen | | SENSOR_TYPE_ORIENTATION | Orientation sensor | Measures the rotation angles of a device on three physical axes (X, Y, and Z), in the unit of rad. | Providing the three orientation angles of the screen |
| SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor.| Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system | | SENSOR_TYPE_ROTATION_VECTOR | Rotation vector sensor | Measures the rotation vector of a device. It is a composite sensor that generates data from the acceleration sensor, magnetic field sensor, and gyroscope sensor. | Detecting the orientation of a device in the East, North, Up (ENU) Cartesian coordinate system |
| SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call | | SENSOR_TYPE_PROXIMITY | Proximity sensor | Measures the distance between a visible object and the device screen. | Measuring the distance between a person and the device during a call |
| SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top| | SENSOR_TYPE_AMBIENT_LIGHT | Ambient light sensor | Measures the ambient light intensity of a device, in the unit of lux. | Automatically adjusting the screen brightness and checking whether the screen is covered on the top|
| SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data | | SENSOR_TYPE_HEART_RATE | Heart rate sensor | Measures the heart rate of a user. | Providing users' heart rate data |
| SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables | | SENSOR_TYPE_WEAR_DETECTION | Wear detection sensor | Checks whether a user is wearing a wearable device. | Detecting wearables |
| SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device | | SENSOR_TYPE_HALL | Hall effect sensor | Detects a magnetic field around a device. | Smart cover mode of the device |
## Working Principles ## Working Principles
...@@ -54,12 +54,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso ...@@ -54,12 +54,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
Table 7 Sensor data permissions Table 7 Sensor data permissions
| Sensor | Permission | Sensitivity | Permission Description | | Sensor | Permission | Sensitivity | Permission Description |
| ------------------------- | -------------------------------- | ------------ | ----------------------- | | ------------------------- | -------------------------------- | ------------ | ----------------------- |
| Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.| | Acceleration sensor, uncalibrated acceleration sensor, and linear acceleration sensor| ohos.permission.ACCELEROMETER | system_grant | Allows an application to subscribe to data of these acceleration-related sensors in the motion category.|
| Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.| | Gyroscope sensor and uncalibrated gyroscope sensor | ohos.permission.GYROSCOPE | system_grant | Allows an application to subscribe to data of the gyroscope-related sensors in the motion category.|
| Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. | | Pedometer sensor | ohos.permission.ACTIVITY_MOTION | user_grant | Allows an application to subscribe to the motion status. |
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. | | Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
......
...@@ -5,17 +5,19 @@ ...@@ -5,17 +5,19 @@
You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls. You can set different vibration effects as needed, for example, customizing the vibration intensity, frequency, and duration for button touches, alarm clocks, and incoming calls.
For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md).
## Available APIs ## Available APIs
| Module | API | Description | | Module | API | Description |
| ------------- | ---------------------------------------- | ------------------------------- | | ------------- | ---------------------------------------- | ------------------------------- |
| ohos.vibrator | vibrate(duration:&nbsp;number):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result. | | ohos.vibrator | vibrate(duration: number): Promise&lt;void&gt; | Triggers vibration with the specified duration. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(duration:&nbsp;number,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified duration. This API uses a callback to return the result. | | ohos.vibrator | vibrate(duration: number, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified duration. This API uses a callback to return the result. |
| ohos.vibrator | vibrate(effectId:&nbsp;EffectId):&nbsp;Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result. | | ohos.vibrator | vibrate(effectId: EffectId): Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise to return the result. |
| ohos.vibrator | vibrate(effectId:&nbsp;EffectId,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Triggers vibration with the specified effect. This API uses a callback to return the result.| | ohos.vibrator | vibrate(effectId: EffectId, callback?: AsyncCallback&lt;void&gt;): void | Triggers vibration with the specified effect. This API uses a callback to return the result.|
| ohos.vibrator | stop(stopMode:&nbsp;VibratorStopMode):&nbsp;Promise&lt;void&gt; | Stops vibration. This API uses a promise to return the result. | | ohos.vibrator | stop(stopMode: VibratorStopMode): Promise&lt;void&gt; | Stops vibration. This API uses a promise to return the result. |
| ohos.vibrator | stop(stopMode:&nbsp;VibratorStopMode,&nbsp;callback?:&nbsp;AsyncCallback&lt;void&gt;):&nbsp;void | Stops vibration. This API uses a callback to return the result. | | ohos.vibrator | stop(stopMode: VibratorStopMode, callback?: AsyncCallback&lt;void&gt;): void | Stops vibration. This API uses a callback to return the result. |
## How to Develop ## How to Develop
...@@ -24,36 +26,36 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -24,36 +26,36 @@ You can set different vibration effects as needed, for example, customizing the
``` ```
"reqPermissions": [ "reqPermissions": [
{ {
"name": "ohos.permission.ACCELEROMETER", "name": "ohos.permission.ACCELEROMETER",
"reason": "", "reason": "",
"usedScene": { "usedScene": {
"ability": [ "ability": [
".MainAbility" ".MainAbility"
], ],
"when": "inuse" "when": "inuse"
} }
}, },
{ {
"name": "ohos.permission.VIBRATE", "name": "ohos.permission.VIBRATE",
"reason": "", "reason": "",
"usedScene": { "usedScene": {
"ability": [ "ability": [
".MainAbility" ".MainAbility"
], ],
"when": "inuse" "when": "inuse"
} }
}, },
{ {
"name": "ohos.permission.ACTIVITY_MOTION", "name": "ohos.permission.ACTIVITY_MOTION",
"reason": "", "reason": "",
"usedScene": { "usedScene": {
"ability": [ "ability": [
".MainAbility" ".MainAbility"
], ],
"when": "inuse" "when": "inuse"
} }
}, },
] ]
``` ```
...@@ -61,12 +63,12 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -61,12 +63,12 @@ You can set different vibration effects as needed, for example, customizing the
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error)=>{ vibrator.vibrate(1000).then((error) => {
if (error){ // The call fails, and error.code and error.message are printed. if (error) { // The call fails, and error.code and error.message are printed.
Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); Console.log("Promise return failed.error.code " + error.code + "error.message " + error.message);
}else{ // The call is successful, and the device starts to vibrate. } else { // The call is successful, and the device starts to vibrate.
Console.log("Promise returned to indicate a successful vibration.") Console.log("Promise returned to indicate a successful vibration.")
}; }
}) })
``` ```
...@@ -74,17 +76,11 @@ You can set different vibration effects as needed, for example, customizing the ...@@ -74,17 +76,11 @@ You can set different vibration effects as needed, for example, customizing the
``` ```
import vibrator from "@ohos.vibrator" import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => {
if(error){ // The call fails, and error.code and error.message are printed. if (error) { // The call fails, and error.code and error.message are printed.
Console.log("Promise return failed.error.code"+error.code+"error.message"+error.message); Console.log("Promise return failed.error.code " + error.code + "error.message " + error.message);
}else{ // The call is successful, and the device stops vibrating. } else { // The call is successful, and the device stops vibrating.
Console.log("Promise returned to indicate a successful stop."); Console.log("Promise returned to indicate a successful stop.");
}; }
}) })
``` ```
## Samples
The following sample is provided to help you better understand how to develop vibrators:
- [`Vibrator`: vibrator (eTS, API 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Vibrator)
...@@ -88,9 +88,3 @@ In this example, an application event is logged after the application startup ex ...@@ -88,9 +88,3 @@ In this example, an application event is logged after the application startup ex
``` ```
2. Tap the run button on the application UI to run the project. 2. Tap the run button on the application UI to run the project.
## Samples
The following sample is provided to help you better understand how to develop the application event logging feature:
- [`JsDotTest`: Event Logging Test (JavaScript) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/DFX/JsDotTest)
# Internationalization Development (i18n) # Internationalization Development (I18N)
This development guide describes how to use i18n APIs that are not defined in ECMA 402. This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N interfaces that are not defined in ECMA 402.
The [Intl](intl-guidelines.md) module provides basic I18N capabilities through the standard I18N interfaces defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities.
## Obtaining System Language and Region Information ## Obtaining System Language and Region Information
......
# Internationalization Development (intl) # Internationalization Development (Intl)
This development guide describes how to use i18n APIs that are defined in ECMA 402. This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N interfaces defined in ECMA 402.
The [I18N](i18n-guidelines.md) module provides enhanced I18N capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities.
> **NOTE**<br> > **NOTE**<br>
> In the code snippets in this document, **intl** refers to the name of the imported module. > In the code snippets in this document, **intl** refers to the name of the imported module.
...@@ -49,21 +50,21 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ...@@ -49,21 +50,21 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
2. Obtain the string representing a **Locale** object.<br> 2. Obtain the string representing a **Locale** object.<br>
Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options. Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options.
``` ```
var localeStr = localeObj.toString(); var localeStr = localeObj.toString();
``` ```
3. Maximize locale information.<br> 3. Maximize locale information.<br>
Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information.
``` ```
var maximizedLocale = localeObj.maximize(); var maximizedLocale = localeObj.maximize();
``` ```
4. Minimize locale information.<br> 4. Minimize locale information.<br>
Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information.
``` ```
var minimizedLocale = localeObj.minimize(); var minimizedLocale = localeObj.minimize();
``` ```
...@@ -104,7 +105,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -104,7 +105,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
2. Format the date and time.<br> 2. Format the date and time.<br>
Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result.
``` ```
Date date = new Date(); Date date = new Date();
var formatResult = dateTimeFormat.format(date); var formatResult = dateTimeFormat.format(date);
...@@ -112,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -112,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
3. Format a period.<br> 3. Format a period.<br>
Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
``` ```
Date startDate = new Date(); Date startDate = new Date();
Date endDate = new Date(); Date endDate = new Date();
...@@ -121,7 +122,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -121,7 +122,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
4. Obtain attributes of the **DateTimeFormat** object.<br> 4. Obtain attributes of the **DateTimeFormat** object.<br>
Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object.
``` ```
var options = dateTimeFormat.resolvedOptions(); var options = dateTimeFormat.resolvedOptions();
``` ```
...@@ -161,7 +162,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for ...@@ -161,7 +162,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
2. Format a number.<br> 2. Format a number.<br>
Call the **format** method to format a number. A string is returned as the formatting result. Call the **format** method to format a number. A string is returned as the formatting result.
``` ```
var number = 1234.5678 var number = 1234.5678
var formatResult = numberFormat.format(number); var formatResult = numberFormat.format(number);
...@@ -169,7 +170,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for ...@@ -169,7 +170,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
3. Obtain attributes of the **NumberFormat** object.<br> 3. Obtain attributes of the **NumberFormat** object.<br>
Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object.
``` ```
var options = numberFormat.resolvedOptions(); var options = numberFormat.resolvedOptions();
``` ```
...@@ -208,7 +209,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ...@@ -208,7 +209,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
2. Compare two strings.<br> 2. Compare two strings.<br>
Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths.
``` ```
var str1 = "first string"; var str1 = "first string";
var str2 = "second string"; var str2 = "second string";
...@@ -217,7 +218,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ...@@ -217,7 +218,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
3. Obtain attributes of the **Collator** object.<br> 3. Obtain attributes of the **Collator** object.<br>
Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object.
``` ```
var options = collator.resolvedOptions(); var options = collator.resolvedOptions();
``` ```
...@@ -255,7 +256,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu ...@@ -255,7 +256,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
2. Determine the singular-plural type.<br> 2. Determine the singular-plural type.<br>
Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**.
``` ```
var number = 1234.5678 var number = 1234.5678
var categoryResult = plurals.select(number); var categoryResult = plurals.select(number);
...@@ -296,7 +297,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -296,7 +297,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
2. Format the relative time.<br> 2. Format the relative time.<br>
Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result. Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result.
``` ```
var number = 2; var number = 2;
var unit = "year" var unit = "year"
...@@ -305,7 +306,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -305,7 +306,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
3. Obtain each part of the relative time format.<br> 3. Obtain each part of the relative time format.<br>
Upon obtaining each part of the relative time format, customize the relative time formatting result. Upon obtaining each part of the relative time format, customize the relative time formatting result.
``` ```
var number = 2; var number = 2;
var unit = "year" var unit = "year"
...@@ -314,13 +315,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -314,13 +315,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
4. Obtain attributes of the **RelativeTimeFormat** object.<br> 4. Obtain attributes of the **RelativeTimeFormat** object.<br>
Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md). Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md).
``` ```
var options = numberFormat.resolvedOptions(); var options = numberFormat.resolvedOptions();
``` ```
## Samples
The following sample is provided to help you better understand how to develop internationalization capabilities:
-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/UI/International)
...@@ -9,14 +9,15 @@ ...@@ -9,14 +9,15 @@
- [Audio Capture Development](audio-capturer.md) - [Audio Capture Development](audio-capturer.md)
- [OpenSL ES Audio Playback Development](opensles-playback.md) - [OpenSL ES Audio Playback Development](opensles-playback.md)
- [OpenSL ES Audio Recording Development](opensles-capture.md) - [OpenSL ES Audio Recording Development](opensles-capture.md)
- [Audio Interruption Mode Development](audio-interruptmode.md)
- Video - Video
- [Video Playback Development](video-playback.md) - [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md) - [Video Recording Development](video-recorder.md)
- Image - Image
- [Image Development](image.md) - [Image Development](image.md)
- Camera - Camera
- [Camera Development](camera.md) - [Camera Development](camera.md)
# Audio Interruption Mode Development
## When to Use
The audio interruption mode is used to control the playback of multiple audio streams.<br>
Audio applications can set the audio interruption mode to independent or shared under **AudioRenderer**.<br>
In shared mode, multiple audio streams share one session ID. In independent mode, each audio stream has an independent session ID.
### Asynchronous Operations
To prevent the UI thread from being blocked, most **AudioRenderer** calls are asynchronous. Each API provides the callback and promise functions. The following examples use the promise functions.
## How to Develop
For details about the APIs, see [AudioRenderer in Audio Management](../reference/apis/js-apis-audio.md#audiorenderer8).
1. Use **createAudioRenderer()** to create an **AudioRenderer** instance.<br>
Set parameters of the **AudioRenderer** instance in **audioRendererOptions**.<br>
This instance is used to render audio, control and obtain the rendering status, and register a callback for notification.<br>
```js
import audio from '@ohos.multimedia.audio';
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_1,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioRendererInfo = {
content: audio.ContentType.CONTENT_TYPE_SPEECH,
usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION,
rendererFlags: 1
}
var audioRendererOptions = {
streamInfo: audioStreamInfo,
rendererInfo: audioRendererInfo
}
let audioRenderer = await audio.createAudioRenderer(audioRendererOptions);
```
2. Set the audio interruption mode.
After the **AudioRenderer** instance is initialized, you can set the audio interruption mode.<br>
```js
var mode_ = audio.InterruptMode.SHARE_MODE;
await this.audioRenderer.setInterruptMode(mode_).then(()=>{
console.log('[JSAR] [SetInterruptMode] Setting: '+ (mode_ == 0? " share mode":"independent mode") + "success");
});
```
...@@ -39,36 +39,36 @@ function printfDescription(obj) { ...@@ -39,36 +39,36 @@ function printfDescription(obj) {
// Set the player callbacks. // Set the player callbacks.
function setCallBack(audioPlayer) { function setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // The play() API can be invoked only after the dataLoad event callback is complete. The play event callback is then triggered. audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
}); });
audioPlayer.on('play', () => { // Set the play event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.pause(); // Trigger the pause event callback and pause the playback. audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
}); });
audioPlayer.on('pause', () => { // Set the pause event callback. audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success'); console.info('audio pause success');
audioPlayer.seek(5000); // Trigger the timeUpdate event callback, and seek to 5000 ms for playback. audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
}); });
audioPlayer.on('stop', () => { // Set the stop event callback. audioPlayer.on('stop', () => { // Set the 'stop' event callback.
console.info('audio stop success'); console.info('audio stop success');
audioPlayer.reset(); // Trigger the reset event callback, and reconfigure the src attribute to switch to the next song. audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
}); });
audioPlayer.on('reset', () => { // Set the reset event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success'); console.info('audio reset success');
audioPlayer.release(); // Release the AudioPlayer resources. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the timeUpdate event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') { if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail'); console.info('audio seek fail');
return; return;
} }
console.info('audio seek success, and seek time is ' + seekDoneTime); console.info('audio seek success, and seek time is ' + seekDoneTime);
audioPlayer.setVolume(0.5); // Trigger the volumeChange event callback. audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
}); });
audioPlayer.on('volumeChange', () => { // Set the volumeChange event callback. audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success'); console.info('audio volumeChange success');
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') { if (typeof (arrlist) != 'undefined') {
...@@ -78,13 +78,13 @@ function setCallBack(audioPlayer) { ...@@ -78,13 +78,13 @@ function setCallBack(audioPlayer) {
} else { } else {
console.log(`audio getTrackDescription fail, error:${error.message}`); console.log(`audio getTrackDescription fail, error:${error.message}`);
} }
audioPlayer.stop(); // Trigger the stop event callback to stop the playback. audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback.
}); });
}); });
audioPlayer.on('finish', () => { // Set the finish event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
}); });
audioPlayer.on('error', (error) => { // Set the error event callback. audioPlayer.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`); console.info(`audio error called, errMessage is ${error.message}`);
...@@ -107,7 +107,7 @@ async function audioPlayerDemo() { ...@@ -107,7 +107,7 @@ async function audioPlayerDemo() {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
``` ```
...@@ -119,16 +119,16 @@ import fileIO from '@ohos.fileio' ...@@ -119,16 +119,16 @@ import fileIO from '@ohos.fileio'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the play event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { // Set the finish event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer resources. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}); });
} }
...@@ -147,7 +147,7 @@ export class AudioDemo { ...@@ -147,7 +147,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
``` ```
...@@ -161,15 +161,15 @@ export class AudioDemo { ...@@ -161,15 +161,15 @@ export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
private isNextMusic = false; private isNextMusic = false;
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the play event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.reset(); // Call the reset() API and trigger the reset event callback. audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
}); });
audioPlayer.on('reset', () => { // Set the reset event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio play success'); console.info('audio play success');
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented. this.nextMusic(audioPlayer); // Changing songs is implemented.
...@@ -193,7 +193,7 @@ export class AudioDemo { ...@@ -193,7 +193,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = nextFdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
async audioPlayerDemo() { async audioPlayerDemo() {
...@@ -210,7 +210,7 @@ export class AudioDemo { ...@@ -210,7 +210,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
``` ```
...@@ -223,12 +223,12 @@ import fileIO from '@ohos.fileio' ...@@ -223,12 +223,12 @@ import fileIO from '@ohos.fileio'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.loop = true; // Set the loop playback attribute. audioPlayer.loop = true; // Set the loop playback attribute.
audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Sets the play event callback to start loop playback. audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback.
console.info('audio play success'); console.info('audio play success');
}); });
} }
...@@ -247,17 +247,7 @@ export class AudioDemo { ...@@ -247,17 +247,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio playback:
- [`JsDistributedMusicPlayer`: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -186,12 +186,3 @@ export class AudioRecorderDemo { ...@@ -186,12 +186,3 @@ export class AudioRecorderDemo {
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio recording:
- [`Recorder`: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`JsRecorder`: Recorder (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -15,19 +15,19 @@ For details about the APIs, see [Image Processing](../reference/apis/js-apis-ima ...@@ -15,19 +15,19 @@ For details about the APIs, see [Image Processing](../reference/apis/js-apis-ima
The full process includes creating an instance, reading image information, reading and writing pixel maps, updating data, packaging pixels, and releasing resources. The full process includes creating an instance, reading image information, reading and writing pixel maps, updating data, packaging pixels, and releasing resources.
```js ```js
const Color = new ArrayBuffer(96); // Create a buffer to store image pixel data. const color = new ArrayBuffer(96); // Create a buffer to store image pixel data.
let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data. let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data.
// Create a PixelMap object. // Create a PixelMap object.
const Color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } }
image.createPixelMap(Color, opts, pixelmap => { image.createPixelMap(color, opts, pixelmap => {
expect(pixelmap !== null).assertTrue(); expect(pixelmap !== null).assertTrue();
console.info('TC_001-1 success'); console.info('TC_001-1 success');
done(); done();
}) })
// Read pixels. // Read pixels.
pixelmap.readPixels(area,(data) => { pixelmap.readPixels(area,(data) => {
if(data !== null) { if(data !== null) {
var bufferArr = new Uint8Array(area.pixels); var bufferArr = new Uint8Array(area.pixels);
var res = true; var res = true;
...@@ -50,39 +50,39 @@ pixelmap.readPixelsToBuffer(readBuffer,() => { ...@@ -50,39 +50,39 @@ pixelmap.readPixelsToBuffer(readBuffer,() => {
var bufferArr = new Uint8Array(readBuffer); var bufferArr = new Uint8Array(readBuffer);
var res = true; var res = true;
for (var i = 0; i < bufferArr.length; i++) { for (var i = 0; i < bufferArr.length; i++) {
if(res) { if(res) {
if (bufferArr[i] !== 0) { if (bufferArr[i] !== 0) {
res = false; res = false;
console.info('TC_020-1 Success'); console.info('TC_020-1 Success');
expect(true).assertTrue(); expect(true).assertTrue();
done(); done();
break; break;
} }
}
} }
}
// Write pixels. // Write pixels.
pixelmap.writePixels(area,() => { pixelmap.writePixels(area,() => {
const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }}
pixelmap.readPixels(readArea,() => { pixelmap.readPixels(readArea,() => {
var readArr = new Uint8Array(readArea.pixels); var readArr = new Uint8Array(readArea.pixels);
var res = true; var res = true;
for (var i = 0; i < readArr.length; i++) { for (var i = 0; i < readArr.length; i++) {
if(res) { if(res) {
if (readArr[i] !== 0) { if (readArr[i] !== 0) {
res = false; res = false;
console.info('TC_022-1 Success'); console.info('TC_022-1 Success');
expect(true).assertTrue(); expect(true).assertTrue();
done(); done();
break; break;
} }
}
} }
}
// Write pixels to the buffer. // Write pixels to the buffer.
pixelmap.writeBufferToPixels(writeColor).then(() => { pixelmap.writeBufferToPixels(writeColor).then(() => {
const readBuffer = new ArrayBuffer(96); const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then (() => { pixelmap.readPixelsToBuffer(readBuffer).then (() => {
var bufferArr = new Uint8Array(readBuffer); var bufferArr = new Uint8Array(readBuffer);
var res = true; var res = true;
for (var i = 0; i < bufferArr.length; i++) { for (var i = 0; i < bufferArr.length; i++) {
...@@ -95,18 +95,18 @@ pixelmap.writePixels(area,() => { ...@@ -95,18 +95,18 @@ pixelmap.writePixels(area,() => {
break; break;
} }
} }
} }
// Obtain image information. // Obtain image information.
pixelmap.getImageInfo( imageInfo => { pixelmap.getImageInfo( imageInfo => {
if (imageInfo !== null) { if (imageInfo !== null) {
console.info('TC_024-1 imageInfo is ready'); console.info('TC_024-1 imageInfo is ready');
expect(imageInfo.size.height == 4).assertTrue(); expect(imageInfo.size.height == 4).assertTrue();
expect(imageInfo.size.width == 6).assertTrue(); expect(imageInfo.size.width == 6).assertTrue();
expect(imageInfo.pixelFormat == 4).assertTrue(); expect(imageInfo.pixelFormat == 4).assertTrue();
done(); done();
} }
}) })
// Release the PixelMap object. // Release the PixelMap object.
pixelmap.release(()=>{ pixelmap.release(()=>{
...@@ -116,7 +116,7 @@ pixelmap.release(()=>{ ...@@ -116,7 +116,7 @@ pixelmap.release(()=>{
}) })
// Create an image source (uri). // Create an image source (uri).
const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.jpg' const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg'
// Create an image source (fd). // Create an image source (fd).
const imageSourceApi = image.createImageSource(29); const imageSourceApi = image.createImageSource(29);
...@@ -136,7 +136,7 @@ imagePackerApi.packing(imageSourceApi, packOpts, data => { ...@@ -136,7 +136,7 @@ imagePackerApi.packing(imageSourceApi, packOpts, data => {
console.info('TC_062-1 finished'); console.info('TC_062-1 finished');
expect(data !== null).assertTrue(); expect(data !== null).assertTrue();
done(); done();
}) })
// Release the ImagePacker object. // Release the ImagePacker object.
imagePackerApi.release(); imagePackerApi.release();
...@@ -148,7 +148,7 @@ imagePackerApi.release(); ...@@ -148,7 +148,7 @@ imagePackerApi.release();
/data/local/tmp/test.jpg // Set the path for creating an image source. /data/local/tmp/test.jpg // Set the path for creating an image source.
// Create an image source using a path. // Create an image source using a path.
const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.jpg' const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg'
// Set parameters. // Set parameters.
let decodingOptions = { let decodingOptions = {
...@@ -171,9 +171,9 @@ imageSourceApi.createPixelMap(decodingOptions, pixelmap => { ...@@ -171,9 +171,9 @@ imageSourceApi.createPixelMap(decodingOptions, pixelmap => {
// Create a pixel map in promise mode. // Create a pixel map in promise mode.
imageSourceApi.createPixelMap().then(pixelmap => { imageSourceApi.createPixelMap().then(pixelmap => {
console.info('TC_050-11 createPixelMap '); console.info('TC_050-11 createPixelMap ');
expect(pixelmap !== null ).assertTrue(); expect(pixelmap !== null ).assertTrue();
done(); done();
}) })
// Capture error information when an exception occurs during function invoking. // Capture error information when an exception occurs during function invoking.
...@@ -181,7 +181,7 @@ catch(error => { ...@@ -181,7 +181,7 @@ catch(error => {
console.log('TC_050-11 error: ' + error); console.log('TC_050-11 error: ' + error);
expect().assertFail(); expect().assertFail();
done(); done();
}) })
// Obtain the number of bytes in each line of pixels. // Obtain the number of bytes in each line of pixels.
pixelmap.getBytesNumberPerRow( num => { pixelmap.getBytesNumberPerRow( num => {
...@@ -192,13 +192,13 @@ pixelmap.getBytesNumberPerRow( num => { ...@@ -192,13 +192,13 @@ pixelmap.getBytesNumberPerRow( num => {
// Obtain the total number of pixel bytes. // Obtain the total number of pixel bytes.
pixelmap.getPixelBytesNumber(num => { pixelmap.getPixelBytesNumber(num => {
console.info('TC_026-1 num is ' + num); console.info('TC_026-1 num is ' + num);
expect(num == expectNum).assertTrue(); expect(num == expectNum).assertTrue();
done(); done();
}) })
// Obtain the pixel map information. // Obtain the pixel map information.
pixelmap.getImageInfo( imageInfo => {}) pixelmap.getImageInfo( imageInfo => {})
// Print the failure information. // Print the failure information.
console.info('TC_024-1 imageInfo is empty'); console.info('TC_024-1 imageInfo is empty');
...@@ -206,17 +206,17 @@ expect(false).assertTrue() ...@@ -206,17 +206,17 @@ expect(false).assertTrue()
// Release the PixelMap object. // Release the PixelMap object.
pixelmap.release(()=>{ pixelmap.release(()=>{
expect(true).assertTrue(); expect(true).assertTrue();
console.log('TC_027-1 suc'); console.log('TC_027-1 suc');
done(); done();
}) })
// Capture release failure information. // Capture release failure information.
catch(error => { catch(error => {
console.log('TC_027-1 error: ' + error); console.log('TC_027-1 error: ' + error);
expect().assertFail(); expect().assertFail();
done(); done();
}) })
``` ```
### Encoding Scenario ### Encoding Scenario
...@@ -225,14 +225,14 @@ catch(error => { ...@@ -225,14 +225,14 @@ catch(error => {
/data/local/tmp/test.png // Set the path for creating an image source. /data/local/tmp/test.png // Set the path for creating an image source.
// Set the image source. // Set the image source.
const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.png' const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.png'
// Print the error message if the image source fails to be created. // Print the error message if the image source fails to be created.
if (imageSourceApi == null) { if (imageSourceApi == null) {
console.info('TC_062 create image source failed'); console.info('TC_062 create image source failed');
expect(false).assertTrue(); expect(false).assertTrue();
done(); done();
} }
// Create an image packer if the image source is successfully created. // Create an image packer if the image source is successfully created.
const imagePackerApi = image.createImagePacker(); const imagePackerApi = image.createImagePacker();
...@@ -242,31 +242,58 @@ if (imagePackerApi == null) { ...@@ -242,31 +242,58 @@ if (imagePackerApi == null) {
console.info('TC_062 create image packer failed'); console.info('TC_062 create image packer failed');
expect(false).assertTrue(); expect(false).assertTrue();
done(); done();
} }
// Set encoding parameters if the image packer is successfully created. // Set encoding parameters if the image packer is successfully created.
let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg. let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg.
quality:98 }// Image quality, which ranges from 0 to 100. quality:98 } // Image quality, which ranges from 0 to 100.
// Encode the image. // Encode the image.
imagePackerApi.packing(imageSourceApi, packOpts) imagePackerApi.packing(imageSourceApi, packOpts)
.then( data => { .then( data => {
console.info('TC_062 finished'); console.info('TC_062 finished');
expect(data !== null).assertTrue(); expect(data !== null).assertTrue();
done(); done();
}) })
// Release the image packer after the encoding is complete. // Release the image packer after the encoding is complete.
imagePackerApi.release(); imagePackerApi.release();
// Obtain the image source information. // Obtain the image source information.
imageSourceApi.getImageInfo(imageInfo => { imageSourceApi.getImageInfo(imageInfo => {
console.info('TC_045 imageInfo'); console.info('TC_045 imageInfo');
expect(imageInfo !== null).assertTrue(); expect(imageInfo !== null).assertTrue();
done(); done();
}) })
// Update incremental data. // Update incremental data.
imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {}) imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {})
``` ```
### Using ImageReceiver
Example scenario: The camera functions as the client to transmit image data to the server.
```js
public async init(surfaceId: any) {
// (Server code) Create an ImageReceiver object.
var receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1);
// Obtain the surface ID.
var surfaceId = await receiver.getReceivingSurfaceId();
// Register a surface listener, which is triggered after the buffer of the surface is ready.
receiver.on('imageArrival', () => {
// Obtain the latest buffer of the surface.
receiver.readNextImage((err, img) => {
img.getComponent(4, (err, component) => {
// Consume component.byteBuffer. For example, save the content in the buffer as an image.
})
})
})
// Call a Camera API to transfer the surface ID to the camera, which then obtains the surface based on the surface ID and generates a surface buffer.
}
```
...@@ -2,10 +2,7 @@ ...@@ -2,10 +2,7 @@
## When to Use ## When to Use
You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
[OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented yet is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
## How to Develop ## How to Develop
...@@ -27,8 +24,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -27,8 +24,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
(*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
``` ```
3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface. 3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface.
```c++ ```c++
...@@ -36,8 +31,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -36,8 +31,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineItf); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineItf);
``` ```
4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance. 4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance.
```c++ ```c++
...@@ -81,21 +74,19 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -81,21 +74,19 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
``` ```
5. Obtain the **recordItf** instance of the **SL_IID_RECORD** interface. 5. Obtain the **recordItf** instance of the **SL_IID_RECORD** interface.
``` ```c++
SLRecordItf recordItf; SLRecordItf recordItf;
(*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf); (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf);
``` ```
6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. 6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface.
``` ```c++
SLOHBufferQueueItf bufferQueueItf; SLOHBufferQueueItf bufferQueueItf;
(*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf);
``` ```
7. Register the **BufferQueueCallback** function. 7. Register the **BufferQueueCallback** function.
```c++ ```c++
...@@ -120,7 +111,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -120,7 +111,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
(*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);
``` ```
8. Start audio recording. 8. Start audio recording.
```c++ ```c++
...@@ -145,7 +135,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -145,7 +135,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
} }
``` ```
9. Stop audio recording. 9. Stop audio recording.
```c++ ```c++
......
# OpenSL ES Audio Playback Development # OpenSL ES Audio Playback Development
## When to Use ## When to Use
You can use OpenSL ES to develop the audio playback function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. You can use OpenSL ES to develop the audio playback function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
## How to Develop ## How to Develop
To use OpenSL ES to develop the audio playback function in OpenHarmony, perform the following steps: To use OpenSL ES to develop the audio playback function in OpenHarmony, perform the following steps:
...@@ -20,8 +16,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -20,8 +16,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
#include <OpenSLES_Platform.h> #include <OpenSLES_Platform.h>
``` ```
2. Use the **slCreateEngine** API to obtain an **engine** instance. 2. Use the **slCreateEngine** API to obtain an **engine** instance.
```c++ ```c++
...@@ -30,8 +24,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -30,8 +24,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
``` ```
3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface. 3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface.
```c++ ```c++
...@@ -39,8 +31,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -39,8 +31,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);
``` ```
4. Configure the player and create an **AudioPlayer** instance. 4. Configure the player and create an **AudioPlayer** instance.
```c++ ```c++
...@@ -66,8 +56,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -66,8 +56,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE); (*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE);
``` ```
5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. 5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface.
``` ```
...@@ -75,8 +63,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -75,8 +63,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf);
``` ```
6. Open an audio file and register the **BufferQueueCallback** function. 6. Open an audio file and register the **BufferQueueCallback** function.
```c++ ```c++
...@@ -101,8 +87,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -101,8 +87,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);
``` ```
7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** interface and start playback. 7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** interface and start playback.
```c++ ```c++
...@@ -111,8 +95,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -111,8 +95,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);
``` ```
8. Stop audio playback. 8. Stop audio playback.
```c++ ```c++
......
...@@ -441,8 +441,3 @@ export class VideoPlayerDemo { ...@@ -441,8 +441,3 @@ export class VideoPlayerDemo {
} }
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop video playback:
- [`VideoPlayer`: Video Playback (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/media/VideoPlayer)
...@@ -8,8 +8,6 @@ During video recording, audio and video signals are captured, encoded, and saved ...@@ -8,8 +8,6 @@ During video recording, audio and video signals are captured, encoded, and saved
![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png) ![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of video recording **Figure 2** Layer 0 diagram of video recording
![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png) ![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png)
......
...@@ -200,9 +200,3 @@ The following steps describe how to use the text drawing and display feature of ...@@ -200,9 +200,3 @@ The following steps describe how to use the text drawing and display feature of
double position[2] = {10.0, 15.0}; double position[2] = {10.0, 15.0};
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); 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)
...@@ -169,9 +169,3 @@ if (this.subscriber != null) { ...@@ -169,9 +169,3 @@ if (this.subscriber != null) {
}) })
} }
``` ```
## Samples
The following sample is provided to help you better understand how to use the common event functionality:
- [`CommonEvent`: eTS Common Event (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent)
...@@ -256,10 +256,3 @@ function cancelCallback(err) { ...@@ -256,10 +256,3 @@ function cancelCallback(err) {
Notification.cancel(1, "label", cancelCallback) Notification.cancel(1, "label", cancelCallback)
``` ```
## Samples
The following sample is provided to help you better understand how to develop notification functions:
[`Notification`: EtsNotification (API 8)](https://gitee.com/openharmony/app_samples/tree/master/common/Notification)
\ No newline at end of file
...@@ -4,19 +4,19 @@ The **HarmonyAppProvision** configuration file (also called profile) is the file ...@@ -4,19 +4,19 @@ The **HarmonyAppProvision** configuration file (also called profile) is the file
## Configuration File Internal Structure ## Configuration File Internal Structure
The **HarmonyAppProvision** file consists of several parts, which are described in the table below. The **HarmonyAppProvision** file consists of several parts, which are described in the table below.
**Table 1** Configuration file internal structure **Table 1** Internal structure of the HarmonyAppProvision file
| Name | Description | Data Type| Mandatory | Initial Value Allowed| | Name | Description | Data Type| Mandatory| Initial Value Allowed|
| ----------- | ---------------------------------------------------------------------------------------- | -------- | -------- | -------- | | ----------- | ---------------------------------------------------------------------------------------- | -------- | -------- | -------- |
| version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes | No | | version-code | Version number of the **HarmonyAppProvision** file format. The value is a positive integer containing 32 or less digits.| Number | Yes| No |
| version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes | No| | version-name | Description of the version number. It is recommended that the value consist of three segments, for example, **A.B.C**. | String | Yes| No|
| uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes | No| | uuid | Unique ID of the **HarmonyAppProvision** file. | String | Yes| No|
| type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) and **release** (for application release). The recommended value is **debug**.| String | Yes | No| | type | Type of the **HarmonyAppProvision** file. The value can be **debug** (for application debugging) or **release** (for application release). The recommended value is **debug**.| String | Yes| No|
| issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes | No| | issuer | Issuer of the **HarmonyAppProvision** file. | String | Yes| No|
| validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes | No | | validity | Validity period of the **HarmonyAppProvision** file. For details, see [Internal Structure of the validity Object](#internal-structure-of-the-validity-object). | Object | Yes | No |
| bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes | No | | bundle-info | Information about the application bundle and developer. For details, see [Internal Structure of the bundle-info Object](#internal-structure-of-the-bundle-info-object). | Object | Yes| No |
| acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No | No | | acls | Information about the Access Control Lists (ACLs). For details, see [Internal Structure of the acls Object](#internal-structure-of-the-acls-object). | Object | No| No |
| permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No | No | | permissions | Permissions required for your application. For details, see [Internal Structure of the permissions Object](#internal-structure-of-the-permissions-object). | Object | No| No |
| debug-info | Additional debug information. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No | No | | debug-info | Additional information for application debugging. For details, see [Internal Structure of the debug-info Object](#internal-structure-of-the-debug-info-object). | Object | No| No |
An example of the **HarmonyAppProvision** file is as follows: An example of the **HarmonyAppProvision** file is as follows:
```json ```json
...@@ -54,46 +54,46 @@ An example of the **HarmonyAppProvision** file is as follows: ...@@ -54,46 +54,46 @@ An example of the **HarmonyAppProvision** file is as follows:
### Internal Structure of the validity Object ### Internal Structure of the validity Object
| Name | Description | Data Type| Mandatory | Initial Value Allowed| | Name | Description | Data Type| Mandatory| Initial Value Allowed|
| ---------- | ------------------------------- | ------- | ------- | --------- | | ---------- | ------------------------------- | ------- | ------- | --------- |
| not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | | not-before | Start time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No |
| not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes | No | | not-after | End time of the file validity period. The value is a Unix timestamp, which is a non-negative integer.| Number | Yes| No |
### Internal Structure of the bundle-info Object ### Internal Structure of the bundle-info Object
| Name | Description | Data Type| Mandatory | Initial Value Allowed| | Name | Description | Data Type| Mandatory| Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | -------- | --------- | | ------------------------ | ------------------------------- | ------- | -------- | --------- |
| developer-id | Unique ID of the developer.| String | Yes | No | | developer-id | Unique ID of the developer.| String | Yes| No |
| development-certificate | Information about the [debug certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No | | development-certificate | Information about the [debug certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **debug** and no otherwise | No |
| distribution-certificate | Information about the [release certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise | No | | distribution-certificate | Information about the [release certificate](../security/hapsigntool-guidelines.md).| Number | Yes if **type** is set to **release** and no otherwise| No |
| bundle-name | Bundle name of the application.| String | Yes | No | | bundle-name | Bundle name of the application.| String | Yes| No |
| apl | [Ability privilege level (APL)](../security/accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes | No | | apl | [Ability privilege level (APL)](../security/accesstoken-overview.md) of your application. The value can be **normal**, **system_basic**, or **system_core**.| String | Yes| No |
| app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (non-system application).| String | Yes | No | | app-feature | Type of your application. The value can be **hos_system_app** (system application) or **hos_normal_app** (non-system application).| String | Yes| No |
### Internal structure of the acls Object ### Internal Structure of the acls Object
The **acls** object contains the [ACLs](../security/accesstoken-overview.md) configured for your application. It should be noted that you still need to fill the ACL information in the **reqPermissions** attribute in the [config.json](package-structure.md) file. The **acls** object contains the [ACLs](../security/accesstoken-overview.md) configured for your application. It should be noted that you still need to fill the ACL information in the **reqPermissions** attribute in the [config.json](package-structure.md) file.
**Table 4** Internal structure of the acls object **Table 4** Internal structure of the acls object
| Name | Description | Data Type| Mandatory | Initial Value Allowed| | Name | Description | Data Type| Mandatory| Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- | | ------------------------ | ------------------------------- | ------- | ------- | --------- |
| allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No | No | | allowed-acls | [ACLs](../security/accesstoken-overview.md) configured for your application.| String array | No| No |
### Internal Structure of the permissions Object ### Internal Structure of the permissions Object
The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to fill the permission information in the **reqPermissions** attribute in the [config.json](package-structure.md) file. The **permissions** object contains restricted permissions required for your application. Different from the ACLs set in the **acls** object, these permissions need user authorization during the running of your application. It should be noted that you still need to fill the permission information in the **reqPermissions** attribute in the [config.json](package-structure.md) file.
**Table 5** Internal structure of the permissions object **Table 5** Internal structure of the permissions object
| Name | Description | Data Type| Mandatory | Initial Value Allowed| | Name | Description | Data Type| Mandatory| Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- | | ------------------------ | ------------------------------- | ------- | ------- | --------- |
| restricted-permissions | [Restricted permissions](../security/accesstoken-overview.md) required for your application.| String array | No | No | | restricted-permissions | [Restricted permissions](../security/accesstoken-overview.md) required for your application.| String array | No| No |
### Internal Structure of the debug-info Object ### Internal Structure of the debug-info Object
The **debug-info** object contains debug information of your application, mainly device management and control information. The **debug-info** object contains debugging information of your application, mainly device management and control information.
**Table 6** Internal structure of the debug-info object **Table 6** Internal structure of the debug-info object
| Name | Description | Data Type| Mandatory | Initial Value Allowed| | Name | Description | Data Type| Mandatory| Initial Value Allowed|
| ------------------------ | ------------------------------- | ------- | ------- | --------- | | ------------------------ | ------------------------------- | ------- | ------- | --------- |
| device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No | No | | device-id-type | Type of the device ID. Currently, only the udid type is supported.| String | No| No |
| device-ids | IDs of devices on which your application can be debugged.| String array | No | No | | device-ids | IDs of devices on which your application can be debugged.| String array | No| No |
...@@ -59,6 +59,7 @@ ...@@ -59,6 +59,7 @@
- Bundle Management - Bundle Management
- [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle](js-apis-Bundle.md)
- [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md)
- [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md)
- [@ohos.zlib](js-apis-zlib.md) - [@ohos.zlib](js-apis-zlib.md)
- bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md)
...@@ -108,6 +109,7 @@ ...@@ -108,6 +109,7 @@
- [@ohos.configPolicy](js-apis-config-policy.md) - [@ohos.configPolicy](js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md)
- [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- Security - Security
...@@ -173,6 +175,7 @@ ...@@ -173,6 +175,7 @@
- [@ohos.hichecker](js-apis-hichecker.md) - [@ohos.hichecker](js-apis-hichecker.md)
- [@ohos.hidebug](js-apis-hidebug.md) - [@ohos.hidebug](js-apis-hidebug.md)
- [@ohos.hilog](js-apis-hilog.md) - [@ohos.hilog](js-apis-hilog.md)
- [@ohos.hiSysEvent](js-apis-hisysevent.md)
- [@ohos.hiTraceChain](js-apis-hitracechain.md) - [@ohos.hiTraceChain](js-apis-hitracechain.md)
- [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - [@ohos.hiTraceMeter](js-apis-hitracemeter.md)
- [@ohos.inputMethod](js-apis-inputmethod.md) - [@ohos.inputMethod](js-apis-inputmethod.md)
...@@ -192,13 +195,13 @@ ...@@ -192,13 +195,13 @@
- [@ohos.geolocation](js-apis-geolocation.md) - [@ohos.geolocation](js-apis-geolocation.md)
- [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md)
- [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md)
- [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md)
- [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md) - [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md)
- [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md) - [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md)
- [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md)
- [@ohos.multimodalInput.keyCode](js-apis-keycode.md) - [@ohos.multimodalInput.keyCode](js-apis-keycode.md)
- [@ohos.multimodalInput.keyEvent](js-apis-keyevent.md) - [@ohos.multimodalInput.keyEvent](js-apis-keyevent.md)
- [@ohos.multimodalInput.mouseEvent](js-apis-mouseevent.md) - [@ohos.multimodalInput.mouseEvent](js-apis-mouseevent.md)
- [@ohos.multimodalInput.ToucEvent](js-apis-touchevent.md) - [@ohos.multimodalInput.touchEvent](js-apis-touchevent.md)
- [@ohos.power](js-apis-power.md) - [@ohos.power](js-apis-power.md)
- [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.runningLock](js-apis-runninglock.md)
- [@ohos.sensor](js-apis-sensor.md) - [@ohos.sensor](js-apis-sensor.md)
......
# EnterpriseAdminExtentionAbility
The **EnterpriseAdminExtentionAbility** module provides APIs for Extension abilities of enterprise administrators.
> **NOTE**
>
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import EnterpriseAdminExtentionAbility from '@ohos.EnterpriseAdminExtentionAbility'
```
## EnterpriseAdminExtentionAbility.onAdminEnabled
onAdminEnabled(): void
Called when an enterprise administrator is enabled.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**Example**
```ts
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminEnabled() {
}
};
```
## EnterpriseAdminExtentionAbility.onAdminDisabled
onAdminDisabled(): void
Called when an enterprise administrator is disabled.
**System capability**: SystemCapability.Customization.EnterpriseDeviceManager
**Example**
```ts
export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility {
onAdminDisabled() {
}
};
```
# AbilityManager
The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information.
> **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 APIs of this module are system APIs and cannot be called by third-party applications.
# Modules to Import
```js
import AbilityManager from '@ohos.application.abilityManager'
```
## AbilityState
Enumerates the ability states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Value| Description|
| -------- | -------- | -------- |
| INITIAL | 0 | The ability is in the initial state.|
| FOREGROUND | 9 | The ability is in the foreground state. |
| BACKGROUND | 10 | The ability is in the background state. |
| FOREGROUNDING | 11 | The ability is in the foregrounding state. |
| BACKGROUNDING | 12 | The ability is in the backgrounding state. |
## updateConfiguration
updateConfiguration(config: Configuration, callback: AsyncCallback\<void>): void
Obtains the ability running information. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | Configuration | Yes | New configuration.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var config = {
language: 'chinese'
}
abilitymanager.updateConfiguration(config, () => {
console.log('------------ updateConfiguration -----------');
})
```
## updateConfiguration
updateConfiguration(config: Configuration): Promise\<void>
Updates the configuration. This API uses a promise to return the result.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | Configuration | Yes | New configuration.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<void> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var config = {
language: 'chinese'
}
abilitymanager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success');
}).catch((err) => {
console.log('updateConfiguration fail');
})
```
## getAbilityRunningInfos
getAbilityRunningInfos(callback: AsyncCallback\<Array\<AbilityRunningInfo>>): void
Obtains the ability running information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<Array\<AbilityRunningInfo>> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
## getAbilityRunningInfos
getAbilityRunningInfos(): Promise\<Array\<AbilityRunningInfo>>
Obtains the ability running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<AbilityRunningInfo>> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err)
});
```
## getExtensionRunningInfos<sup>9+</sup>
getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\<Array\<ExtensionRunningInfo>>): void
Obtains the extension running information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
| callback | AsyncCallback\<Array\<AbilityRunningInfo>> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var upperLimit = 0;
abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
## getExtensionRunningInfos<sup>9+</sup>
getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>>
Obtains the extension running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<AbilityRunningInfo>> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var upperLimit = 0;
abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err);
})
```
## getTopAbility<sup>9+</sup>
getTopAbility(callback: AsyncCallback\<ElementName>): void;
Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<ElementName> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getTopAbility((err,data) => {
console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data));
});
```
## getTopAbility<sup>9+</sup>
getTopAbility(): Promise\<ElementName>;
Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<ElementName>| Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getTopAbility().then((data) => {
console.log("getTopAbility data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getTopAbility err: " + err);
})
```
# Animator # Animator
> **NOTE**<br> > **NOTE**
>
> 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.
...@@ -22,7 +23,7 @@ Creates an **Animator** object. ...@@ -22,7 +23,7 @@ Creates an **Animator** object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.| | options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -213,6 +214,8 @@ animator.oncancel(); ...@@ -213,6 +214,8 @@ animator.oncancel();
onrepeat: () => void onrepeat: () => void
Called when this animation repeats.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example** **Example**
...@@ -220,8 +223,6 @@ onrepeat: () => void ...@@ -220,8 +223,6 @@ onrepeat: () => void
animator.onrepeat(); animator.onrepeat();
``` ```
Called when this animation repeats.
## AnimatorOptions ## AnimatorOptions
Defines animator options. Defines animator options.
...@@ -231,7 +232,7 @@ Defines animator options. ...@@ -231,7 +232,7 @@ Defines animator options.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.| | 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**.| | 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.| | 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 the target will retain its end state (defined by the last keyframe) after the animation is executed. | | fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed. |
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.| | direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.|
......
# App Account Management # App Account Management
Provides app account management, including adding, deleting, querying, modifying, and authorizing app accounts, writing data to disks, and synchronizing data. The **appAccount** module provides APIs for app account management. You can use the APIs to add, delete, query, modify, and authorize app accounts, write data to disks, and synchronize data.
> **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.
...@@ -64,7 +64,7 @@ Adds an app account to the **AppAccountManager** service. This API uses an async ...@@ -64,7 +64,7 @@ Adds an app account to the **AppAccountManager** service. This API uses an async
addAccount(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;): void addAccount(name: string, extraInfo: string, callback: AsyncCallback&lt;void&gt;): void
Adds the account name and additional information (information that can be converted into the string type, such as token) of this app to the **AppAccountManager** service. This API uses an asynchronous callback to return the result. Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -91,7 +91,7 @@ Adds the account name and additional information (information that can be conver ...@@ -91,7 +91,7 @@ Adds the account name and additional information (information that can be conver
addAccount(name: string, extraInfo: string): Promise&lt;void&gt; addAccount(name: string, extraInfo: string): Promise&lt;void&gt;
Adds the account name and additional information (information that can be converted into the string type, such as token) of this app to the **AppAccountManager** service. This API uses a promise to return the result. Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses a promise to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -978,7 +978,7 @@ Unsubscribes from the account change events. This API uses an asynchronous callb ...@@ -978,7 +978,7 @@ Unsubscribes from the account change events. This API uses an asynchronous callb
authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void
Authenticates an app account to obtain the Open Authorization (OAuth) token. This API uses an asynchronous callback to return the result. Authenticates an app account to obtain an Open Authorization (OAuth) token. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -986,7 +986,7 @@ Authenticates an app account to obtain the Open Authorization (OAuth) token. Thi ...@@ -986,7 +986,7 @@ Authenticates an app account to obtain the Open Authorization (OAuth) token. Thi
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| -------- | --------------------- | ---- | --------------- | | -------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the app account to authenticate. | | name | string | Yes | Name of the target app account. |
| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. |
| authType | string | Yes | Authentication type. | | authType | string | Yes | Authentication type. |
| options | {[key: string]: any} | Yes | Options for the authentication. | | options | {[key: string]: any} | Yes | Options for the authentication. |
...@@ -1578,7 +1578,7 @@ Checks whether an app account is authorized to access an app. This API uses an a ...@@ -1578,7 +1578,7 @@ Checks whether an app account is authorized to access an app. This API uses an a
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ---------------------------- | ----- | ---------------- | | ---------- | ---------------------------- | ----- | ---------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of the app to check. | | bundleName | string | Yes | Bundle name of the app to access.|
| callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. | | callback | AsyncCallback&lt;boolean&gt; | Yes | Callback invoked to return the result. |
**Example** **Example**
...@@ -1604,7 +1604,7 @@ Checks whether an app account is authorized to access an app. This API uses a pr ...@@ -1604,7 +1604,7 @@ Checks whether an app account is authorized to access an app. This API uses a pr
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ------ | ----- | ---------------- | | ---------- | ------ | ----- | ---------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of the app to check. | | bundleName | string | Yes | Bundle name of the app to access.|
**Parameters** **Parameters**
...@@ -2002,7 +2002,7 @@ Represents the options for setting authenticator properties. ...@@ -2002,7 +2002,7 @@ Represents the options for setting authenticator properties.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------- | ---------------------- | ----- | -------------- | | ---------- | ---------------------- | ----- | -------------- |
| properties | {[key:string]: Object} | No | Authenticator properties to set. | | properties | {[key:string]: Object} | No | Authenticator properties. |
| parameters | {[key:string]: Object} | No | Customized parameters.| | parameters | {[key:string]: Object} | No | Customized parameters.|
## Constants<sup>8+</sup> ## Constants<sup>8+</sup>
...@@ -2037,7 +2037,7 @@ Enumerates the result codes. ...@@ -2037,7 +2037,7 @@ Enumerates the result codes.
| ----------------------------------- | ----- | ------------ | | ----------------------------------- | ----- | ------------ |
| SUCCESS | 0 | The operation is successful. | | SUCCESS | 0 | The operation is successful. |
| ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | | ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. |
| ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The app account service is abnormal. | | ERROR_APP_ACCOUNT_SERVICE_EXCEPTION | 10002 | The **AppAccountManager** service is abnormal. |
| ERROR_INVALID_PASSWORD | 10003 | The password is invalid. | | ERROR_INVALID_PASSWORD | 10003 | The password is invalid. |
| ERROR_INVALID_REQUEST | 10004 | The request is invalid. | | ERROR_INVALID_REQUEST | 10004 | The request is invalid. |
| ERROR_INVALID_RESPONSE | 10005 | The response is invalid. | | ERROR_INVALID_RESPONSE | 10005 | The response is invalid. |
...@@ -2063,7 +2063,7 @@ Provides OAuth authenticator callbacks. ...@@ -2063,7 +2063,7 @@ Provides OAuth authenticator callbacks.
onResult: (code: number, result: {[key: string]: any}) =&gt; void onResult: (code: number, result: {[key: string]: any}) =&gt; void
Returns the result of an authentication request. Called to return the result of an authentication request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -2093,7 +2093,7 @@ Returns the result of an authentication request. ...@@ -2093,7 +2093,7 @@ Returns the result of an authentication request.
onRequestRedirected: (request: Want) =&gt; void onRequestRedirected: (request: Want) =&gt; void
Redirects a request. Called to redirect a request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -2126,7 +2126,7 @@ Redirects a request. ...@@ -2126,7 +2126,7 @@ Redirects a request.
onRequestContinued: () =&gt; void onRequestContinued: () =&gt; void
Continues to process the request. Called to continue to process the request.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -2183,7 +2183,7 @@ Authenticates an app account to obtain the OAuth access token. This API uses an ...@@ -2183,7 +2183,7 @@ Authenticates an app account to obtain the OAuth access token. This API uses an
verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void;
Verifies the app account credential. This API uses an asynchronous callback to return the result. Verifies the credential of an app account. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
...@@ -2191,7 +2191,7 @@ Verifies the app account credential. This API uses an asynchronous callback to r ...@@ -2191,7 +2191,7 @@ Verifies the app account credential. This API uses an asynchronous callback to r
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- | | ---------------- | --------------------- | ---- | --------------- |
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Optional for credential verification. | | options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for credential verification. |
| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.| | callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.|
### setProperties<sup>9+</sup> ### setProperties<sup>9+</sup>
......
# Audio Management # Audio Management
> **NOTE**<br/> The **Audio** module provides basic audio management capabilities, including audio volume and audio device management, and audio data collection and rendering.
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
This module provides the following common audio-related functions: This module provides the following common audio-related functions:
...@@ -9,6 +8,10 @@ This module provides the following common audio-related functions: ...@@ -9,6 +8,10 @@ This module provides the following common audio-related functions:
- [AudioRenderer](#audiorenderer8): audio rendering, used to play Pulse Code Modulation (PCM) audio data. - [AudioRenderer](#audiorenderer8): audio rendering, used to play Pulse Code Modulation (PCM) audio data.
- [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. - [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data.
> **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.
## Modules to Import ## Modules to Import
``` ```
...@@ -254,7 +257,7 @@ Enumerates the audio interruption modes. ...@@ -254,7 +257,7 @@ Enumerates the audio interruption modes.
| Name | Default Value| Description | | Name | Default Value| Description |
| ---------------------------- | ------ | ---------- | | ---------------------------- | ------ | ---------- |
| SHARE_MODE | 0 | Share mode.| | SHARE_MODE | 0 | Shared mode.|
| INDEPENDENT_MODE| 1 | Independent mode. | | INDEPENDENT_MODE| 1 | Independent mode. |
## DeviceFlag ## DeviceFlag
...@@ -578,7 +581,7 @@ Describes the device connection status and device information. ...@@ -578,7 +581,7 @@ Describes the device connection status and device information.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| :---------------- | :------------------------------------------------ | :--- | :----------------- | | :---------------- | :------------------------------------------------ | :--- | :----------------- |
| type | [DeviceChangeType](#devicechangetype) | Yes | Device connection status.| | type | [DeviceChangeType](#devicechangetype) | Yes | Device connection status.|
| deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. | | deviceDescriptors | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Device information. |
## DeviceChangeType ## DeviceChangeType
...@@ -649,6 +652,8 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l ...@@ -649,6 +652,8 @@ setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback&l
Sets the volume for a stream. This API uses an asynchronous callback to return the result. Sets the volume for a stream. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
**System capability**: SystemCapability.Multimedia.Audio.Volume **System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters** **Parameters**
...@@ -677,6 +682,8 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise&lt;void&gt; ...@@ -677,6 +682,8 @@ setVolume(volumeType: AudioVolumeType, volume: number): Promise&lt;void&gt;
Sets the volume for a stream. This API uses a promise to return the result. Sets the volume for a stream. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
**System capability**: SystemCapability.Multimedia.Audio.Volume **System capability**: SystemCapability.Multimedia.Audio.Volume
**Parameters** **Parameters**
...@@ -1041,6 +1048,8 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback&lt;void&gt;): void ...@@ -1041,6 +1048,8 @@ setRingerMode(mode: AudioRingMode, callback: AsyncCallback&lt;void&gt;): void
Sets the ringer mode. This API uses an asynchronous callback to return the result. Sets the ringer mode. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
**System capability**: SystemCapability.Multimedia.Audio.Communication **System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters** **Parameters**
...@@ -1068,6 +1077,8 @@ setRingerMode(mode: AudioRingMode): Promise&lt;void&gt; ...@@ -1068,6 +1077,8 @@ setRingerMode(mode: AudioRingMode): Promise&lt;void&gt;
Sets the ringer mode. This API uses a promise to return the result. Sets the ringer mode. This API uses a promise to return the result.
**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY
**System capability**: SystemCapability.Multimedia.Audio.Communication **System capability**: SystemCapability.Multimedia.Audio.Communication
**Parameters** **Parameters**
...@@ -1148,6 +1159,8 @@ Sets an audio parameter. This API uses an asynchronous callback to return the re ...@@ -1148,6 +1159,8 @@ Sets an audio parameter. This API uses an asynchronous callback to return the re
This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS
**System capability**: SystemCapability.Multimedia.Audio.Core **System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters** **Parameters**
...@@ -1178,6 +1191,8 @@ Sets an audio parameter. This API uses a promise to return the result. ...@@ -1178,6 +1191,8 @@ Sets an audio parameter. This API uses a promise to return the result.
This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only. This API is used to extend the audio configuration based on the hardware capability. The supported audio parameters vary according to the device and can be obtained from the device manual. The example below is for reference only.
**Required permissions**: ohos.permission.MODIFY_AUDIO_SETTINGS
**System capability**: SystemCapability.Multimedia.Audio.Core **System capability**: SystemCapability.Multimedia.Audio.Core
**Parameters** **Parameters**
...@@ -1434,6 +1449,8 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback&lt;void&gt;): void ...@@ -1434,6 +1449,8 @@ setMicrophoneMute(mute: boolean, callback: AsyncCallback&lt;void&gt;): void
Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MICROPHONE
**System capability**: SystemCapability.Multimedia.Audio.Device **System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters** **Parameters**
...@@ -1461,6 +1478,8 @@ setMicrophoneMute(mute: boolean): Promise&lt;void&gt; ...@@ -1461,6 +1478,8 @@ setMicrophoneMute(mute: boolean): Promise&lt;void&gt;
Mutes or unmutes the microphone. This API uses a promise to return the result. Mutes or unmutes the microphone. This API uses a promise to return the result.
**Required permissions:** ohos.permission.MICROPHONE
**System capability**: SystemCapability.Multimedia.Audio.Device **System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters** **Parameters**
...@@ -1489,6 +1508,8 @@ isMicrophoneMute(callback: AsyncCallback&lt;boolean&gt;): void ...@@ -1489,6 +1508,8 @@ isMicrophoneMute(callback: AsyncCallback&lt;boolean&gt;): void
Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. Checks whether the microphone is muted. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.MICROPHONE
**System capability**: SystemCapability.Multimedia.Audio.Device **System capability**: SystemCapability.Multimedia.Audio.Device
**Parameters** **Parameters**
...@@ -1515,6 +1536,8 @@ isMicrophoneMute(): Promise&lt;boolean&gt; ...@@ -1515,6 +1536,8 @@ isMicrophoneMute(): Promise&lt;boolean&gt;
Checks whether the microphone is muted. This API uses a promise to return the result. Checks whether the microphone is muted. This API uses a promise to return the result.
**Required permissions**: ohos.permission.MICROPHONE
**System capability**: SystemCapability.Multimedia.Audio.Device **System capability**: SystemCapability.Multimedia.Audio.Device
**Return value** **Return value**
...@@ -1546,7 +1569,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1546,7 +1569,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of event to subscribe to. The value **volumeChange** means the system volume change event, which is triggered when a system volume change is detected.| | type | string | Yes | Event type. The value **volumeChange** means the system volume change event, which is triggered when a system volume change is detected.|
| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | | callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. |
**Example** **Example**
...@@ -1573,7 +1596,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -1573,7 +1596,7 @@ This is a system API and cannot be called by third-party applications.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of event to subscribe to. The value **ringerModeChange** means the ringer mode change event, which is triggered when a ringer mode change is detected.| | type | string | Yes | Event type. The value **ringerModeChange** means the ringer mode change event, which is triggered when a ringer mode change is detected.|
| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the updated ringer mode. | | callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the updated ringer mode. |
**Example** **Example**
...@@ -1596,7 +1619,7 @@ Subscribes to device change events. When a device is connected or disconnected, ...@@ -1596,7 +1619,7 @@ Subscribes to device change events. When a device is connected or disconnected,
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | | :------- | :--------------------------------------------------- | :--- | :----------------------------------------- |
| type | string | Yes | Type of event to subscribe to. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| | type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.|
| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)\> | Yes | Callback used to return the device update details. | | callback | Callback<[DeviceChangeAction](#DeviceChangeAction)\> | Yes | Callback used to return the device update details. |
**Example** **Example**
...@@ -1622,7 +1645,7 @@ Unsubscribes from device change events. ...@@ -1622,7 +1645,7 @@ Unsubscribes from device change events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | | -------- | --------------------------------------------------- | ---- | ------------------------------------------ |
| type | string | Yes | Type of event to unsubscribe from. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| | type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.|
| callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | No | Callback used to return the device update details. | | callback | Callback<[DeviceChangeAction](#DeviceChangeAction)> | No | Callback used to return the device update details. |
**Example** **Example**
...@@ -1645,7 +1668,7 @@ Subscribes to audio interruption events. When the application's audio is interru ...@@ -1645,7 +1668,7 @@ Subscribes to audio interruption events. When the application's audio is interru
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of event to subscribe to. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| | type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.|
| interrupt | AudioInterrupt | Yes | Audio interruption event type. | | interrupt | AudioInterrupt | Yes | Audio interruption event type. |
| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | | callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. |
...@@ -1681,7 +1704,7 @@ Unsubscribes from audio interruption events. ...@@ -1681,7 +1704,7 @@ Unsubscribes from audio interruption events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of event to unsubscribe from. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| | type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.|
| interrupt | AudioInterrupt | Yes | Audio interruption event type. | | interrupt | AudioInterrupt | Yes | Audio interruption event type. |
| callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | | callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. |
...@@ -2557,7 +2580,7 @@ Subscribes to audio interruption events. This API uses a callback to get interru ...@@ -2557,7 +2580,7 @@ Subscribes to audio interruption events. This API uses a callback to get interru
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| type | string | Yes | Type of event to subscribe to. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted.| | type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted.|
| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | | callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. |
**Example** **Example**
...@@ -2623,7 +2646,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th ...@@ -2623,7 +2646,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| :------- | :----------------------- | :--- | :---------------------------------------- | | :------- | :----------------------- | :--- | :---------------------------------------- |
| type | string | Yes | Type of event to subscribe to. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| | type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.|
| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | | frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. |
...@@ -2650,7 +2673,7 @@ Unsubscribes from mark reached events. ...@@ -2650,7 +2673,7 @@ Unsubscribes from mark reached events.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| :----- | :----- | :--- | :------------------------------------------------ | | :----- | :----- | :--- | :------------------------------------------------ |
| type | string | Yes | Type of event to unsubscribe from. The value is fixed at **markReach**.| | type | string | Yes | Event type. The value is fixed at **markReach**.|
**Example** **Example**
...@@ -2670,7 +2693,7 @@ Subscribes to period reached events. When the period of frame rendering reaches ...@@ -2670,7 +2693,7 @@ Subscribes to period reached events. When the period of frame rendering reaches
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| :------- | :----------------------- | :--- | :------------------------------------------ | | :------- | :----------------------- | :--- | :------------------------------------------ |
| type | string | Yes | Type of event to subscribe to. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| | type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.|
| frame | number | Yes | Period during which frame rendering is listened. The value must be greater than **0**. | | frame | number | Yes | Period during which frame rendering is listened. The value must be greater than **0**. |
| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. |
...@@ -2696,7 +2719,7 @@ Unsubscribes from period reached events. ...@@ -2696,7 +2719,7 @@ Unsubscribes from period reached events.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| :----- | :----- | :--- | :-------------------------------------------------- | | :----- | :----- | :--- | :-------------------------------------------------- |
| type | string | Yes | Type of event to unsubscribe from. The value is fixed at **periodReach**.| | type | string | Yes | Event type. The value is fixed at **periodReach**.|
**Example** **Example**
...@@ -2716,7 +2739,7 @@ Subscribes to state change events. ...@@ -2716,7 +2739,7 @@ Subscribes to state change events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| :------- | :------------------------- | :--- | :------------------------------------------ | | :------- | :------------------------- | :--- | :------------------------------------------ |
| type | string | Yes | Type of event to subscribe to. The value **stateChange** means the state change event.| | type | string | Yes | Event type. The value **stateChange** means the state change event.|
| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | | callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. |
**Example** **Example**
...@@ -3216,7 +3239,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th ...@@ -3216,7 +3239,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| :------- | :---------------------- | :--- | :----------------------------------------- | | :------- | :---------------------- | :--- | :----------------------------------------- |
| type | string | Yes | Type of event to subscribe to. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | | type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. |
| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | | frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. |
| callback | position: number) => {} | Yes | Callback invoked when the event is triggered.| | callback | position: number) => {} | Yes | Callback invoked when the event is triggered.|
...@@ -3242,7 +3265,7 @@ Unsubscribes from mark reached events. ...@@ -3242,7 +3265,7 @@ Unsubscribes from mark reached events.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| :----- | :----- | :--- | :-------------------------------------------- | | :----- | :----- | :--- | :-------------------------------------------- |
| type | string | Yes | Type of event to unsubscribe from. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| | type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.|
**Example** **Example**
...@@ -3262,7 +3285,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th ...@@ -3262,7 +3285,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| :------- | :----------------------- | :--- | :------------------------------------------ | | :------- | :----------------------- | :--- | :------------------------------------------ |
| type | string | Yes | Type of event to subscribe to. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| | type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.|
| frame | number | Yes | Period during which frame capturing is listened. The value must be greater than **0**. | | frame | number | Yes | Period during which frame capturing is listened. The value must be greater than **0**. |
| callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. | | callback | (position: number) => {} | Yes | Callback invoked when the event is triggered. |
...@@ -3288,7 +3311,7 @@ Unsubscribes from period reached events. ...@@ -3288,7 +3311,7 @@ Unsubscribes from period reached events.
| Name| Type | Mandatory| Description | | Name| Type | Mandatory| Description |
| :----- | :----- | :--- | :---------------------------------------------- | | :----- | :----- | :--- | :---------------------------------------------- |
| type | string | Yes | Type of event to unsubscribe from. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| | type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.|
**Example** **Example**
...@@ -3308,7 +3331,7 @@ Subscribes to state change events. ...@@ -3308,7 +3331,7 @@ Subscribes to state change events.
| Name | Type | Mandatory| Description | | Name | Type | Mandatory| Description |
| :------- | :------------------------- | :--- | :------------------------------------------ | | :------- | :------------------------- | :--- | :------------------------------------------ |
| type | string | Yes | Type of event to subscribe to. The value **stateChange** means the state change event.| | type | string | Yes | Event type. The value **stateChange** means the state change event.|
| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | | callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. |
**Example** **Example**
......
...@@ -3,7 +3,7 @@ ...@@ -3,7 +3,7 @@
> **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.
Provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. The Bluetooth module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising.
## Modules to Import ## Modules to Import
...@@ -201,7 +201,7 @@ Obtains the connection state of a profile. ...@@ -201,7 +201,7 @@ Obtains the connection state of a profile.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | --------- | ---- | ------------------------------------- | | --------- | --------- | ---- | ------------------------------------- |
| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| | ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.|
**Return value** **Return value**
...@@ -222,12 +222,12 @@ cancelPairedDevice(deviceId: string): boolean ...@@ -222,12 +222,12 @@ cancelPairedDevice(deviceId: string): boolean
Cancels a paired remote device. Cancels a paired remote device.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -388,7 +388,7 @@ startBluetoothDiscovery(): boolean ...@@ -388,7 +388,7 @@ startBluetoothDiscovery(): boolean
Starts Bluetooth scan to discover remote devices. Starts Bluetooth scan to discover remote devices.
**Required permissions**: ohos.permission.USE_BLUETOOTH and ohos.permission.LOCATION **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
...@@ -1039,9 +1039,9 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); ...@@ -1039,9 +1039,9 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
## bluetooth.getProfile<sup>9+</sup><a name="getProfile"></a> ## bluetooth.getProfile<sup>9+</sup><a name="getProfile"></a>
getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile
Obtains a profile instance. **HidHostProfile** is added in API version 9. Obtains a profile instance. API version 9 is added with **HidHostProfile** and **PanProfile**.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
...@@ -1055,7 +1055,7 @@ Obtains a profile instance. **HidHostProfile** is added in API version 9. ...@@ -1055,7 +1055,7 @@ Obtains a profile instance. **HidHostProfile** is added in API version 9.
| Type | Description | | Type | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [A2dpSourceProfile](#A2dpSourceProfile), [HandsFreeAudioGatewayProfile](#HandsFreeAudioGatewayProfile), or [HidHostProfile](#HidHostProfile) | Profile object obtained. **A2dpSourceProfile**, **HandsFreeAudioGatewayProfile**, and **HidHostProfile** are supported.| | [A2dpSourceProfile](#A2dpSourceProfile), [HandsFreeAudioGatewayProfile](#HandsFreeAudioGatewayProfile), [HidHostProfile](#HidHostProfile), or [PanProfile](#PanProfile)| Profile instance obtained, which can be **A2dpSourceProfile**, **HandsFreeAudioGatewayProfile**, **HidHostProfile**, or **PanProfile**.|
**Example** **Example**
...@@ -1344,7 +1344,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. ...@@ -1344,7 +1344,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device to connect.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1374,7 +1374,7 @@ Disconnects an A2DP connection. ...@@ -1374,7 +1374,7 @@ Disconnects an A2DP connection.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device to disconnect.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1422,7 +1422,7 @@ a2dpSrc.on('connectionStateChange', onReceiveEvent); ...@@ -1422,7 +1422,7 @@ a2dpSrc.on('connectionStateChange', onReceiveEvent);
### off('connectionStateChange')<sup>8+</sup> ### off('connectionStateChange')<sup>8+</sup>
off(type: "connectionStateChange", callback: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void off(type: "connectionStateChange", callback?: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
Unsubscribes from the A2DP connection state change events. Unsubscribes from the A2DP connection state change events.
...@@ -1451,12 +1451,14 @@ a2dpSrc.off('connectionStateChange', onReceiveEvent); ...@@ -1451,12 +1451,14 @@ a2dpSrc.off('connectionStateChange', onReceiveEvent);
``` ```
### getPlayingState ### getPlayingState<sup>9+</sup>
getPlayingState(device: string): PlayingState getPlayingState(device: string): PlayingState
Obtains the playing state of a device. Obtains the playing state of a device.
**Required permissions**: ohos.permission.USE_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters** **Parameters**
...@@ -1576,7 +1578,7 @@ hfpAg.on('connectionStateChange', onReceiveEvent); ...@@ -1576,7 +1578,7 @@ hfpAg.on('connectionStateChange', onReceiveEvent);
### off('connectionStateChange')<sup>8+</sup> ### off('connectionStateChange')<sup>8+</sup>
off(type: "connectionStateChange", callback: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void off(type: "connectionStateChange", callback?: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
Unsubscribes from the HFP connection state change events. Unsubscribes from the HFP connection state change events.
...@@ -1616,12 +1618,12 @@ connect(device: string): boolean ...@@ -1616,12 +1618,12 @@ connect(device: string): boolean
Connects to the HidHost service of a device. Connects to the HidHost service of a device.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -1648,12 +1650,12 @@ disconnect(device: string): boolean ...@@ -1648,12 +1650,12 @@ disconnect(device: string): boolean
Disconnects from the HidHost service of a device. Disconnects from the HidHost service of a device.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
...@@ -1706,7 +1708,7 @@ hidHost.on('connectionStateChange', onReceiveEvent); ...@@ -1706,7 +1708,7 @@ hidHost.on('connectionStateChange', onReceiveEvent);
### off('connectionStateChange')<sup>9+</sup> ### off('connectionStateChange')<sup>9+</sup>
off(type: "connectionStateChange", callback: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void off(type: "connectionStateChange", callback?: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
Unsubscribes from the HidHost connection state change events. Unsubscribes from the HidHost connection state change events.
...@@ -1735,6 +1737,162 @@ hidHost.off('connectionStateChange', onReceiveEvent); ...@@ -1735,6 +1737,162 @@ hidHost.off('connectionStateChange', onReceiveEvent);
``` ```
## PanProfile
Before using a method of **PanProfile**, you need to create an instance of this class by using the **getProfile()** method.
### disconnect<sup>9+</sup><a name="disconnect"></a>
disconnect(device: string): boolean
Disconnects from the Personal Area Network (PAN) service of a device.
This is a system API.
**Required permissions**: ohos.permission.USE_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the target device.|
**Return value**
| Type | Description |
| --------------------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX');
```
### on('connectionStateChange')<sup>9+</sup>
on(type: "connectionStateChange", callback: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
Subscribes to the PAN connection state change events.
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.|
| callback | Callback&lt;[StateChangeParam](#StateChangeParam)&gt; | Yes | Callback used to return the PAN connection state change event. |
**Return value**
No value is returned.
**Example**
```js
function onReceiveEvent(data) {
console.info('pan state = '+ JSON.stringify(data));
}
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
panProfile.on('connectionStateChange', onReceiveEvent);
```
### off('connectionStateChange')<sup>9+</sup>
off(type: "connectionStateChange", callback?: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
Unsubscribes from the PAN connection state change events.
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- |
| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.|
| callback | Callback&lt;[StateChangeParam](#StateChangeParam)&gt; | No | Callback used to return the PAN connection state change event. |
**Return value**
No value is returned.
**Example**
```js
function onReceiveEvent(data) {
console.info('pan state = '+ JSON.stringify(data));
}
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
panProfile.on('connectionStateChange', onReceiveEvent);
panProfile.off('connectionStateChange', onReceiveEvent);
```
### setTethering<sup>9+</sup><a name="setTethering"></a>
setTethering(value: boolean): boolean
Sets tethering.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| value | boolean | Yes | Whether to set tethering over a Bluetooth PAN.|
**Return value**
| Type | Description |
| --------------------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
let ret = panProfile.setTethering(true);
```
### isTetheringOn<sup>9+</sup><a name="isTetheringOn"></a>
isTetheringOn(): boolean
Obtains the tethering status.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Return value**
| Type | Description |
| --------------------- | --------------------------------- |
| boolean | Returns **true** if tethering is available over a Bluetooth PAN; return **false** otherwise.|
**Example**
```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
let ret = panProfile.isTetheringOn();
```
## GattServer ## GattServer
Implements the Generic Attribute Profile (GATT) server. Before using a method of this class, you need to create a **GattServer** instance using the **createGattServer()** method. Implements the Generic Attribute Profile (GATT) server. Before using a method of this class, you need to create a **GattServer** instance using the **createGattServer()** method.
...@@ -1964,6 +2122,15 @@ Notifies the connected client device when a characteristic value changes. ...@@ -1964,6 +2122,15 @@ Notifies the connected client device when a characteristic value changes.
**Example** **Example**
```js ```js
// Create descriptors.
let descriptors = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8); let arrayBufferC = new ArrayBuffer(8);
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};
...@@ -2335,6 +2502,7 @@ let gattServer = bluetooth.BLE.createGattServer(); ...@@ -2335,6 +2502,7 @@ let gattServer = bluetooth.BLE.createGattServer();
gattServer.off("descriptorWrite"); gattServer.off("descriptorWrite");
``` ```
### on('connectStateChange') ### on('connectStateChange')
on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void
...@@ -2541,14 +2709,9 @@ Obtains all services of the remote BLE device. This API uses a promise to return ...@@ -2541,14 +2709,9 @@ Obtains all services of the remote BLE device. This API uses a promise to return
```js ```js
// Promise // Promise
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX'); gattClientDevice.getServices().then(result => {
device.connect(); console.info("Got services successfully:" + JSON.stringify(result));
var services = device.getServices(); });
console.log("bluetooth services size is ", services.length);
for (let i = 0; i < services.length; i++) {
console.log('bluetooth serviceUuid is ' + services[i].serviceUuid);
}
``` ```
...@@ -2556,7 +2719,7 @@ for (let i = 0; i < services.length; i++) { ...@@ -2556,7 +2719,7 @@ for (let i = 0; i < services.length; i++) {
readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback&lt;BLECharacteristic&gt;): void readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback&lt;BLECharacteristic&gt;): void
Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. Reads the characteristic value of the specific service of the peer BLE device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2610,7 +2773,7 @@ device.readCharacteristicValue(characteristic, readCcc); ...@@ -2610,7 +2773,7 @@ device.readCharacteristicValue(characteristic, readCcc);
readCharacteristicValue(characteristic: BLECharacteristic): Promise&lt;BLECharacteristic&gt; readCharacteristicValue(characteristic: BLECharacteristic): Promise&lt;BLECharacteristic&gt;
Reads the characteristic value of the specific service of the remote BLE device. This API uses a promise to return the result. Reads the characteristic value of the specific service of the peer BLE device. This API uses a promise to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2657,7 +2820,7 @@ device.readCharacteristicValue(characteristic); ...@@ -2657,7 +2820,7 @@ device.readCharacteristicValue(characteristic);
readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback&lt;BLEDescriptor&gt;): void readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback&lt;BLEDescriptor&gt;): void
Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. Reads the descriptor contained in the specific characteristic of the peer BLE device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2701,7 +2864,7 @@ device.readDescriptorValue(descriptor, readDesc); ...@@ -2701,7 +2864,7 @@ device.readDescriptorValue(descriptor, readDesc);
readDescriptorValue(descriptor: BLEDescriptor): Promise&lt;BLEDescriptor&gt; readDescriptorValue(descriptor: BLEDescriptor): Promise&lt;BLEDescriptor&gt;
Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses a promise to return the result. Reads the descriptor contained in the specific characteristic of the peer BLE device. This API uses a promise to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2881,6 +3044,15 @@ Sets the function of notifying the GATT client when the characteristic value of ...@@ -2881,6 +3044,15 @@ Sets the function of notifying the GATT client when the characteristic value of
**Example** **Example**
```js ```js
// Create descriptors.
let descriptors = [];
let arrayBuffer = new ArrayBuffer(8);
let descV = new Uint8Array(arrayBuffer);
descV[0] = 11;
let descriptor = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB',
descriptorUuid: '00001830-0000-1000-8000-00805F9B34FB', descriptorValue: arrayBuffer};
descriptors[0] = descriptor;
let arrayBufferC = new ArrayBuffer(8); let arrayBufferC = new ArrayBuffer(8);
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};
...@@ -3139,7 +3311,7 @@ Enumerates the scan modes. ...@@ -3139,7 +3311,7 @@ Enumerates the scan modes.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Default Value | Description |
| ---------------------------------------- | ---- | --------------- | | ---------------------------------------- | ---- | --------------- |
| SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_NONE | 0 | No scan mode. |
| SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. |
...@@ -3154,7 +3326,7 @@ Enumerates the pairing states. ...@@ -3154,7 +3326,7 @@ Enumerates the pairing states.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Default Value | Description |
| ------------------ | ---- | ------ | | ------------------ | ---- | ------ |
| BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_INVALID | 0 | Invalid pairing.|
| BOND_STATE_BONDING | 1 | Pairing. | | BOND_STATE_BONDING | 1 | Pairing. |
...@@ -3180,7 +3352,7 @@ Enumerates the SPP link types. ...@@ -3180,7 +3352,7 @@ Enumerates the SPP link types.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Default Value | Description |
| ---------- | ---- | ------------- | | ---------- | ---- | ------------- |
| SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.|
......
...@@ -42,7 +42,7 @@ Provides the ability information. ...@@ -42,7 +42,7 @@ Provides the ability information.
| labelId | number | Yes | No | Ability label ID. | | labelId | number | Yes | No | Ability label ID. |
| subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. | | subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability. |
| metaData<sup>8+</sup> | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Custom metadata of the ability. | | metaData<sup>8+</sup> | Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)> | Yes | No | Custom metadata of the ability. |
| metaData<sup>9+</sup> | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. | | metadata<sup>9+</sup> | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. |
| enabled<sup>8+</sup> | boolean | Yes | No | Whether the ability is enabled. | | enabled<sup>8+</sup> | boolean | Yes | No | Whether the ability is enabled. |
| supportWindowMode<sup>9+</sup> | Array\<[SupportWindowMode](js-apis-Bundle.md)> | Yes | No | Window modes supported by the ability. | | supportWindowMode<sup>9+</sup> | Array\<[SupportWindowMode](js-apis-Bundle.md)> | Yes | No | Window modes supported by the ability. |
| maxWindowRatio<sup>9+</sup> | number | Yes | No | Maximum window ratio supported by the ability. | | maxWindowRatio<sup>9+</sup> | number | Yes | No | Maximum window ratio supported by the ability. |
......
# ApplicationInfo # ApplicationInfo
> **NOTE**
>
> **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.
Provides the application information. Provides the application information.
## ApplicationInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description | | Name | Type | Readable| Writable| Description |
| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------ | | -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Application name. | | name | string | Yes | No | Application name. |
| description | string | Yes | No | Application description. | | description | string | Yes | No | Application description. |
| descriptionId | number | Yes | No | Application description ID. | | descriptionId | number | Yes | No | Application description ID. |
| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | | systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. |
| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | | enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. |
| label | string | Yes | No | Application label. | | label | string | Yes | No | Application label. |
| labelId | string | Yes | No | Application label ID. | | labelId | string | Yes | No | Application label ID. |
| icon | string | Yes | No | Application icon. | | icon | string | Yes | No | Application icon. |
| iconId | string | Yes | No | Application icon ID. | | iconId | string | Yes | No | Application icon ID. |
| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used.| | process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. |
| supportedModes | number | Yes | No | Running modes supported by the application. | | supportedModes | number | Yes | No | Running modes supported by the application. |
| moduleSourceDirs | Array\<string> | Yes | No | Relative paths for storing application resources. | | moduleSourceDirs | Array\<string> | Yes | No | Relative paths for storing application resources. |
| permissions | Array\<string> | Yes | No | Permissions required for accessing the application. | | permissions | Array\<string> | Yes | No | Permissions required for accessing the application. |
| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | | moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. |
| entryDir | string | Yes | No | Path for storing application files. | | entryDir | string | Yes | No | Path for storing application files. |
| codePath<sup>8+</sup> | string | Yes | No | Installation directory of the application. | | codePath<sup>8+</sup> | string | Yes | No | Installation directory of the application. |
| metaData<sup>8+</sup> | Map\<string, Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)>> | Yes | No | Custom metadata of the application. | | metaData<sup>8+</sup> | Map\<string, Array\<[CustomizeData](js-apis-bundle-CustomizeData.md)>> | Yes | No | Custom metadata of the application. |
| metaData<sup>9+</sup> | Map\<string, Array\<[Metadata](js-apis-bundle-Metadata.md)>> | Yes | No | Metadata of the application. | | metadata<sup>9+</sup> | Map\<string, Array\<[Metadata](js-apis-bundle-Metadata.md)>> | Yes | No | Metadata of the application. |
| removable<sup>8+</sup> | boolean | Yes | No | Whether the application is removable. | | removable<sup>8+</sup> | boolean | Yes | No | Whether the application is removable. |
| accessTokenId<sup>8+</sup> | number | Yes | No | Access token ID of the application. | | accessTokenId<sup>8+</sup> | number | Yes | No | Access token ID of the application. |
| uid<sup>8+</sup> | number | Yes | No | UID of the application. | | uid<sup>8+</sup> | number | Yes | No | UID of the application. |
| entityType<sup>8+</sup> | string | Yes | No | Entity type of the application. | | entityType<sup>8+</sup> | string | Yes | No | Entity type of the application. |
| fingerprint<sup>9+</sup> | string | Yes | No | Signing certificate fingerprint of the application, that is, the SHA-256 checksum of the signing certificate that you apply for for the application. | | fingerprint<sup>9+</sup> | string | Yes | No | Signing certificate fingerprint of the application, that is, the SHA-256 checksum of the signing certificate that you request for the application.|
| appDistributionType<sup>9+</sup> | string | Yes | No | Distribution type of the application signing certificate. The options are **app_gallery**, **enterprise**, **os_integration**, and **crowdtesting**. |
| appProvisionType<sup>9+</sup> | string | Yes | No | Type of the application signing certificate file. The options are **debug** and **release**.|
...@@ -2,14 +2,15 @@ ...@@ -2,14 +2,15 @@
> **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.
Provides the application bundle information. Provides the application bundle information.
## BundleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
......
...@@ -2,14 +2,15 @@ ...@@ -2,14 +2,15 @@
> **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.
Provides custom metadata. Provides custom metadata.
## CustomizeData
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
......
# ElementName
> **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.
Provides the element name information.
## ElementName
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| ----------------------- | ---------| ---- | ---- | ------------------------- |
| deviceId | string | Yes | Yes | Device ID. |
| bundleName | string | Yes | Yes | Bundle name of the application. |
| abilityName | string | Yes | Yes | Name of the ability. |
| uri | string | Yes | Yes | URI. |
| shortName | string | Yes | Yes | Short name of the ability. |
| moduleName<sup>9+</sup> | string | Yes | Yes | Name of the HAP file to which the ability belongs. |
...@@ -2,14 +2,15 @@ ...@@ -2,14 +2,15 @@
> **NOTE**<br> > **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.
Provides the Extension ability information. Provides the Extension ability information.
## ExtensionAbilityInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
...@@ -25,7 +26,7 @@ Provides the Extension ability information. ...@@ -25,7 +26,7 @@ Provides the Extension ability information.
| extensionAbilityType | bundle.ExtensionAbilityType | Yes | No | Type of the Extension ability. | | extensionAbilityType | bundle.ExtensionAbilityType | Yes | No | Type of the Extension ability. |
| permissions | Array\<string> | Yes | No | Permissions required for other applications to call the Extension ability.| | permissions | Array\<string> | Yes | No | Permissions required for other applications to call the Extension ability.|
| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the Extension ability. | | applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information of the Extension ability. |
| metaData | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. | | metadata | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the Extension ability. |
| enabled | boolean | Yes | No | Whether the Extension ability is enabled. | | enabled | boolean | Yes | No | Whether the Extension ability is enabled. |
| readPermission | string | Yes | No | Permission required for reading the Extension ability data. | | readPermission | string | Yes | No | Permission required for reading the Extension ability data. |
| writePermission | string | Yes | No | Permission required for writing data to the Extension ability. | | writePermission | string | Yes | No | Permission required for writing data to the Extension ability. |
...@@ -2,14 +2,15 @@ ...@@ -2,14 +2,15 @@
> **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.
Provides the HAP module information. Provides the HAP module information.
## HapModuleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
...@@ -35,4 +36,4 @@ Provides the HAP module information. ...@@ -35,4 +36,4 @@ Provides the HAP module information.
| mainElementName<sup>9+</sup> | string | Yes | No | Information about the main ability. | | mainElementName<sup>9+</sup> | string | Yes | No | Information about the main ability. |
| extensionAbilityInfo<sup>9+</sup> | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.| | extensionAbilityInfo<sup>9+</sup> | Array\<[ExtensionAbilityInfo](js-apis-bundle-ExtensionAbilityInfo.md)> | Yes | No | Information about the Extension ability.|
| metadata<sup>9+</sup> | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. | | metadata<sup>9+</sup> | Array\<[Metadata](js-apis-bundle-Metadata.md)> | Yes | No | Metadata of the ability. |
| hashValue<sup>9+</sup> | string | Yes | No | The hash value of the module. | | hashValue<sup>9+</sup> | string | Yes | No | Hash value of the module. |
\ No newline at end of file
...@@ -2,14 +2,15 @@ ...@@ -2,14 +2,15 @@
> **NOTE**<br> > **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 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
Provides the metadata information. Provides the metadata information.
## Metadata
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
......
...@@ -2,14 +2,15 @@ ...@@ -2,14 +2,15 @@
> **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.
Provides the module information of the application. Provides the module information of the application.
## ModuleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework **System capability**: SystemCapability.BundleManager.BundleFramework
......
# Standard NFC Card Emulation # Standard NFC Card Emulation
Implements Near-Field Communication (NFC) card emulation. The cardEmulation module implements Near-Field Communication (NFC) card emulation.
> **NOTE**<br> > **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. > 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
``` ```
import cardEmulation from '@ohos.nfc.cardEmulation'; import cardEmulation from '@ohos.nfc.cardEmulation';
......
...@@ -29,7 +29,7 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul ...@@ -29,7 +29,7 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.| | version | number | Yes| RDB store version.|
| callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.| | callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.|
...@@ -59,7 +59,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set ...@@ -59,7 +59,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | Context | Yes|Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.| | version | number | Yes| RDB store version.|
...@@ -92,7 +92,7 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul ...@@ -92,7 +92,7 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
...@@ -118,7 +118,7 @@ Deletes an RDB store. This API uses a promise to return the result. ...@@ -118,7 +118,7 @@ Deletes an RDB store. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
**Return value** **Return value**
...@@ -1018,7 +1018,7 @@ const valueBucket = { ...@@ -1018,7 +1018,7 @@ const valueBucket = {
} }
let promise = rdbStore.insert("EMPLOYEE", valueBucket) let promise = rdbStore.insert("EMPLOYEE", valueBucket)
promise.then(async (ret) => { promise.then(async (ret) => {
console.log("Insert first done: " + ret) console.log("Inserted first row: " + ret)
}).catch((err) => { }).catch((err) => {
console.log("Failed to insert data, err: " + err) console.log("Failed to insert data, err: " + err)
}) })
...@@ -1029,16 +1029,16 @@ promise.then(async (ret) => { ...@@ -1029,16 +1029,16 @@ promise.then(async (ret) => {
update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void
Updates data in the database based on the specified RdbPredicates object. This API uses an asynchronous callback to return the result. Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1064,14 +1064,14 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { ...@@ -1064,14 +1064,14 @@ rdbStore.update(valueBucket, predicates, function (err, ret) {
update(values: ValuesBucket, predicates: RdbPredicates):Promise&lt;number&gt; update(values: ValuesBucket, predicates: RdbPredicates):Promise&lt;number&gt;
Updates data in the database based on the specified RdbPredicates object. This API uses a promise to return the result. Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.|
**Return value** **Return value**
...@@ -1100,7 +1100,7 @@ promise.then(async (ret) => { ...@@ -1100,7 +1100,7 @@ promise.then(async (ret) => {
### update<sup>9+</sup> ### update<sup>9+</sup>
update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void
Updates data in the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1108,9 +1108,9 @@ Updates data in the database based on the specified **DataSharePredicates** obje ...@@ -1108,9 +1108,9 @@ Updates data in the database based on the specified **DataSharePredicates** obje
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| | predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1135,7 +1135,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { ...@@ -1135,7 +1135,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) {
update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise&lt;number&gt; update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise&lt;number&gt;
Updates data in the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1143,7 +1143,7 @@ Updates data in the database based on the specified **DataSharePredicates** obje ...@@ -1143,7 +1143,7 @@ Updates data in the database based on the specified **DataSharePredicates** obje
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| | predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.|
**Return value** **Return value**
...@@ -1175,7 +1175,7 @@ promise.then(async (ret) => { ...@@ -1175,7 +1175,7 @@ promise.then(async (ret) => {
delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void
Deletes data from the database based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1203,7 +1203,7 @@ rdbStore.delete(predicates, function (err, rows) { ...@@ -1203,7 +1203,7 @@ rdbStore.delete(predicates, function (err, rows) {
delete(predicates: RdbPredicates):Promise&lt;number&gt; delete(predicates: RdbPredicates):Promise&lt;number&gt;
Deletes data from the database based on the specified **RdbPredicates** object. This API uses a promise to return the result. Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1215,7 +1215,7 @@ Deletes data from the database based on the specified **RdbPredicates** object. ...@@ -1215,7 +1215,7 @@ Deletes data from the database based on the specified **RdbPredicates** object.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1234,7 +1234,7 @@ promise.then((rows) => { ...@@ -1234,7 +1234,7 @@ promise.then((rows) => {
delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void
Deletes data from the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1262,7 +1262,7 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { ...@@ -1262,7 +1262,7 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) {
delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt; delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt;
Deletes data from the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1275,7 +1275,7 @@ Deletes data from the database based on the specified **DataSharePredicates** ob ...@@ -1275,7 +1275,7 @@ Deletes data from the database based on the specified **DataSharePredicates** ob
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1294,7 +1294,7 @@ promise.then((rows) => { ...@@ -1294,7 +1294,7 @@ promise.then((rows) => {
query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1324,7 +1324,7 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e ...@@ -1324,7 +1324,7 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e
query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
Queries data in the database based on specified conditions. This API uses a promise to return the result. Queries data in the RDB store based on specified conditions. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1356,7 +1356,7 @@ Queries data in the database based on specified conditions. This API uses a prom ...@@ -1356,7 +1356,7 @@ Queries data in the database based on specified conditions. This API uses a prom
query(predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1386,7 +1386,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], ...@@ -1386,7 +1386,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"],
query(predicates: DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(predicates: DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
Queries data in the database based on specified conditions. This API uses a promise to return the result. Queries data in the RDB store based on specified conditions. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1625,14 +1625,14 @@ try { ...@@ -1625,14 +1625,14 @@ try {
backup(destName:string, callback: AsyncCallback&lt;void&gt;):void backup(destName:string, callback: AsyncCallback&lt;void&gt;):void
Backs up the database with the specified name. This API uses an asynchronous callback to return the result. Backs up an RDB store. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| destName | string | Yes| Name of the database backup file.| | destName | string | Yes| Name of the RDB store backup file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
...@@ -1650,14 +1650,14 @@ rdbStore.backup("dbBackup.db", function(err) { ...@@ -1650,14 +1650,14 @@ rdbStore.backup("dbBackup.db", function(err) {
backup(destName:string): Promise&lt;void&gt; backup(destName:string): Promise&lt;void&gt;
Backs up the database with the specified name. This API uses a promise to return the result. Backs up an RDB store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| destName | string | Yes| Name of the database backup file.| | destName | string | Yes| Name of the RDB store backup file.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -1678,14 +1678,14 @@ promiseBackup.then(()=>{ ...@@ -1678,14 +1678,14 @@ promiseBackup.then(()=>{
restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void
Restores a database from a specified database backup file. This API uses an asynchronous callback to return the result. Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| srcName | string | Yes| Name of the database backup file.| | srcName | string | Yes| Name of the RDB store backup file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
...@@ -1703,14 +1703,14 @@ rdbStore.restore("dbBackup.db", function(err) { ...@@ -1703,14 +1703,14 @@ rdbStore.restore("dbBackup.db", function(err) {
restore(srcName:string): Promise&lt;void&gt; restore(srcName:string): Promise&lt;void&gt;
Restores a database from a specified database backup file. This API uses a promise to return the result. Restores an RDB store using a backup file. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| srcName | string | Yes| Name of the database backup file.| | srcName | string | Yes| Name of the RDB store backup file.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -1809,7 +1809,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, ...@@ -1809,7 +1809,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err,
console.info('Failed to obtain DistributedTableName, err: ' + err) console.info('Failed to obtain DistributedTableName, err: ' + err)
return return
} }
console.info('Obtained DistributedTableName successfully, tableName=.' + tableName) console.info('Obtained distributed table name successfully, tableName=.' + tableName)
}) })
``` ```
...@@ -1839,7 +1839,7 @@ Obtains the distributed table name for a remote device based on the local table ...@@ -1839,7 +1839,7 @@ Obtains the distributed table name for a remote device based on the local table
```js ```js
let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE")
promise.then((tableName) => { promise.then((tableName) => {
console.info('Obtained DistributedTableName successfully, tableName= ' + tableName) console.info('Obtained distributed table name successfully, tableName= ' + tableName)
}).catch((err) => { }).catch((err) => {
console.info('Failed to obtain DistributedTableName, err: ' + err) console.info('Failed to obtain DistributedTableName, err: ' + err)
}) })
......
# Result Set # Result Set
A result set is a set of results returned after the relational database (RDB) query APIs are called. You can use the **resultset** APIs to obtain required data.
> **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.
## Usage ## Usage
You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain the **resultSet** object. You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain a **resultSet** object.
```js ```js
import dataRdb from '@ohos.data.rdb'; import dataRdb from '@ohos.data.rdb';
...@@ -20,7 +23,7 @@ promise.then((resultSet) => { ...@@ -20,7 +23,7 @@ promise.then((resultSet) => {
## ResultSet ## ResultSet
Provides methods to access the result set, which is obtained by querying the relational database (RDB) store. Provides methods to access the result set, which is obtained by querying the RDB store.
### Attributes ### Attributes
......
...@@ -213,7 +213,7 @@ Called when the configuration of the environment where the ability is running is ...@@ -213,7 +213,7 @@ Called when the configuration of the environment where the ability is running is
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| config | [Configuration](#section188911144124715) | Yes| New configuration.| | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.|
**Example** **Example**
......
# Key Event # Key Event
Represents key events reported by an input device. The Key Event module provides key events reported by an input device.
> **NOTE**<br> > **NOTE**<br>
> 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.
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册