提交 8787bf87 编写于 作者: J junyi233 提交者: Gitee

修改扫描缺陷

......@@ -198,6 +198,9 @@ 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-screenshot.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.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-webgl2.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
......@@ -316,6 +319,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-hisysevent.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-with-ets.md @ge-yafang
zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang
......
......@@ -38,13 +38,13 @@
<!--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="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 name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<!--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="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 name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
......
......@@ -26,7 +26,7 @@
- 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)了解版本详情。
......
......@@ -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).
## 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**
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)
## 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
## 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.
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
**Table 1** Data ability lifecycle APIs
......@@ -129,7 +154,7 @@ The basic dependency packages include:
import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb'
var urivar = "dataability:///com.ix.DataAbility"
var DAHelper = featureAbility.acquireDataAbilityHelper(
urivar
......@@ -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.
![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 {
},
}
```
## 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:
```javascript
import prompt from '@system.prompt'
let mRemote;
function onConnectCallback(element, remote){
console.log('onConnectLocalService onConnectDone element: ' + element);
......@@ -161,13 +161,13 @@ You can use either of the following methods to connect to a Service ability:
}).catch((e) => {
console.log('sendRequest error:' + e);
});
}
function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect Callback')
}
function onFailedCallback(code){
console.log('ConnectAbility onFailed Callback')
}
......@@ -196,7 +196,7 @@ You can use either of the following methods to connect to a Service ability:
```javascript
import rpc from "@ohos.rpc";
let mMyStub;
export default {
onStart() {
......@@ -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 {
}
}
```
## 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 {
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
Now you've got a widget shown below.
![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
onRemoteRequest(code, data, reply, option) {
}
}
class ServiceExt extends ServiceExtensionAbility {
console.log('onCreate, want:' + want.abilityName);
}
......@@ -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(
}
);
```
## 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
tcp.off('close');
}, 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)
......@@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca
## Available APIs
For details about the APIs related to the distributed data object, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
### Creating a Distributed Data Object Instance
Call **createDistributedObject()** to create a distributed data object instance. You can specify the attributes of the instance in **source**.
......@@ -15,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance
| Package| API| Description|
| -------- | -------- | -------- |
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>-&nbsp;**source**: attributes of the **distributedObject** set.<br>-&nbsp;**DistributedObject**: returns the distributed object created.|
| ohos.data.distributedDataObject| createDistributedObject(source: object): DistributedObject | Creates a distributed data object instance for data operations.<br>- **source**: attributes of the **distributedObject** set.<br>- **DistributedObject**: returns the distributed object created.|
### Generating a Session ID
......@@ -33,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s
**Table 3** API for setting a session ID
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br>&nbsp;**sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
| DistributedDataObject | setSessionId(sessionId?: string): boolean | Sets a session ID for distributed data objects.<br> **sessionId**: session ID of a distributed object in a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
### Observing Data Changes
Call **on()** to subscribe to data changes of a distributed data object. When the data changes, a callback will be invoked to return the data changes. You can use **off()** to unsubscribe from the data changes.
**Table 4** APIs for observing data changes of a distributed data object
| Class| API| Description|
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject| on(type: 'change', callback: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Subscribes to data changes.|
| DistributedDataObject| off(type: 'change', callback?: Callback<{ sessionId: string, fields: Array&lt;string&gt; }>): void | Unsubscribes from data changes. **Callback**: specifies callback used to return changes of the distributed data object. If this parameter is not specified, all callbacks related to data changes will be unregistered.|
### Observing Online or Offline Status
......@@ -67,13 +69,13 @@ The saved data will be released in the following cases:
- The application has been uninstalled.
- Data is successfully restored.
**Table 6** APIs for saving a distributed data object and revoking the saving
**Table 6** APIs for saving a distributed data object and revoking the saving operation
| Class| API| Description|
| -------- | -------- | -------- |
| DistributedDataObject | save(deviceId: string): Promise&lt;SaveSuccessResponse&gt; | Saves a distributed data object. This API uses a promise to return the result.|
| DistributedDataObject| save(deviceId: string, callback: AsyncCallback&lt;SaveSuccessResponse&gt;): void | Saves a distributed data object. This API uses an asynchronous callback to return the result.|
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. |
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result. |
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result.|
| DistributedDataObject| revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result.|
## How to Develop
......@@ -157,7 +159,7 @@ The following example shows how to implement a distributed data object synchroni
local_object.on("change", this.changeCallback.bind(this));
```
6. Modify object attributes. <br>The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
6. Modify object attributes. <br>The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types).
The sample code is as follows:
```js
......@@ -205,41 +207,39 @@ The following example shows how to implement a distributed data object synchroni
10. Save a distributed data object and revoke the data saving operation.
- Callback
```js
// Save a distributed data object.
local_object.save("local", (result, data)=>{
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
```
- Promise
```js
// Save a distributed data object.
g_object.save("local").then((result)=>{
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result)=>{
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
```
11. Unsubscribe from the status changes of the distributed data object. <br>You can specify the callback to unregister. If you do not specify the callback, this API unregister all callbacks of this distributed data object.
```js
// Save a distributed data object.
local_object.save("local", (result, data)=>{
console.log("save callback");
console.info("save sessionId " + data.sessionId);
console.info("save version " + data.version);
console.info("save deviceId " + data.deviceId);
});
// Revoke the data saving operation.
local_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
console.info("revokeSave sessionId " + data.sessionId);
});
```
- Promise
```js
// Save a distributed data object.
g_object.save("local").then((result)=>{
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result)=>{
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
```
11. Unsubscribe from the status changes of the distributed data object. <br>You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object.
The sample code is as follows:
```js
......
......@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs
For details about the APIs related to distributed data, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS
| Category | API | Description |
| -------- | --- | ----------- |
| Creating a distributed database | createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store | getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**. |
| Managing data in a distributed KV store | put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array \| string \| number \| boolean): Promise&lt;void> | Inserts and updates data. |
| Category | API | Description |
| ------------ | ------------- | ------------- |
| Creating a distributed database| createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| Obtaining a distributed KV store| getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;T extends KVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains the KV store with the specified **Options** and **storeId**.|
| Managing data in a distributed KV store| put(key: string, value: Uint8Array \| string \| number \| boolean, callback: AsyncCallback&lt;void&gt;): void<br>put(key: string, value: Uint8Array \| string \| number \| boolean): Promise&lt;void> | Inserts and updates data.|
| Managing data in a distributed KV store| delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| Managing data in a distributed KV store | get(key: string, callback: AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;): void<br>get(key: string): Promise&lt;Uint8Array \| string \| boolean \| number> | Queries data. |
| Subscribing to changes in the distributed data | on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void | Subscribes to data changes in the KV store. |
| Synchronizing data across devices | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
| Managing data in a distributed KV store| get(key: string, callback: AsyncCallback&lt;Uint8Array \| string \| boolean \| number&gt;): void<br>get(key: string): Promise&lt;Uint8Array \| string \| boolean \| number> | Queries data. |
| Subscribing to changes in the distributed data| on(event: 'dataChange', type: SubscribeType, observer: Callback&lt;ChangeNotification&gt;): void<br>on(event: 'syncComplete', syncCallback: Callback&lt;Array&lt;[string, number]&gt;&gt;): void | Subscribes to data changes in the KV store.|
| Synchronizing data across devices| sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
......@@ -29,14 +31,13 @@ The table below describes the APIs provided by the OpenHarmony DDS module.
The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module.
```js
import distributedData from '@ohos.data.distributedData';
```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **KvManagerConfig** object based on the application context.
2. Create a **KvManager** instance.
(1) Create a **KvManagerConfig** object based on the application context.
(2) Create a **KvManager** instance.
The sample code is as follows:
```js
......@@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p
```
3. Create and obtain a single KV store.
1. Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
(1) Declare the ID of the single KV store to create.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required.
The sample code is as follows:
```js
......@@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p
}
```
> ![icon-note.gif](../public_sys-resources/icon-note.gif) **NOTE**<br/>
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> For data synchronization between networked devices, you are advised to open the distributed KV store during application startup to obtain the database handle. With this database handle (**kvStore** in this example), you can perform operations, such as inserting data into the KV store, without creating the KV store repeatedly during the lifecycle of the handle.
4. Subscribe to changes in the distributed data.<br/>
4. Subscribe to changes in the distributed data.<br/>
The following is the sample code for subscribing to the data changes of a single KV store:
```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(data));
......@@ -104,8 +104,8 @@ The following uses a single KV store as an example to describe the development p
```
5. Write data to the single KV store.
1. Construct the key and value to be written into the single KV store.
2. Write key-value pairs into the single KV store.
(1) Construct the key and value to be written into the single KV store.
(2) Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store:
......@@ -126,11 +126,10 @@ The following uses a single KV store as an example to describe the development p
```
6. Query data in the single KV store.
1. Construct the key to be queried from the single KV store.
2. Query data from the single KV store.
(1) Construct the key to be queried from the single KV store.
(2) Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store:
```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-test-string';
......@@ -178,3 +177,7 @@ The following uses a single KV store as an example to describe the development p
}
});
```
## Samples
The following samples are provided to help you better understand the distributed data development:
- [`KvStore`: Distributed Database (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/data/Kvstore)
- [Distributed Database](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData)
# 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
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
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
......@@ -26,7 +30,7 @@ Call the **put()** method to add or modify data in a **Preferences** instance.
| 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
......@@ -36,7 +40,7 @@ Call the **get()** method to read data from a **Preferences** instance.
| 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
......@@ -67,7 +71,7 @@ Use the following APIs to delete a **Preferences** instance or data file.
| 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.
## How to Develop
......@@ -91,8 +95,8 @@ Use the following APIs to delete a **Preferences** instance or data file.
```js
promise.then((preferences) => {
let getPromise = preferences.put('startup', 'auto')
getPromise.then(() => {
let putPromise = preferences.put('startup', 'auto')
putPromise.then(() => {
console.info("Put the value of startup successfully.")
}).catch((err) => {
console.info("Failed to put the value of startup with err: " + err)
......
......@@ -16,17 +16,18 @@ The following table describes APIs available for mutual conversion between coord
| API | Description |
| -------- | -------- |
| isGeoServiceAvailable(callback:&nbsp;AsyncCallback&lt;boolean&gt;)&nbsp;:&nbsp;void | Checks&nbsp;whether&nbsp;the&nbsp;(reverse)&nbsp;geocoding&nbsp;service&nbsp;is&nbsp;available.&nbsp;This&nbsp;function&nbsp;uses&nbsp;an&nbsp;asynchronous&nbsp;callback&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
| isGeoServiceAvailable()&nbsp;:&nbsp;Promise&lt;boolean&gt; | Checks&nbsp;whether&nbsp;the&nbsp;(reverse)&nbsp;geocoding&nbsp;service&nbsp;is&nbsp;available.&nbsp;This&nbsp;function&nbsp;uses&nbsp;a&nbsp;promise&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
| getAddressesFromLocation(request:&nbsp;ReverseGeoCodeRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;)&nbsp;:&nbsp;void | Converts&nbsp;coordinates&nbsp;into&nbsp;geographic&nbsp;description&nbsp;through&nbsp;reverse&nbsp;geocoding.&nbsp;This&nbsp;function&nbsp;uses&nbsp;an&nbsp;asynchronous&nbsp;callback&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
| getAddressesFromLocation(request:&nbsp;ReverseGeoCodeRequest)&nbsp;:&nbsp;Promise&lt;Array&lt;GeoAddress&gt;&gt;; | Converts&nbsp;coordinates&nbsp;into&nbsp;geographic&nbsp;description&nbsp;through&nbsp;reverse&nbsp;geocoding.&nbsp;This&nbsp;function&nbsp;uses&nbsp;a&nbsp;promise&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
| getAddressesFromLocationName(request:&nbsp;GeoCodeRequest,&nbsp;callback:&nbsp;AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;)&nbsp;:&nbsp;void | Converts&nbsp;geographic&nbsp;description&nbsp;into&nbsp;coordinates&nbsp;through&nbsp;geocoding.&nbsp;This&nbsp;function&nbsp;uses&nbsp;an&nbsp;asynchronous&nbsp;callback&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
| getAddressesFromLocationName(request:&nbsp;GeoCodeRequest)&nbsp;:&nbsp;Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts&nbsp;geographic&nbsp;description&nbsp;into&nbsp;coordinates&nbsp;through&nbsp;geocoding.&nbsp;This&nbsp;function&nbsp;uses&nbsp;a&nbsp;promise&nbsp;to&nbsp;return&nbsp;the&nbsp;result. |
| isGeoServiceAvailable(callback: AsyncCallback&lt;boolean&gt;) : void | Checks whether the (reverse) geocoding service is available. This function uses an asynchronous callback to return the result. |
| isGeoServiceAvailable() : Promise&lt;boolean&gt; | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void | Converts coordinates into geographic description through reverse geocoding. This function uses an asynchronous callback to return the result. |
| getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt;; | Converts coordinates into geographic description through reverse geocoding. This function uses a promise to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback&lt;Array&lt;GeoAddress&gt;&gt;) : void | Converts geographic description into coordinates through geocoding. This function uses an asynchronous callback to return the result. |
| getAddressesFromLocationName(request: GeoCodeRequest) : Promise&lt;Array&lt;GeoAddress&gt;&gt; | Converts geographic description into coordinates through geocoding. This function uses a promise to return the result. |
## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:**
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
>
> The **GeoConvert** instance needs to access backend services to obtain information. Therefore, before performing the following steps, ensure that your device is connected to the network.
1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
......@@ -45,7 +46,7 @@ The following table describes APIs available for mutual conversion between coord
});
```
Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see the _API Reference_.
Your application can obtain the **GeoAddress** list that matches the specified coordinates and then read location information from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
- Call **getAddressesFromLocationName** to convert geographic description into coordinates.
```
......@@ -55,6 +56,6 @@ The following table describes APIs available for mutual conversion between coord
});
```
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see the _API Reference_.
Your application can obtain the **GeoAddress** list that matches the specified location information and read coordinates from it. For details, see [Geolocation](../reference/apis/js-apis-geolocation.md).
To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
......@@ -34,40 +34,52 @@
1. To obtain data from a type of sensor, configure the requested permissions in the **config.json** file.
```
"reqPermissions":[
{
"name":"ohos.permission.ACCELEROMETER",
"reason"":"",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
{
"name":"ohos.permission.GYROSCOPE",
"reason"":"",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
{
"name":"ohos.permission.ACTIVITY_MOTION",
"reason"":"ACTIVITY_MOTION_TEST",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
{
"name":"ohos.permission.READ_HEALTH_DATA",
"reason"":"HEALTH_DATA_TEST",
"usedScene":{
"ability": ["sensor.index.MainAbility",".MainAbility"],
"when":"inuse"
}
},
]
"reqPermissions": [
{
"name": "ohos.permission.ACCELEROMETER",
"reason": "",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.GYROSCOPE",
"reason": "",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACTIVITY_MOTION",
"reason": "ACTIVITY_MOTION_TEST",
"usedScene": {
"ability": [
"sensor.index.MainAbility",
".MainAbility"
],
"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.
......@@ -75,7 +87,7 @@
```
import sensor from "@ohos.sensor"
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 @@
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
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:
| 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_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_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_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_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_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_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_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_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_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_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 |
| 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_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_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_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_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_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_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_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_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_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_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 |
## Working Principles
......@@ -54,12 +54,12 @@ The following modules work cooperatively to implement OpenHarmony sensors: Senso
Table 7 Sensor data permissions
| 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.|
| 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. |
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
| 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.|
| 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. |
| Heart rate sensor | ohos.permission.READ_HEALTH_DATA | user_grant | Allows an application to read health data. |
......
......@@ -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.
For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md).
## Available APIs
| 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:&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(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:&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 | stop(stopMode:&nbsp;VibratorStopMode):&nbsp;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 | 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: 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: EffectId): Promise&lt;void&gt; | Triggers vibration with the specified effect. This API uses a promise 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: VibratorStopMode): Promise&lt;void&gt; | Stops vibration. This API uses a promise 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
......@@ -24,36 +26,36 @@ You can set different vibration effects as needed, for example, customizing the
```
"reqPermissions": [
{
"name": "ohos.permission.ACCELEROMETER",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.VIBRATE",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACTIVITY_MOTION",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACCELEROMETER",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.VIBRATE",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
{
"name": "ohos.permission.ACTIVITY_MOTION",
"reason": "",
"usedScene": {
"ability": [
".MainAbility"
],
"when": "inuse"
}
},
]
```
......@@ -61,12 +63,12 @@ You can set different vibration effects as needed, for example, customizing the
```
import vibrator from "@ohos.vibrator"
vibrator.vibrate(1000).then((error)=>{
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);
}else{ // The call is successful, and the device starts to vibrate.
vibrator.vibrate(1000).then((error) => {
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);
} else { // The call is successful, and the device starts to vibrate.
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
```
import vibrator from "@ohos.vibrator"
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error)=>{
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);
}else{ // The call is successful, and the device stops vibrating.
vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then((error) => {
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);
} else { // The call is successful, and the device stops vibrating.
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)
......@@ -9,3 +9,5 @@
- Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.md)
- Error Management
- [Development of Error Manager](errormanager-guidelines.md)
# Development of Error Manager
## When to Use
If coding specification issues or errors exist in the code of an application, the application may encounter unexpected errors, for example, uncaught exceptions or application lifecycle timeouts, while it is running. In such a case, the application may exit unexpectedly. Error logs, however, are usually stored on users' local storage, making it inconvenient to locate faults. With the APIs provided by the **errorManager** module, your application will be able to report related errors and logs to your service platform for fault locating before it exits.
## Available APIs
Application error management APIs are provided by the **errorManager** module. For details about how to import the module to use related APIs, see [Development Example](#development-example).
**Table 1** Description of application error management APIs
| API | Description |
| ------------------------------------------------------------ | ---------------------------------------------------- |
| registerErrorObserver(observer: ErrorObserver): number | Registers an observer for application errors. A callback will be invoked when an application error is detected. This API works in a synchronous manner. The return value is the SN of the registered observer.|
| unregisterErrorObserver(observerId: number, callback: AsyncCallback\<void\>): void | Unregisters an observer in callback mode. The number passed to this API is the SN of the registered observer. |
| unregisterErrorObserver(observerId: number): Promise\<void\> | Unregisters an observer in promise mode. The number passed to this API is the SN of the registered observer. |
When an asynchronous callback is used, the return value can be processed directly in the callback. If a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Result Codes for Unregistering an Observer](#result-codes-for-unregistering-an-observer).
**Table 2** Description of the ErrorObserver API
| API | Description |
| ------------------------------ | ------------------------------------------------------------ |
| onUnhandledException(errMsg: string): void | Called when an application generates an uncaught exception after being registered.|
### Result Codes for Unregistering an Observer
| Result Code| Description |
| ------ | --------------------------- |
| 0 | Normal. |
| -1 | Input number not exist. |
| -2 | Invalid parameter. |
## Development Example
```ts
import Ability from '@ohos.application.Ability'
import errorManager from '@ohos.application.errorManager'
var registerId = -1;
var callback = {
onUnhandledException: function (errMsg) {
console.log(errMsg);
}
}
export default class MainAbility extends Ability {
onCreate(want, launchParam) {
console.log("[Demo] MainAbility onCreate")
globalThis.abilityWant = want;
}
onDestroy() {
console.log("[Demo] MainAbility onDestroy")
}
onWindowStageCreate(windowStage) {
// Main window is created for this ability.
console.log("[Demo] MainAbility onWindowStageCreate")
globalThis.registerObserver = (() => {
registerId = errorManager.registerErrorObserver(callback);
})
globalThis.unRegisterObserver = (() => {
errorManager.unregisterErrorObserver(registerId, (result) => {
console.log("[Demo] result " + result.code + ";" + result.message)
});
})
windowStage.setUIContent(this.context, "pages/index", null)
}
onWindowStageDestroy() {
// Main window is destroyed to release UI resources.
console.log("[Demo] MainAbility onWindowStageDestroy")
}
onForeground() {
// Ability is brought to the foreground.
console.log("[Demo] MainAbility onForeground")
}
onBackground() {
// Ability is brought back to the background.
console.log("[Demo] MainAbility onBackground")
}
};
```
......@@ -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.
## 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
......
# 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>
> 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
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.
```
var localeStr = localeObj.toString();
```
3. Maximize locale information.<br>
Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information.
```
var maximizedLocale = localeObj.maximize();
```
4. Minimize locale information.<br>
Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information.
```
var minimizedLocale = localeObj.minimize();
```
......@@ -104,7 +105,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
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.
```
Date date = new Date();
var formatResult = dateTimeFormat.format(date);
......@@ -112,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
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.
```
Date startDate = new Date();
Date endDate = new 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>
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();
```
......@@ -161,7 +162,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
2. Format a number.<br>
Call the **format** method to format a number. A string is returned as the formatting result.
```
var number = 1234.5678
var formatResult = numberFormat.format(number);
......@@ -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>
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();
```
......@@ -208,7 +209,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
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.
```
var str1 = "first string";
var str2 = "second string";
......@@ -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>
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();
```
......@@ -255,7 +256,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
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**.
```
var number = 1234.5678
var categoryResult = plurals.select(number);
......@@ -296,7 +297,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
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.
```
var number = 2;
var unit = "year"
......@@ -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>
Upon obtaining each part of the relative time format, customize the relative time formatting result.
```
var number = 2;
var unit = "year"
......@@ -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>
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();
```
## 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 @@
- [Audio Capture Development](audio-capturer.md)
- [OpenSL ES Audio Playback Development](opensles-playback.md)
- [OpenSL ES Audio Recording Development](opensles-capture.md)
- [Audio Interruption Mode Development](audio-interruptmode.md)
- Video
- [Video Playback Development](video-playback.md)
- [Video Recording Development](video-recorder.md)
- Image
- [Image Development](image.md)
- Camera
- [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) {
// Set the player callbacks.
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');
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');
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');
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');
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');
audioPlayer.release(); // Release the AudioPlayer resources.
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the timeUpdate event callback.
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail');
return;
}
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');
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') {
......@@ -78,13 +78,13 @@ function setCallBack(audioPlayer) {
} else {
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');
});
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, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`);
......@@ -107,7 +107,7 @@ async function audioPlayerDemo() {
}).catch((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'
export class AudioDemo {
// Set the player callbacks.
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');
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');
});
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');
audioPlayer.release(); // Release the AudioPlayer resources.
audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined;
});
}
......@@ -147,7 +147,7 @@ export class AudioDemo {
}).catch((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 {
// Set the player callbacks.
private isNextMusic = false;
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');
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');
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');
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented.
......@@ -193,7 +193,7 @@ export class AudioDemo {
}).catch((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() {
......@@ -210,7 +210,7 @@ export class AudioDemo {
}).catch((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'
export class AudioDemo {
// Set the player callbacks.
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');
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');
});
}
......@@ -247,17 +247,7 @@ export class AudioDemo {
}).catch((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 {
}
```
## 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
The full process includes creating an instance, reading image information, reading and writing pixel maps, updating data, packaging pixels, and releasing resources.
```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.
// 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 } }
image.createPixelMap(Color, opts, pixelmap => {
image.createPixelMap(color, opts, pixelmap => {
expect(pixelmap !== null).assertTrue();
console.info('TC_001-1 success');
done();
})
// Read pixels.
pixelmap.readPixels(area,(data) => {
pixelmap.readPixels(area,(data) => {
if(data !== null) {
var bufferArr = new Uint8Array(area.pixels);
var res = true;
......@@ -50,39 +50,39 @@ pixelmap.readPixelsToBuffer(readBuffer,() => {
var bufferArr = new Uint8Array(readBuffer);
var res = true;
for (var i = 0; i < bufferArr.length; i++) {
if(res) {
if (bufferArr[i] !== 0) {
res = false;
console.info('TC_020-1 Success');
expect(true).assertTrue();
done();
break;
}
}
if(res) {
if (bufferArr[i] !== 0) {
res = false;
console.info('TC_020-1 Success');
expect(true).assertTrue();
done();
break;
}
}
}
// Write pixels.
pixelmap.writePixels(area,() => {
const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }}
pixelmap.readPixels(readArea,() => {
var readArr = new Uint8Array(readArea.pixels);
var res = true;
for (var i = 0; i < readArr.length; i++) {
if(res) {
if (readArr[i] !== 0) {
res = false;
console.info('TC_022-1 Success');
expect(true).assertTrue();
done();
break;
}
}
pixelmap.readPixels(readArea,() => {
var readArr = new Uint8Array(readArea.pixels);
var res = true;
for (var i = 0; i < readArr.length; i++) {
if(res) {
if (readArr[i] !== 0) {
res = false;
console.info('TC_022-1 Success');
expect(true).assertTrue();
done();
break;
}
}
}
// Write pixels to the buffer.
pixelmap.writeBufferToPixels(writeColor).then(() => {
const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then (() => {
pixelmap.writeBufferToPixels(writeColor).then(() => {
const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then (() => {
var bufferArr = new Uint8Array(readBuffer);
var res = true;
for (var i = 0; i < bufferArr.length; i++) {
......@@ -95,18 +95,18 @@ pixelmap.writePixels(area,() => {
break;
}
}
}
}
// Obtain image information.
pixelmap.getImageInfo( imageInfo => {
if (imageInfo !== null) {
console.info('TC_024-1 imageInfo is ready');
expect(imageInfo.size.height == 4).assertTrue();
expect(imageInfo.size.width == 6).assertTrue();
expect(imageInfo.pixelFormat == 4).assertTrue();
done();
}
})
if (imageInfo !== null) {
console.info('TC_024-1 imageInfo is ready');
expect(imageInfo.size.height == 4).assertTrue();
expect(imageInfo.size.width == 6).assertTrue();
expect(imageInfo.pixelFormat == 4).assertTrue();
done();
}
})
// Release the PixelMap object.
pixelmap.release(()=>{
......@@ -116,7 +116,7 @@ pixelmap.release(()=>{
})
// 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).
const imageSourceApi = image.createImageSource(29);
......@@ -136,7 +136,7 @@ imagePackerApi.packing(imageSourceApi, packOpts, data => {
console.info('TC_062-1 finished');
expect(data !== null).assertTrue();
done();
})
})
// Release the ImagePacker object.
imagePackerApi.release();
......@@ -148,7 +148,7 @@ imagePackerApi.release();
/data/local/tmp/test.jpg // Set the path for creating an image source.
// 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.
let decodingOptions = {
......@@ -171,9 +171,9 @@ imageSourceApi.createPixelMap(decodingOptions, pixelmap => {
// Create a pixel map in promise mode.
imageSourceApi.createPixelMap().then(pixelmap => {
console.info('TC_050-11 createPixelMap ');
expect(pixelmap !== null ).assertTrue();
done();
console.info('TC_050-11 createPixelMap ');
expect(pixelmap !== null ).assertTrue();
done();
})
// Capture error information when an exception occurs during function invoking.
......@@ -181,7 +181,7 @@ catch(error => {
console.log('TC_050-11 error: ' + error);
expect().assertFail();
done();
})
})
// Obtain the number of bytes in each line of pixels.
pixelmap.getBytesNumberPerRow( num => {
......@@ -192,13 +192,13 @@ pixelmap.getBytesNumberPerRow( num => {
// Obtain the total number of pixel bytes.
pixelmap.getPixelBytesNumber(num => {
console.info('TC_026-1 num is ' + num);
expect(num == expectNum).assertTrue();
done();
})
console.info('TC_026-1 num is ' + num);
expect(num == expectNum).assertTrue();
done();
})
// Obtain the pixel map information.
pixelmap.getImageInfo( imageInfo => {})
pixelmap.getImageInfo( imageInfo => {})
// Print the failure information.
console.info('TC_024-1 imageInfo is empty');
......@@ -206,17 +206,17 @@ expect(false).assertTrue()
// Release the PixelMap object.
pixelmap.release(()=>{
expect(true).assertTrue();
console.log('TC_027-1 suc');
done();
})
expect(true).assertTrue();
console.log('TC_027-1 suc');
done();
})
// Capture release failure information.
catch(error => {
console.log('TC_027-1 error: ' + error);
expect().assertFail();
done();
})
console.log('TC_027-1 error: ' + error);
expect().assertFail();
done();
})
```
### Encoding Scenario
......@@ -225,14 +225,14 @@ catch(error => {
/data/local/tmp/test.png // Set the path for creating an 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.
if (imageSourceApi == null) {
console.info('TC_062 create image source failed');
expect(false).assertTrue();
done();
}
console.info('TC_062 create image source failed');
expect(false).assertTrue();
done();
}
// Create an image packer if the image source is successfully created.
const imagePackerApi = image.createImagePacker();
......@@ -242,31 +242,58 @@ if (imagePackerApi == null) {
console.info('TC_062 create image packer failed');
expect(false).assertTrue();
done();
}
}
// Set encoding parameters if the image packer is successfully created.
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.
imagePackerApi.packing(imageSourceApi, packOpts)
.then( data => {
console.info('TC_062 finished');
expect(data !== null).assertTrue();
done();
})
console.info('TC_062 finished');
expect(data !== null).assertTrue();
done();
})
// Release the image packer after the encoding is complete.
imagePackerApi.release();
imagePackerApi.release();
// Obtain the image source information.
imageSourceApi.getImageInfo(imageInfo => {
console.info('TC_045 imageInfo');
expect(imageInfo !== null).assertTrue();
done();
})
console.info('TC_045 imageInfo');
expect(imageInfo !== null).assertTrue();
done();
})
// Update incremental 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 @@
## When to Use
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 yet is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
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.
## How to Develop
......@@ -27,8 +24,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
(*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
```
3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface.
```c++
......@@ -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);
```
4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance.
```c++
......@@ -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.
```
```c++
SLRecordItf recordItf;
(*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf);
```
```
6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface.
```
```c++
SLOHBufferQueueItf bufferQueueItf;
(*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf);
```
7. Register the **BufferQueueCallback** function.
```c++
......@@ -120,7 +111,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
(*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);
```
8. Start audio recording.
```c++
......@@ -145,7 +135,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
}
```
9. Stop audio recording.
```c++
......
# OpenSL ES Audio Playback Development
## 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.
## How to Develop
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
#include <OpenSLES_Platform.h>
```
2. Use the **slCreateEngine** API to obtain an **engine** instance.
```c++
......@@ -30,8 +24,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
```
3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface.
```c++
......@@ -39,8 +31,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);
```
4. Configure the player and create an **AudioPlayer** instance.
```c++
......@@ -66,8 +56,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE);
```
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
(*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf);
```
6. Open an audio file and register the **BufferQueueCallback** function.
```c++
......@@ -101,8 +87,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);
```
7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** interface and start playback.
```c++
......@@ -111,8 +95,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);
```
8. Stop audio playback.
```c++
......
......@@ -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
![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of video recording
![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
double position[2] = {10.0, 15.0};
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]);
```
## Samples
The following samples are provided to help you better understand how to use the Native Drawing module:
* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp)
* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp)
......@@ -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) {
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
## Configuration File Internal Structure
The **HarmonyAppProvision** file consists of several parts, which are described in the table below.
**Table 1** Configuration file internal structure
| Name | Description | Data Type| Mandatory | Initial Value Allowed|
**Table 1** Internal structure of the HarmonyAppProvision file
| 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-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|
| 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|
| issuer | Issuer of the **HarmonyAppProvision** file. | String | 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|
| uuid | Unique ID of the **HarmonyAppProvision** file. | 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|
| 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 |
| 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 |
| 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 |
| 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 |
| 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 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:
```json
......@@ -54,46 +54,46 @@ An example of the **HarmonyAppProvision** file is as follows:
### 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-after | End 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 |
### 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
| 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 |
### 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.
**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
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
| 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
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
| 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-ids | IDs of devices on which your application can be debugged.| String array | 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 |
......@@ -59,6 +59,7 @@
- Bundle Management
- [@ohos.bundle](js-apis-Bundle.md)
- [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md)
- [@ohos.bundleState](js-apis-deviceUsageStatistics.md)
- [@ohos.zlib](js-apis-zlib.md)
- bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md)
......@@ -108,6 +109,7 @@
- [@ohos.configPolicy](js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md)
- [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- Security
......@@ -173,6 +175,7 @@
- [@ohos.hichecker](js-apis-hichecker.md)
- [@ohos.hidebug](js-apis-hidebug.md)
- [@ohos.hilog](js-apis-hilog.md)
- [@ohos.hiSysEvent](js-apis-hisysevent.md)
- [@ohos.hiTraceChain](js-apis-hitracechain.md)
- [@ohos.hiTraceMeter](js-apis-hitracemeter.md)
- [@ohos.inputMethod](js-apis-inputmethod.md)
......@@ -192,13 +195,13 @@
- [@ohos.geolocation](js-apis-geolocation.md)
- [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md)
- [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md)
- [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md)
- [@ohos.multimodalInput.inputEventClient](js-apis-inputeventclient.md)
- [@ohos.multimodalInput.inputMonitor](js-apis-inputmonitor.md)
- [@ohos.multimodalInput.inputEvent](js-apis-inputevent.md)
- [@ohos.multimodalInput.keyCode](js-apis-keycode.md)
- [@ohos.multimodalInput.keyEvent](js-apis-keyevent.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.runningLock](js-apis-runninglock.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
> **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.
......@@ -22,7 +23,7 @@ Creates an **Animator** object.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.|
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.|
**Return value**
| Type| Description|
......@@ -213,6 +214,8 @@ animator.oncancel();
onrepeat: () => void
Called when this animation repeats.
**System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example**
......@@ -220,8 +223,6 @@ onrepeat: () => void
animator.onrepeat();
```
Called when this animation repeats.
## AnimatorOptions
Defines animator options.
......@@ -231,7 +232,7 @@ Defines animator options.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.|
| easing | string | Yes| Animation interpolation curve. The default value is **ease**.|
| easing | string | Yes| Animation interpolation curve. The default value is **'ease'**.|
| delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.|
| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that 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**.|
......
# 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>
> 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
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
......@@ -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;
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
......@@ -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
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
......@@ -986,7 +986,7 @@ Authenticates an app account to obtain the Open Authorization (OAuth) token. Thi
| 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. |
| authType | string | Yes | Authentication type. |
| 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
| Name | Type | Mandatory | Description |
| ---------- | ---------------------------- | ----- | ---------------- |
| 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. |
**Example**
......@@ -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 | 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**
......@@ -2002,7 +2002,7 @@ Represents the options for setting authenticator properties.
| 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.|
## Constants<sup>8+</sup>
......@@ -2037,7 +2037,7 @@ Enumerates the result codes.
| ----------------------------------- | ----- | ------------ |
| SUCCESS | 0 | The operation is successful. |
| 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_REQUEST | 10004 | The request is invalid. |
| ERROR_INVALID_RESPONSE | 10005 | The response is invalid. |
......@@ -2063,7 +2063,7 @@ Provides OAuth authenticator callbacks.
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
......@@ -2093,7 +2093,7 @@ Returns the result of an authentication request.
onRequestRedirected: (request: Want) =&gt; void
Redirects a request.
Called to redirect a request.
**System capability**: SystemCapability.Account.AppAccount
......@@ -2126,7 +2126,7 @@ Redirects a request.
onRequestContinued: () =&gt; void
Continues to process the request.
Called to continue to process the request.
**System capability**: SystemCapability.Account.AppAccount
......@@ -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;
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
......@@ -2191,7 +2191,7 @@ Verifies the app account credential. This API uses an asynchronous callback to r
| Name | Type | Mandatory | Description |
| ---------------- | --------------------- | ---- | --------------- |
| 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.|
### setProperties<sup>9+</sup>
......
......@@ -3,7 +3,7 @@
> **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.
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
......@@ -201,7 +201,7 @@ Obtains the connection state of a profile.
| 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**
......@@ -222,12 +222,12 @@ cancelPairedDevice(deviceId: string): boolean
Cancels a paired remote device.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
......@@ -388,7 +388,7 @@ startBluetoothDiscovery(): boolean
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
......@@ -1039,9 +1039,9 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
## 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
......@@ -1055,7 +1055,7 @@ Obtains a profile instance. **HidHostProfile** is added in API version 9.
| 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**
......@@ -1344,7 +1344,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device to connect.|
| device | string | Yes | Address of the target device.|
**Return value**
......@@ -1374,7 +1374,7 @@ Disconnects an A2DP connection.
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device to disconnect.|
| device | string | Yes | Address of the target device.|
**Return value**
......@@ -1422,7 +1422,7 @@ a2dpSrc.on('connectionStateChange', onReceiveEvent);
### 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.
......@@ -1451,12 +1451,14 @@ a2dpSrc.off('connectionStateChange', onReceiveEvent);
```
### getPlayingState
### getPlayingState<sup>9+</sup>
getPlayingState(device: string): PlayingState
Obtains the playing state of a device.
**Required permissions**: ohos.permission.USE_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
......@@ -1576,7 +1578,7 @@ hfpAg.on('connectionStateChange', onReceiveEvent);
### 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.
......@@ -1616,12 +1618,12 @@ connect(device: string): boolean
Connects to the HidHost service of a device.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
......@@ -1648,12 +1650,12 @@ disconnect(device: string): boolean
Disconnects from the HidHost service of a device.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
......@@ -1706,7 +1708,7 @@ hidHost.on('connectionStateChange', onReceiveEvent);
### 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.
......@@ -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
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.
**Example**
```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 characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
......@@ -2335,6 +2502,7 @@ let gattServer = bluetooth.BLE.createGattServer();
gattServer.off("descriptorWrite");
```
### on('connectStateChange')
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
```js
// Promise
let device = bluetooth.BLE.createGattClientDevice('XX:XX:XX:XX:XX:XX');
device.connect();
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);
}
gattClientDevice.getServices().then(result => {
console.info("Got services successfully:" + JSON.stringify(result));
});
```
......@@ -2556,7 +2719,7 @@ for (let i = 0; i < services.length; i++) {
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
......@@ -2610,7 +2773,7 @@ device.readCharacteristicValue(characteristic, readCcc);
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
......@@ -2657,7 +2820,7 @@ device.readCharacteristicValue(characteristic);
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
......@@ -2701,7 +2864,7 @@ device.readDescriptorValue(descriptor, readDesc);
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
......@@ -2881,6 +3044,15 @@ Sets the function of notifying the GATT client when the characteristic value of
**Example**
```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 characteristic = {serviceUuid: '00001810-0000-1000-8000-00805F9B34FB',
characteristicUuid: '00001820-0000-1000-8000-00805F9B34FB', characteristicValue: arrayBufferC, descriptors:descriptors};
......@@ -3139,7 +3311,7 @@ Enumerates the scan modes.
**System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description |
| Name | Default Value | Description |
| ---------------------------------------- | ---- | --------------- |
| SCAN_MODE_NONE | 0 | No scan mode. |
| SCAN_MODE_CONNECTABLE | 1 | Connectable mode. |
......@@ -3154,7 +3326,7 @@ Enumerates the pairing states.
**System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description |
| Name | Default Value | Description |
| ------------------ | ---- | ------ |
| BOND_STATE_INVALID | 0 | Invalid pairing.|
| BOND_STATE_BONDING | 1 | Pairing. |
......@@ -3180,7 +3352,7 @@ Enumerates the SPP link types.
**System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description |
| Name | Default Value | Description |
| ---------- | ---- | ------------- |
| SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.|
......
......@@ -42,7 +42,7 @@ Provides the ability information.
| labelId | number | Yes | No | Ability label ID. |
| 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>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. |
| 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. |
......
# ApplicationInfo
> **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.
Provides the application information.
## ApplicationInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Readable| Writable| Description |
| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------ |
| name | string | Yes | No | Application name. |
| description | string | Yes | No | Application description. |
| descriptionId | number | Yes | No | Application description ID. |
| 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**. |
| label | string | Yes | No | Application label. |
| labelId | string | Yes | No | Application label ID. |
| icon | string | Yes | No | Application icon. |
| 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.|
| supportedModes | number | Yes | No | Running modes supported by the application. |
| moduleSourceDirs | Array\<string> | Yes | No | Relative paths for storing application resources. |
| permissions | Array\<string> | Yes | No | Permissions required for accessing the application. |
| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. |
| entryDir | string | Yes | No | Path for storing application files. |
| 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>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. |
| accessTokenId<sup>8+</sup> | number | Yes | No | Access token ID 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. |
| 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. |
| Name | Type | Readable| Writable| Description |
| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ |
| name | string | Yes | No | Application name. |
| description | string | Yes | No | Application description. |
| descriptionId | number | Yes | No | Application description ID. |
| 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**. |
| label | string | Yes | No | Application label. |
| labelId | string | Yes | No | Application label ID. |
| icon | string | Yes | No | Application icon. |
| 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. |
| supportedModes | number | Yes | No | Running modes supported by the application. |
| moduleSourceDirs | Array\<string> | Yes | No | Relative paths for storing application resources. |
| permissions | Array\<string> | Yes | No | Permissions required for accessing the application. |
| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. |
| entryDir | string | Yes | No | Path for storing application files. |
| 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>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. |
| accessTokenId<sup>8+</sup> | number | Yes | No | Access token ID 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. |
| 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 @@
> **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.
Provides the application bundle information.
## BundleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
......
......@@ -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.
Provides custom metadata.
## CustomizeData
**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 @@
> **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.
Provides the Extension ability information.
## ExtensionAbilityInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
......@@ -25,7 +26,7 @@ Provides the Extension ability information.
| 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.|
| 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. |
| 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. |
......@@ -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.
Provides the HAP module information.
## HapModuleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
......@@ -35,4 +36,4 @@ Provides the HAP module information.
| 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.|
| 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. |
\ No newline at end of file
| hashValue<sup>9+</sup> | string | Yes | No | Hash value of the module. |
......@@ -2,14 +2,15 @@
> **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.
> **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.
Provides the metadata information.
## Metadata
**System capability**: SystemCapability.BundleManager.BundleFramework
......
......@@ -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.
Provides the module information of the application.
## ModuleInfo
**System capability**: SystemCapability.BundleManager.BundleFramework
......
# Performance Tracing
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
> - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead.
> - 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.
......@@ -17,7 +17,7 @@ import bytrace from '@ohos.bytrace';
startTrace(name: string, taskId: number, expectedTime?: number): void
Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace.
Marks the start of a timeslice trace task.
**System capability**: SystemCapability.Developtools.Bytrace
......@@ -25,11 +25,12 @@ Starts a trace task. **expectedTime** is an optional parameter, which specifies
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the trace task to start.|
| taskId | number | Yes| Task ID.|
| name | string | Yes| Name of a timeslice trace task.|
| taskId | number | Yes| ID of a timeslice trace task.|
| expectedTime | number | No| Expected duration of the trace, in ms.|
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. If the trace tasks with the same name are not performed at the same time, the same taskId can be used. For details, see the bytrace.finishTrace example.
**Example**
......@@ -44,7 +45,7 @@ bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is
finishTrace(name: string, taskId: number): void
Stops a trace task.
Marks the end of a timeslice trace task.
**System capability**: SystemCapability.Developtools.Bytrace
......@@ -52,10 +53,11 @@ Stops a trace task.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the trace task to start.|
| taskId | number | Yes| Task ID.|
| name | string | Yes| Name of a timeslice trace task.|
| taskId | number | Yes| ID of a timeslice trace task.|
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> **NOTE**
>
> To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**.
**Example**
......@@ -91,7 +93,7 @@ bytrace.finishTrace("myTestFunc", 1);
traceByValue(name: string, count: number): void
Traces the value changes of a variable.
Defines the variable that indicates the number of timeslice trace tasks.
**System capability**: SystemCapability.Developtools.Bytrace
......
# Standard NFC Card Emulation
Implements Near-Field Communication (NFC) card emulation.
The cardEmulation module implements Near-Field Communication (NFC) card emulation.
> **NOTE**<br>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## **Modules to Import**
## Modules to Import
```
import cardEmulation from '@ohos.nfc.cardEmulation';
......
# Distributed Data Object
Provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices.
The distributedDataObject module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices.
> **NOTE**<br/>
>
......@@ -23,9 +23,9 @@ Creates a distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| source | object | Yes| Attribute of the distributed data object to create.|
**Return value**
| Type| Description|
......@@ -33,12 +33,11 @@ Creates a distributed data object.
| [DistributedObject](#distributedobject) | Distributed data object created.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object.
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,
parent:{mother:"jack mom",father:"jack Dad"}});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
// Create a distributed data object, which contains attributes of four types, namely, string, number, boolean, and object.
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
```
## distributedObject.genSessionId
......@@ -50,15 +49,15 @@ Creates a random session ID.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value**
| Type| Description|
| -------- | -------- |
| string | Session ID created.|
| Type| Description|
| -------- | -------- |
| string | Session ID created.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
var sessionId = distributedObject.genSessionId();
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var sessionId = distributedObject.genSessionId();
```
## SaveSuccessResponse<sup>9+</sup>
......@@ -98,27 +97,26 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the session ID is set successfully;<br>returns **false** otherwise. |
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,
parent:{mother:"jack mom",father:"jack Dad"}});
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId());
// Remove g_object from the distributed network.
g_object.setSessionId("");
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});;
// Add g_object to the distributed network.
g_object.setSessionId(distributedObject.genSessionId());
// Remove g_object from the distributed network.
g_object.setSessionId("");
```
### on('change')
......@@ -130,15 +128,15 @@ Subscribes to the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | Yes| Callback used to return the changes of the distributed data object.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}});
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.changeCallback = (sessionId, changeData) => {
console.info("change" + sessionId);
if (changeData != null && changeData != undefined) {
......@@ -159,16 +157,16 @@ Unsubscribes from the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
| callback | Callback<{ sessionId: string, fields: Array&lt;string&gt; }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.<br>**sessionId** indicates the session ID of the distributed data object.<br>**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}});
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
// Unregister the specified data change callback.
g_object.off("change", globalThis.changeCallback);
// Unregister all data change callbacks.
......@@ -184,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.<br>**sessionId**: session ID of the distributed data object.<br>**networkId**: object device ID, that is, **deviceId**.<br>**status** indicates the object status, which can be online or offline.|
**Example**
```js
......@@ -195,7 +193,7 @@ import distributedObject from '@ohos.data.distributedDataObject';
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}});
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
g_object.on("status", globalThis.statusCallback);
```
......@@ -209,16 +207,16 @@ Unsubscribes from the status change (online or offline) of this distributed data
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.<br>**sessionId**: session ID of the distributed data object.<br>**deviceId** indicates the device ID of the distributed data object.<br>**status** indicates the status, which can be online or offline.|
**Example**
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false,parent:{mother:"jack mom",father:"jack Dad"}});
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false, parent:{mother:"jack mom",father:"jack Dad"}});
globalThis.statusCallback = (sessionId, networkId, status) => {
globalThis.response += "status changed " + sessionId + " " + status + " " + networkId;
}
......@@ -245,24 +243,24 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
| callback | AsyncCallback&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
```ts
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local", (result)=>{
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local", (status, result)=>{
console.log("save status = " + status);
console.log("save callback");
console.info("save sessionId: " + result.sessionId);
console.info("save version: " + result.version);
console.info("save deviceId: " + result.deviceId);
});
```
### save<sup>9+</sup>
......@@ -281,31 +279,31 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
**Return value**
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[SaveSuccessResponse](#savesuccessresponse9)&gt; | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
```ts
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local").then((result)=>{
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, ()=>{
console.error("save failed");
});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.save("local").then((result)=>{
console.log("save callback");
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, ()=>{
console.error("save failed");
});
```
### revokeSave<sup>9+</sup>
......@@ -319,20 +317,20 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| callback | AsyncCallback&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
```ts
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.revokeSave((result, data) =>{
console.log("revokeSave callback");
});
```
### revokeSave<sup>9+</sup>
......@@ -345,22 +343,22 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value**
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
| Type| Description|
| -------- | -------- |
| Promise&lt;[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)&gt; | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
```ts
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.revokeSave("local").then((result)=>{
console.log("revokeSave callback");
console.log("sessionId" + result.sessionId);
}, ()=>{
console.error("revokeSave failed");
});
```
```js
import distributedObject from '@ohos.data.distributedDataObject';
var g_object = distributedObject.createDistributedObject({name:"Amy", age:18, isVis:false});
g_object.setSessionId("123456");
g_object.revokeSave().then((result)=>{
console.log("revokeSave callback");
console.log("sessionId" + result.sessionId);
}, ()=>{
console.error("revokeSave failed");
});
```
# 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/>
>
> 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
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
import dataRdb from '@ohos.data.rdb';
......@@ -20,7 +23,7 @@ promise.then((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
......
......@@ -213,7 +213,7 @@ Called when the configuration of the environment where the ability is running is
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| config | [Configuration](#section188911144124715) | Yes| New configuration.|
| config | [Configuration](js-apis-configuration.md) | Yes| New configuration.|
**Example**
......
# Key Event
Represents key events reported by an input device.
The Key Event module provides key events reported by an input device.
> **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.
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册