提交 287e8245 编写于 作者: W wangjiangying

Merge branch 'OpenHarmony-3.2-Beta2' of https://gitee.com/bmeangel/docs into OpenHarmony-3.2-Beta2

...@@ -198,8 +198,9 @@ zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease ...@@ -198,8 +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-display.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-screenshot.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-window.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-screen.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-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-windowAnimationManager.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-webgl2.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-audio.md @zengyawen
......
...@@ -38,13 +38,13 @@ ...@@ -38,13 +38,13 @@
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filepath" name="en/contribute" desc="already checked"/> <filteritem type="filepath" name="en/contribute/.*" desc="already checked"/>
</filefilter> </filefilter>
<filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies"> <filefilter name="copyrightPolicyFilter" desc="Filters for copyright header policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filepath" name="abcdefg/.*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
<!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/--> <!--filteritem type="filepath" name="projectroot/[a-zA-Z0-9]{20,}.sh" desc="Temp files"/-->
<filteritem type="filepath" name="en/contribute" desc="already checked"/> <filteritem type="filepath" name="en/contribute/.*" desc="already checked"/>
</filefilter> </filefilter>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies"> <filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies">
<!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/--> <!--filteritem type="filename" name="*.uvwxyz" desc="Describe the reason for filtering scan results"/-->
......
...@@ -26,7 +26,7 @@ ...@@ -26,7 +26,7 @@
- OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。 - OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。
该版本已更新至OpenHarmony 3.0.3 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.3-LTS.md)了解版本详情。 该版本已更新至OpenHarmony 3.0.5 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md)了解版本详情。
- OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。 - OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。
......
#!/bin/bash
# Copyright (c) 2020 Huawei Device Co., Ltd.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
docker build -t openharmony-docker:1.0.0 .
...@@ -29,6 +29,3 @@ In addition, the following differences exist in the development process: ...@@ -29,6 +29,3 @@ In addition, the following differences exist in the development process:
For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md). For details about the two models, see [FA Model Overview](fa-brief.md) and [Stage Model Overview](stage-brief.md).
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [Intra- and Inter-page Navigation](https://gitee.com/openharmony/codelabs/tree/master/Ability/PageAbility)
...@@ -26,17 +26,3 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy** ...@@ -26,17 +26,3 @@ Currently, the **app.js** file provides only the **onCreate** and **onDestroy**
An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other. An application exclusively uses an independent process, and an ability exclusively uses an independent thread. When an ability is started for the first time, an application process as well as a thread for this ability is created. After the application is started, other abilities in the application are started, and a thread is created for every of these started abilities. Each ability is bound to an independent JSRuntime instance. In this way, abilities are isolated from each other.
![fa-threading-model](figures/fa-threading-model.png) ![fa-threading-model](figures/fa-threading-model.png)
## Samples
The following sample is provided to help you better understand how to develop abilities:
- [`DistributeCalc`: Distributed Calculator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/Preset/DistributeCalc)
- [`DistributeGraffiti`: Distributed Graffiti (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DistributedGraffiti)
- [Remote FA Startup](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA)
- [Distributed News App](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo)
- [Synced Sketchpad (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts)
- [Distributed Authentication (JS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH)
- [Distributed Game Controller (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication)
- [Distributed Mail System (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS)
- [Distributed Jigsaw Puzzle (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame)
- [Distributed Control (eTS)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS)
# Data Ability Development # Data Ability Development
## When to Use ## When to Use
A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices. A Data ability helps applications manage access to data stored by themselves and other applications. It also provides APIs for sharing data with other applications either on the same device or across devices.
Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs. Data ability providers can customize data access-related APIs such as data inserting, deleting, updating, and querying, as well as file opening, and share data with other applications through these open APIs.
## URI Introduction
A Uniform Resource Identifier (URI) is used to identify a specific data item, such as a table in the database or a file on the disk. URIs used in OpenHarmony comply with the commonly used URI standard. A URI consists of the components:
![fa-dataability-uri](figures/fa-dataability-uri.png)
- **scheme**: name of the scheme used by the Data ability. The value is fixed at **dataability**.
- **authority**: device ID. To access data on a remote device, set this component to the ID of the remote device. To access data on the local device, leave this component empty.
- **path**: location of the specific resource to access.
- **query**: query parameters.
- **fragment**: subordinate resources to access.
Example URIs:
- Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10*
- Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10*
> **NOTE**
>
> In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**.
## Available APIs ## Available APIs
**Table 1** Data ability lifecycle APIs **Table 1** Data ability lifecycle APIs
...@@ -129,7 +154,7 @@ The basic dependency packages include: ...@@ -129,7 +154,7 @@ The basic dependency packages include:
import featureAbility from '@ohos.ability.featureAbility' import featureAbility from '@ohos.ability.featureAbility'
import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_ability from '@ohos.data.dataAbility'
import ohos_data_rdb from '@ohos.data.rdb' import ohos_data_rdb from '@ohos.data.rdb'
var urivar = "dataability:///com.ix.DataAbility" var urivar = "dataability:///com.ix.DataAbility"
var DAHelper = featureAbility.acquireDataAbilityHelper( var DAHelper = featureAbility.acquireDataAbilityHelper(
urivar urivar
...@@ -283,9 +308,3 @@ The basic dependency packages include: ...@@ -283,9 +308,3 @@ The basic dependency packages include:
] ]
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop Data abilities:
- [`DataAbility`: Creation and Access of Data Abilities (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DataAbility)
...@@ -349,8 +349,3 @@ Now you've got a widget shown below. ...@@ -349,8 +349,3 @@ Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
## Samples
The following samples are provided to help you better understand how to develop a widget on the FA model:
- [`FormAbility`: FA Model Widget (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormAbility)
- [`FormLauncher`: Widget Host (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormLauncher)
...@@ -217,7 +217,3 @@ export default { ...@@ -217,7 +217,3 @@ export default {
}, },
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop a Page ability:
- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
...@@ -134,7 +134,7 @@ You can use either of the following methods to connect to a Service ability: ...@@ -134,7 +134,7 @@ You can use either of the following methods to connect to a Service ability:
```javascript ```javascript
import prompt from '@system.prompt' import prompt from '@system.prompt'
let mRemote; let mRemote;
function onConnectCallback(element, remote){ function onConnectCallback(element, remote){
console.log('onConnectLocalService onConnectDone element: ' + element); console.log('onConnectLocalService onConnectDone element: ' + element);
...@@ -161,13 +161,13 @@ You can use either of the following methods to connect to a Service ability: ...@@ -161,13 +161,13 @@ You can use either of the following methods to connect to a Service ability:
}).catch((e) => { }).catch((e) => {
console.log('sendRequest error:' + e); console.log('sendRequest error:' + e);
}); });
} }
function onDisconnectCallback(element){ function onDisconnectCallback(element){
console.log('ConnectAbility onDisconnect Callback') console.log('ConnectAbility onDisconnect Callback')
} }
function onFailedCallback(code){ function onFailedCallback(code){
console.log('ConnectAbility onFailed Callback') console.log('ConnectAbility onFailed Callback')
} }
...@@ -196,7 +196,7 @@ You can use either of the following methods to connect to a Service ability: ...@@ -196,7 +196,7 @@ You can use either of the following methods to connect to a Service ability:
```javascript ```javascript
import rpc from "@ohos.rpc"; import rpc from "@ohos.rpc";
let mMyStub; let mMyStub;
export default { export default {
onStart() { onStart() {
...@@ -424,9 +424,3 @@ export default { ...@@ -424,9 +424,3 @@ export default {
} }
}; };
``` ```
## Samples
The following samples are provided to help you better understand how to develop a Service ability:
- [`ServiceAbility`: Service Ability Creation and Use (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/ServiceAbility)
- [`DMS`: Distributed Demo (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/ability/DMS)
...@@ -317,7 +317,3 @@ struct Index { ...@@ -317,7 +317,3 @@ struct Index {
} }
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop an ability on the stage model:
- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
...@@ -247,7 +247,3 @@ try { ...@@ -247,7 +247,3 @@ try {
Logger.error(TAG, `caller release failed with ${error}`) Logger.error(TAG, `caller release failed with ${error}`)
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop an ability call in the stage model:
- [`StageCallAbility`: Stage Call Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
...@@ -358,8 +358,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme ...@@ -358,8 +358,3 @@ You can use HML, CSS, and JSON to develop the UI page for a JavaScript-programme
Now you've got a widget shown below. Now you've got a widget shown below.
![fa-form-example](figures/fa-form-example.png) ![fa-form-example](figures/fa-form-example.png)
## Samples
The following sample is provided to help you better understand how to develop a widget on the stage model:
- [`FormExtAbility`: Stage Model Widget (eTS, JS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/FormExtAbility)
...@@ -50,7 +50,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -50,7 +50,7 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
onRemoteRequest(code, data, reply, option) { onRemoteRequest(code, data, reply, option) {
} }
} }
class ServiceExt extends ServiceExtensionAbility { class ServiceExt extends ServiceExtensionAbility {
console.log('onCreate, want:' + want.abilityName); console.log('onCreate, want:' + want.abilityName);
} }
...@@ -69,7 +69,3 @@ OpenHarmony does not support creation of a Service Extension ability for third-p ...@@ -69,7 +69,3 @@ OpenHarmony does not support creation of a Service Extension ability for third-p
} }
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop Service Extension abilities:
- [`ServiceExtAbility`: Stage Extension Ability Creation and Usage (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/ability/StageCallAbility)
...@@ -71,7 +71,3 @@ httpRequest.request( ...@@ -71,7 +71,3 @@ httpRequest.request(
} }
); );
``` ```
## Samples
The following sample is provided to help you better understand how to develop the HTTP data request feature:
- [`Http`: HTTP Data Request (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Http)
...@@ -19,4 +19,4 @@ In OpenHarmony documents, proxy represents the service requester, and stub repre ...@@ -19,4 +19,4 @@ In OpenHarmony documents, proxy represents the service requester, and stub repre
## Related Modules ## Related Modules
[Distributed Scheduler](https://gitee.com/openharmony/distributedschedule_dms_fwk) [Distributed Scheduler](https://gitee.com/openharmony/ability_dmsfwk)
...@@ -122,7 +122,3 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th ...@@ -122,7 +122,3 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th
tcp.off('close'); tcp.off('close');
}, 30 * 1000); }, 30 * 1000);
``` ```
## Samples
The following sample is provided to help you better understand how to develop the socket connection feature:
- [`Socket`: Socket Connection (eTS) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Network/Socket)
...@@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca ...@@ -7,6 +7,8 @@ The distributed data objects allow data across devices to be processed like loca
## Available APIs ## 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 ### 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**. 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. ...@@ -15,7 +17,7 @@ Call **createDistributedObject()** to create a distributed data object instance.
**Table 1** API for creating a distributed data object instance **Table 1** API for creating a distributed data object instance
| Package| API| Description| | 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 ### Generating a Session ID
...@@ -33,16 +35,16 @@ Call **setSessionId()** to set a session ID for a distributed data object. The s ...@@ -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 **Table 3** API for setting a session ID
| Class| API| Description| | 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 ### 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. 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 **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.| | 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 ### Observing Online or Offline Status
...@@ -67,13 +69,13 @@ The saved data will be released in the following cases: ...@@ -67,13 +69,13 @@ The saved data will be released in the following cases:
- The application has been uninstalled. - The application has been uninstalled.
- Data is successfully restored. - 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| | 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): 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| 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(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(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result.|
## How to Develop ## How to Develop
...@@ -157,7 +159,7 @@ The following example shows how to implement a distributed data object synchroni ...@@ -157,7 +159,7 @@ The following example shows how to implement a distributed data object synchroni
local_object.on("change", this.changeCallback.bind(this)); 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: The sample code is as follows:
```js ```js
...@@ -205,41 +207,39 @@ The following example shows how to implement a distributed data object synchroni ...@@ -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. 10. Save a distributed data object and revoke the data saving operation.
- Callback - Callback
```js
```js // Save a distributed data object.
// Save a distributed data object. local_object.save("local", (result, data)=>{
local_object.save("local", (result, data)=>{ console.log("save callback");
console.log("save callback"); console.info("save sessionId " + data.sessionId);
console.info("save sessionId " + data.sessionId); console.info("save version " + data.version);
console.info("save version " + data.version); console.info("save deviceId " + data.deviceId);
console.info("save deviceId " + data.deviceId); });
}); // Revoke the data saving operation.
// Revoke the data saving operation. local_object.revokeSave((result, data) =>{
local_object.revokeSave((result, data) =>{ console.log("revokeSave callback");
console.log("revokeSave callback"); console.info("revokeSave sessionId " + data.sessionId);
console.info("revokeSave sessionId " + data.sessionId); });
}); ```
``` - Promise
- Promise ```js
// Save a distributed data object.
```js g_object.save("local").then((result)=>{
// Save a distributed data object. console.info("save sessionId " + result.sessionId);
g_object.save("local").then((result)=>{ console.info("save version " + result.version);
console.info("save sessionId " + result.sessionId); console.info("save deviceId " + result.deviceId);
console.info("save version " + result.version); }, (result)=>{
console.info("save deviceId " + result.deviceId); console.info("save local failed.");
}, (result)=>{ });
console.info("save local failed."); // Revoke the data saving operation.
}); g_object.revokeSave().then((result)=>{
// Revoke the data saving operation. console.info("revokeSave success.");
g_object.revokeSave().then((result)=>{ }, (result)=>{
console.info("revokeSave success."); console.info("revokeSave failed.");
}, (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.
```
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.
The sample code is as follows: The sample code is as follows:
```js ```js
......
...@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -7,19 +7,21 @@ The Distributed Data Service (DDS) implements synchronization of application dat
## Available APIs ## 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. The table below describes the APIs provided by the OpenHarmony DDS module.
**Table 1** APIs provided by the DDS **Table 1** APIs provided by the DDS
| Category | API | Description | | 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.| | 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**. | | 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| 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| 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. | | 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. | | 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. | | 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. ...@@ -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. The following uses a single KV store as an example to describe the development procedure.
1. Import the distributed data module. 1. Import the distributed data module.
```js ```js
import distributedData from '@ohos.data.distributedData'; import distributedData from '@ohos.data.distributedData';
``` ```
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. 2. Create a **KvManager** instance based on the specified **KvManagerConfig** object.
1. Create a **KvManagerConfig** object based on the application context. (1) Create a **KvManagerConfig** object based on the application context.
2. Create a **KvManager** instance. (2) Create a **KvManager** instance.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -63,8 +64,8 @@ The following uses a single KV store as an example to describe the development p ...@@ -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. 3. Create and obtain a single KV store.
1. Declare the ID of the single KV store to create. (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. (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: The sample code is as follows:
```js ```js
...@@ -91,12 +92,11 @@ The following uses a single KV store as an example to describe the development p ...@@ -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. > 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: The following is the sample code for subscribing to the data changes of a single KV store:
```js ```js
kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) {
console.log("dataChange callback call data: " + JSON.stringify(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 ...@@ -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. 5. Write data to the single KV store.
1. Construct the key and value to be written 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. (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: 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 ...@@ -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. 6. Query data in the single KV store.
1. Construct the key to be queried 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. (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: The following is the sample code for querying data of the string type from the single KV store:
```js ```js
const KEY_TEST_STRING_ELEMENT = 'key_test_string'; const KEY_TEST_STRING_ELEMENT = 'key_test_string';
const VALUE_TEST_STRING_ELEMENT = 'value-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 ...@@ -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 # Preferences Development
> **NOTE**
>
> This feature is supported since API Version 9. For the versions earlier than API Version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs.
## When to Use ## When to Use
Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs. Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs.
## Available APIs ## Available APIs
Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md).
### Creating a Preferences Instance ### Creating a Preferences Instance
...@@ -26,7 +30,7 @@ Call the **put()** method to add or modify data in a **Preferences** instance. ...@@ -26,7 +30,7 @@ Call the **put()** method to add or modify data in a **Preferences** instance.
| Class | API | Description | | Class | API | Description |
| ------- | -------------------------------------------------- | ----------------------------------------------- | | ------- | -------------------------------------------------- | ----------------------------------------------- |
| Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data of the number, string, and Boolean types.| | Preferences | put(key: string, value: ValueType): Promise\<void> | Writes data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Reading Data ### Reading Data
...@@ -36,7 +40,7 @@ Call the **get()** method to read data from a **Preferences** instance. ...@@ -36,7 +40,7 @@ Call the **get()** method to read data from a **Preferences** instance.
| Class | API | Description | | Class | API | Description |
| ------- | ---------------------------------------------------------- | ----------------------------------------------- | | ------- | ---------------------------------------------------------- | ----------------------------------------------- |
| Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Reads data of the number, string, and Boolean types.| | Preferences | get(key: string, defValue: ValueType): Promise\<ValueType> | Obtains data with the value type of number, string, boolean, Array\<number>, Array\<string>, or Array\<boolean>.|
### Storing Data Persistently ### Storing Data Persistently
...@@ -67,7 +71,7 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -67,7 +71,7 @@ Use the following APIs to delete a **Preferences** instance or data file.
| Package | API | Description | | Package | API | Description |
| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ | | ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ |
| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise<void>; | Deletes a **Preferences** instance from the cache and deletes its file from the device.| | ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\<void>; | Deletes a **Preferences** instance from the cache and deletes its file from the device.|
| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory. | ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\<void>; | Removes a **Preferences** instance from the memory to release memory.
## How to Develop ## How to Develop
...@@ -91,8 +95,8 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -91,8 +95,8 @@ Use the following APIs to delete a **Preferences** instance or data file.
```js ```js
promise.then((preferences) => { promise.then((preferences) => {
let getPromise = preferences.put('startup', 'auto') let putPromise = preferences.put('startup', 'auto')
getPromise.then(() => { putPromise.then(() => {
console.info("Put the value of startup successfully.") console.info("Put the value of startup successfully.")
}).catch((err) => { }).catch((err) => {
console.info("Failed to put the value of startup with err: " + err) console.info("Failed to put the value of startup with err: " + err)
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
## When to Use ## When to Use
On the basis of the SQLite database, the relational database (RDB) allows you to operate data with or without native SQL statements. In OpenHarmony, an RDB is also called RDB store. A relational database (RDB) store allows you to operate local data with or without native SQL statements based on SQLite.
## Available APIs ## Available APIs
...@@ -11,7 +11,7 @@ For details about RDB APIs, see [Relational Database](../reference/apis/js-apis- ...@@ -11,7 +11,7 @@ For details about RDB APIs, see [Relational Database](../reference/apis/js-apis-
### Creating or Deleting an RDB Store ### Creating or Deleting an RDB Store
The following table describes the APIs available for creating and deleting an RDB store. The table below describes the APIs available for creating and deleting an RDB store.
**Table 1** APIs for creating and deleting an RDB store **Table 1** APIs for creating and deleting an RDB store
...@@ -34,7 +34,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -34,7 +34,7 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void | Inserts a row of data into a table. This API uses a callback to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.<br>- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned. Otherwise, **-1** will be returned.| | RdbStore | insert(table: string, values: ValuesBucket, callback: AsyncCallback&lt;number&gt;):void | Inserts a row of data into a table. This API uses a callback to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.<br>- **callback**: callback invoked to return the result. If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.|
| RdbStore | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.| | RdbStore | insert(table: string, values: ValuesBucket): Promise&lt;number&gt; | Inserts a row of data into a table. This API uses a promise to return the result.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.|
- **Updating data** - **Updating data**
...@@ -56,8 +56,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -56,8 +56,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void | Deletes data from the database based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.<br>- **predicates**: conditions for deleting data.<br>- **callback**: callback invoked to return the number of rows updated.| | RdbStore | delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.<br>- **predicates**: conditions for deleting data.<br>- **callback**: callback invoked to return the number of rows updated.|
| RdbStore | delete(predicates: RdbPredicates): Promise&lt;number&gt; | Deletes data from the database based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>- **predicates**: conditions for deleting data.| | RdbStore | delete(predicates: RdbPredicates): Promise&lt;number&gt; | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>- **predicates**: conditions for deleting data.|
- **Querying data** - **Querying data**
...@@ -70,8 +70,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -70,8 +70,8 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore | query(predicates: RdbPredicates, columns: Array, callback: AsyncCallback&lt;ResultSet&gt;): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This API uses a callback to return the result.<br>- **predicates**: conditions for querying data.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.<br>- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| | RdbStore | query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;): void | Queries data in the RDB store based on the specified **RdbPredicates** object. This API uses a callback to return the result.<br>- **predicates**: conditions for querying data.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.<br>- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
| RdbStore | query(predicates: RdbPredicates, columns: Array): Promise&lt;ResultSet&gt; | Queries data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>- **predicates**: conditions for querying data.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| | RdbStore | query(predicates: RdbPredicates, columns?: Array&lt;string&gt;): Promise&lt;ResultSet&gt; | Queries data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>- **predicates**: conditions for querying data.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
| RdbStore | querySql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void | Queries data in the RDB store using the specified SQL statement. This API uses a callback to return the result.<br>- **sql**: SQL statement.<br>- **bindArgs**: arguments in the SQL statement.<br>- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| | RdbStore | querySql(sql: string, bindArgs: Array&lt;ValueType&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void | Queries data in the RDB store using the specified SQL statement. This API uses a callback to return the result.<br>- **sql**: SQL statement.<br>- **bindArgs**: arguments in the SQL statement.<br>- **callback**: callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.|
| RdbStore | querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt; | Queries data in the RDB store using the specified SQL statement. This API uses a promise to return the result.<br>- **sql**: SQL statement.<br>- **bindArgs**: arguments in the SQL statement.| | RdbStore | querySql(sql: string, bindArgs?: Array&lt;ValueType&gt;):Promise&lt;ResultSet&gt; | Queries data in the RDB store using the specified SQL statement. This API uses a promise to return the result.<br>- **sql**: SQL statement.<br>- **bindArgs**: arguments in the SQL statement.|
...@@ -167,7 +167,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -167,7 +167,7 @@ You can obtain the distributed table name for a remote device based on the local
**Synchronizing Data Between Devices** **Synchronizing Data Between Devices**
**Table 10** APIs for cross-device data synchronization **Table 10** APIs for synchronizing data between devices
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
...@@ -190,7 +190,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -190,7 +190,7 @@ You can obtain the distributed table name for a remote device based on the local
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.<br>- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.<br>- **observer**: observer to unregister.| | RdbStore |off(event:'dataChange', type: SubscribeType, observer: Callback\<Array\<string>>): void;| Unregisters the observer of the specified type for the RDB store. This API uses a callback to return the result.<br>- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE** means to subscribe to remote data changes.<br>- **observer**: observer to unregister.|
### Backing Up and Restore an RDB Store ### Backing Up and Restoring an RDB Store
**Backing Up an RDB Store** **Backing Up an RDB Store**
...@@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -198,8 +198,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore |backup(destName:string, callback: AsyncCallback&lt;void&gt;):void| Backs up the RDB store with the specified name. This API uses an asynchronous callback to return the result.<br>- **destName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.| | RdbStore |backup(destName:string, callback: AsyncCallback&lt;void&gt;):void| Backs up an RDB store. This API uses an asynchronous callback to return the result.<br>- **destName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |backup(destName:string): Promise&lt;void&gt;| Backs up the RDB store with the specified name. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.| | RdbStore |backup(destName:string): Promise&lt;void&gt;| Backs up an RDB store. This API uses a promise to return the result.<br>- **destName**: name of the RDB backup file.|
**Restoring an RDB Store** **Restoring an RDB Store**
...@@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -207,8 +207,8 @@ You can obtain the distributed table name for a remote device based on the local
| Class| API| Description| | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| RdbStore |restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void| Restores an RDB store using the specified backup file. This API uses an asynchronous callback to return the result.<br>- **srcName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.| | RdbStore |restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void| Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.<br>- **srcName**: name of the RDB backup file.<br>- **callback**: callback invoked to return the result.|
| RdbStore |restore(srcName:string): Promise&lt;void&gt;| Restores an RDB store using the specified backup file. This API uses a promise to return the result.<br>- **srcName**: name of the RDB backup file.| | RdbStore |restore(srcName:string): Promise&lt;void&gt;| Restores an RDB store using a backup file. This API uses a promise to return the result.<br>- **srcName**: name of the RDB backup file.|
## How to Develop ## How to Develop
...@@ -251,9 +251,9 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -251,9 +251,9 @@ You can obtain the distributed table name for a remote device based on the local
(1) Create an **RdbPredicates** object to specify query conditions. (1) Create an **RdbPredicates** object to specify query conditions.
(2) Call the query() API to query data. (2) Call the **query()** API to query data.
(3) Call the resultSet() API to obtain the result. (3) Call the **resultSet()** API to obtain the result.
The sample code is as follows: The sample code is as follows:
...@@ -270,7 +270,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -270,7 +270,7 @@ You can obtain the distributed table name for a remote device based on the local
const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType")) const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"))
resultSet.close() resultSet.close()
}) })
``` ```
4. Set the distributed tables to be synchronized. 4. Set the distributed tables to be synchronized.
...@@ -283,7 +283,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -283,7 +283,7 @@ You can obtain the distributed table name for a remote device based on the local
} }
``` ```
(2) Obtain the application permissions. (2) Obtain the required permissions.
(3) Set the distributed tables. (3) Set the distributed tables.
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
## When to Use ## When to Use
With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group. With device usage statistics APIs, you can have a better understanding of the application, notification, and system usage. For example, in application usage statistics, you can query the application usage, event log, and bundle group.
The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported. The application records (usage history statistics and event records) cached by components are updated to the database for persistent storage within 30 minutes after an event is reported.
## Available APIs ## Available APIs
...@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState'; ...@@ -23,7 +22,7 @@ import stats from '@ohos.bundleState';
| function queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.|
| function queryAppUsagePriorityGroup(): Promise&lt;number&gt;; | Queries the priority group of this application. This API uses a promise to return the result.| | function queryAppUsagePriorityGroup(): Promise&lt;number&gt;; | Queries the priority group of this application. This API uses a promise to return the result.|
| function isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the application specified by **bundleName** is in the idle state. | | function isIdleState(bundleName: string, callback: AsyncCallback&lt;boolean&gt;): void | Checks whether the application specified by **bundleName** is in the idle state. |
| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | Obtains the number of FA usage records specified by **maxNum**.| | function getRecentlyUsedModules(maxNum? : number, callback: AsyncCallback&lt;BundleActiveModuleInfo&gt;): void | Obtains the number of FA usage records specified by **maxNum**. If **maxNum** is not specified, the default value **1000** is used.|
| function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries the number of notifications from all applications based on the specified start time and end time.| | function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries the number of notifications from all applications based on the specified start time and end time.|
| function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.| | function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback&lt;Array&lt;BundleActiveEventState&gt;&gt;): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.|
| function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(bundleName? : string, callback: AsyncCallback&lt;number&gt;): void | Queries the priority group of the application specified by **bundleName**. If **bundleName** is not specified, the priority group of the current application is queried. This API uses an asynchronous callback to return the result.|
...@@ -45,7 +44,7 @@ import stats from '@ohos.bundleState'; ...@@ -45,7 +44,7 @@ import stats from '@ohos.bundleState';
..., ...,
"reqPermissions": [ "reqPermissions": [
{ {
"name": "ohos.permission.BUNDLE_ACTIVE_INFO" "name": "ohos.permission.BUNDLE_ACTIVE_INFO"
} }
] ]
} }
...@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState'; ...@@ -57,13 +56,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleActiveStates(0, 20000000000000).then( res => { stats.queryBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleActiveStates promise failed, because: ' + err.code);
}); });
...@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState'; ...@@ -87,7 +86,7 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleStateInfos(0, 20000000000000).then( res => { stats.queryBundleStateInfos(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise success.');
let i = 1; let i = 1;
for (let key in res){ for (let key in res){
...@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState'; ...@@ -95,7 +94,7 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key])); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise result ' + JSON.stringify(res[key]));
i++; i++;
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfos promise failed, because: ' + err.code);
}); });
...@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState'; ...@@ -121,13 +120,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryCurrentBundleActiveStates(0, 20000000000000).then( res => { stats.queryCurrentBundleActiveStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.'); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryCurrentBundleActiveStates promise failed, because: ' + err.code);
}); });
...@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState'; ...@@ -151,13 +150,13 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { stats.queryBundleStateInfoByInterval(0, 0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise result ' + JSON.stringify(res[i]));
} }
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise failed, because: ' + err.code);
}); });
...@@ -179,14 +178,14 @@ import stats from '@ohos.bundleState'; ...@@ -179,14 +178,14 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
// Callback mode // Callback mode
stats.queryAppUsagePriorityGroup((err, res) => { stats.queryAppUsagePriorityGroup((err, res) => {
if (err) { if (err) {
...@@ -196,16 +195,16 @@ import stats from '@ohos.bundleState'; ...@@ -196,16 +195,16 @@ import stats from '@ohos.bundleState';
} }
}); });
``` ```
7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured in the **config.json** file. A third-party application can only check the idle status of itself. 7. Check whether the application specified by **bundleName** is in the idle state. This requires no permission to be configured in the **config.json** file. A third-party application can only check the idle status of itself.
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.isIdleState("com.ohos.camera").then( res => { stats.isIdleState("com.ohos.camera").then(res => {
console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE isIdleState promise succeeded, result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE isIdleState promise failed, because: ' + err.code);
}); });
...@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState'; ...@@ -225,18 +224,18 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.getRecentlyUsedModules(1000).then( res => { stats.getRecentlyUsedModules(1000).then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i])); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise result ' + JSON.stringify(res[i]));
} }
}).catch( err=> { }).catch(err=> {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise failed, because: ' + err.code);
}); });
// Promise mode when maxNum is not specified // Promise mode when maxNum is not specified
stats.getRecentlyUsedModules().then( res => { stats.getRecentlyUsedModules().then(res => {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise succeeded');
for (let i = 0; i < res.length; i++) { for (let i = 0; i < res.length; i++) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1)); console.log('BUNDLE_ACTIVE getRecentlyUsedModules promise number : ' + (i + 1));
...@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState'; ...@@ -247,7 +246,7 @@ import stats from '@ohos.bundleState';
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.getRecentlyUsedModules(1000,(err, res) => { stats.getRecentlyUsedModules(1000, (err, res) => {
if(err) { if(err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else { } else {
...@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState'; ...@@ -261,7 +260,7 @@ import stats from '@ohos.bundleState';
// Asynchronous callback mode when maxNum is not specified // Asynchronous callback mode when maxNum is not specified
stats.getRecentlyUsedModules((err, res) => { stats.getRecentlyUsedModules((err, res) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.'); console.log('BUNDLE_ACTIVE getRecentlyUsedModules callback succeeded.');
...@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState'; ...@@ -279,10 +278,10 @@ import stats from '@ohos.bundleState';
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryAppNotificationNumber(0, 20000000000000).then( res => { stats.queryAppNotificationNumber(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.'); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise success.');
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise result ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppNotificationNumber promise failed, because: ' + err.code);
}); });
...@@ -301,15 +300,15 @@ import stats from '@ohos.bundleState'; ...@@ -301,15 +300,15 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.queryBundleActiveEventStates(0, 20000000000000).then( res => { stats.queryBundleActiveEventStates(0, 20000000000000).then(res => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.'); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise success.');
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise result ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code); console.log('BUNDLE_ACTIVE queryBundleActiveEventStates promise failed, because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => { stats.queryBundleActiveEventStates(0, 20000000000000, (err, res) => {
if (err) { if (err) {
...@@ -325,14 +324,14 @@ import stats from '@ohos.bundleState'; ...@@ -325,14 +324,14 @@ import stats from '@ohos.bundleState';
```js ```js
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode without parameters // Promise mode without parameters
stats.queryAppUsagePriorityGroup().then( res => { stats.queryAppUsagePriorityGroup().then(res => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode without parameters // Asynchronous callback mode without parameters
stats.queryAppUsagePriorityGroup((err, res) => { stats.queryAppUsagePriorityGroup((err, res) => {
if (err) { if (err) {
...@@ -341,17 +340,17 @@ import stats from '@ohos.bundleState'; ...@@ -341,17 +340,17 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res));
} }
}); });
// Promise mode with parameters // Promise mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName).then( res => { stats.queryAppUsagePriorityGroup(this.bundleName).then(res => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res));
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode with parameters // Asynchronous callback mode with parameters
stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res)); console.log('BUNDLE_ACTIVE QueryPackageGroup callback succeeded. result: ' + JSON.stringify(res));
...@@ -363,16 +362,16 @@ import stats from '@ohos.bundleState'; ...@@ -363,16 +362,16 @@ import stats from '@ohos.bundleState';
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
stats.setBundleGroup(this.bundleName, this.newGroup).then( () => { stats.setBundleGroup(this.bundleName, this.newGroup).then(() => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.'); console.log('BUNDLE_ACTIVE SetBundleGroup promise succeeded.');
}).catch( err => { }).catch( err => {
console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE SetBundleGroup promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
stats.setBundleGroup(this.bundleName, this.newGroup, (err) => { stats.setBundleGroup(this.bundleName, this.newGroup, (err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code); console.log('BUNDLE_ACTIVE SetBundleGroup callback failed. because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.'); console.log('BUNDLE_ACTIVE SetBundleGroup callback succeeded.');
...@@ -384,9 +383,9 @@ import stats from '@ohos.bundleState'; ...@@ -384,9 +383,9 @@ import stats from '@ohos.bundleState';
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
// Promise mode // Promise mode
let onBundleGroupChanged = (err,res) =>{ let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result newGroup is : ' + res.newGroup);
...@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState'; ...@@ -394,13 +393,13 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result bundleName is : ' + res.bundleName);
}; };
stats.registerGroupCallBack(onBundleGroupChanged).then( () => { stats.registerGroupCallBack(onBundleGroupChanged).then(() => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise succeeded.');
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE RegisterGroupCallBack promise failed. because: ' + err.code);
}); });
// Asynchronous callback mode // Asynchronous callback mode
let onBundleGroupChanged = (err,res) =>{ let onBundleGroupChanged = (err,res) => {
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack callback success.');
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's oldGroup is : ' + res.oldGroup);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's newGroup is : ' + res.newGroup);
...@@ -408,29 +407,29 @@ import stats from '@ohos.bundleState'; ...@@ -408,29 +407,29 @@ import stats from '@ohos.bundleState';
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's userId is : ' + res.userId);
console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName); console.log('BUNDLE_ACTIVE onBundleGroupChanged RegisterGroupCallBack result's bundleName is : ' + res.bundleName);
}; };
stats.registerGroupCallBack(onBundleGroupChanged, (err)=>{ stats.registerGroupCallBack(onBundleGroupChanged, (err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE RegisterGroupCallBack callback success.');
} }
}); });
``` ```
13. Deregister the callback for application group changes. 13. Deregister the callback for application group changes.
```javascript ```javascript
import stats from '@ohos.bundleState' import stats from '@ohos.bundleState'
//promise //promise
stats.unRegisterGroupCallBack().then( () => { stats.unRegisterGroupCallBack().then(() => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.'); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise succeeded.');
}).catch( err => { }).catch(err => {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack promise failed. because: ' + err.code);
}); });
//callback //callback
stats.unRegisterGroupCallBack((err)=>{ stats.unRegisterGroupCallBack((err) => {
if(err) { if (err) {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback failed, because: ' + err.code);
} else { } else {
console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.'); console.log('BUNDLE_ACTIVE UnRegisterGroupCallBack callback success.');
......
...@@ -3,9 +3,9 @@ ...@@ -3,9 +3,9 @@
## When to Use ## When to Use
Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. Describing a location using coordinates is accurate, but neither intuitive nor user-friendly. With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa.
With the geocoding and reverse geocoding capabilities, you will be able to convert geographic description into specific coordinates and vice versa. The geocoding information describes a location using several attributes, including the country, administrative region, street, house number, and address, etc. The geographic description helps users understand a location easily by providing several key attributes, for example, country, administrative region, street, house number, and address.
## Available APIs ## Available APIs
...@@ -16,17 +16,18 @@ The following table describes APIs available for mutual conversion between coord ...@@ -16,17 +16,18 @@ The following table describes APIs available for mutual conversion between coord
| API | Description | | 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(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()&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. | | isGeoServiceAvailable() : Promise&lt;boolean&gt; | Checks whether the (reverse) geocoding service is available. This function uses a promise to return the 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: 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:&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. | | 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:&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: 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:&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. | | 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 ## 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. > 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. 1. Import the **geolocation** module by which you can implement all APIs related to the geocoding and reverse geocoding conversion capabilities.
...@@ -35,26 +36,46 @@ The following table describes APIs available for mutual conversion between coord ...@@ -35,26 +36,46 @@ The following table describes APIs available for mutual conversion between coord
import geolocation from '@ohos.geolocation'; import geolocation from '@ohos.geolocation';
``` ```
2. Obtain the conversion result. 2. Query whether geocoder service is available.
- Call **isGeoServiceAvailable** to query whether the geocoder service is available. If the service is available, continue with step 3.
```
geolocation.isGeoServiceAvailable((err, data) => {
if (err) {
console.log('isGeoServiceAvailable err: ' + JSON.stringify(err));
} else {
console.log('isGeoServiceAvailable data: ' + JSON.stringify(data));
}
});
```
3. Obtain the conversion result.
- Call **getAddressesFromLocation** to convert coordinates into geographical location information. - Call **getAddressesFromLocation** to convert coordinates into geographical location information.
``` ```
var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1};
geolocation.getAddressesFromLocation(reverseGeocodeRequest, (data) => { geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => {
console.log('getAddressesFromLocation: ' + JSON.stringify(data)); if (err) {
console.log('getAddressesFromLocation err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocation data: ' + JSON.stringify(data));
}
}); });
``` ```
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. - Call **getAddressesFromLocationName** to convert geographic description into coordinates.
``` ```
var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1};
geolocation.getAddressesFromLocationName(geocodeRequest, (data) => { geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => {
console.log('getAddressesFromLocationName: ' + JSON.stringify(data)); if (err) {
console.log('getAddressesFromLocationName err: ' + JSON.stringify(err));
} else {
console.log('getAddressesFromLocationName data: ' + JSON.stringify(data));
}
}); });
``` ```
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**. To improve the accuracy of location results, you can set the longitude and latitude ranges in **GeoCodeRequest**.
...@@ -123,7 +123,7 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -123,7 +123,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
The following example instantiates the **RequestParam** object for navigation: The following example instantiates the **RequestParam** object for navigation:
``` ```
var requestInfo = {'scenario': 0x301, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var requestInfo = {'scenario': geolocation.LocationRequestScenario.NAVIGATION, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
``` ```
**Method 2:** **Method 2:**
...@@ -152,7 +152,7 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -152,7 +152,7 @@ To learn more about the APIs for obtaining device location information, see [Geo
The following example instantiates the **RequestParam** object for the location accuracy priority policy: The following example instantiates the **RequestParam** object for the location accuracy priority policy:
``` ```
var requestInfo = {'priority': 0x201, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var requestInfo = {'priority': geolocation.LocationRequestPriority.ACCURACY, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0};
``` ```
4. Instantiate the **Callback** object for the system to report location results. 4. Instantiate the **Callback** object for the system to report location results.
...@@ -179,8 +179,12 @@ To learn more about the APIs for obtaining device location information, see [Geo ...@@ -179,8 +179,12 @@ To learn more about the APIs for obtaining device location information, see [Geo
If your application does not need the real-time device location, it can use the last known device location cached in the system instead. If your application does not need the real-time device location, it can use the last known device location cached in the system instead.
``` ```
geolocation.getLastLocation((data) => { geolocation.getLastLocation((err, data) => {
console.log('getLastLocation: data: ' + JSON.stringify(data)); if (err) {
console.log('getLastLocation: err: ' + JSON.stringify(err));
} else {
console.log('getLastLocation: data: ' + JSON.stringify(data));
}
}); });
``` ```
......
...@@ -135,8 +135,3 @@ ...@@ -135,8 +135,3 @@
console.error(error); console.error(error);
} }
``` ```
## Samples
The following sample is provided to help you better understand how to develop sensors:
- [`Sensor`: sensor (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Sensor)
...@@ -84,9 +84,3 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md ...@@ -84,9 +84,3 @@ For details about the APIs, see [Vibrator](../reference/apis/js-apis-vibrator.md
} }
}) })
``` ```
## Samples
The following sample is provided to help you better understand how to develop vibrators:
- [`Vibrator`: vibrator (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/device/Vibrator)
...@@ -9,3 +9,5 @@ ...@@ -9,3 +9,5 @@
- Distributed Call Chain Tracing - Distributed Call Chain Tracing
- [Overview of Distributed Call Chain Tracing](hitracechain-overview.md) - [Overview of Distributed Call Chain Tracing](hitracechain-overview.md)
- [Development of Distributed Call Chain Tracing](hitracechain-guidelines.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 ...@@ -88,9 +88,3 @@ In this example, an application event is logged after the application startup ex
``` ```
2. Tap the run button on the application UI to run the project. 2. Tap the run button on the application UI to run the project.
## Samples
The following sample is provided to help you better understand how to develop the application event logging feature:
- [`JsDotTest`: Event Logging Test (JavaScript) (API 8)](https://gitee.com/openharmony/app_samples/tree/master/DFX/JsDotTest)
...@@ -50,21 +50,21 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc ...@@ -50,21 +50,21 @@ Use [Locale](../reference/apis/js-apis-intl.md) APIs to maximize or minimize loc
2. Obtain the string representing a **Locale** object.<br> 2. Obtain the string representing a **Locale** object.<br>
Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options. Call the **toString** method to obtain the string representing a **Locale** object, which includes the language, region, and other options.
``` ```
var localeStr = localeObj.toString(); var localeStr = localeObj.toString();
``` ```
3. Maximize locale information.<br> 3. Maximize locale information.<br>
Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information. Call the **maximize** method to maximize locale information; that is, supplement the missing script and region information.
``` ```
var maximizedLocale = localeObj.maximize(); var maximizedLocale = localeObj.maximize();
``` ```
4. Minimize locale information.<br> 4. Minimize locale information.<br>
Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information. Call the **minimize** method to minimize locale information; that is, delete the unnecessary script and region information.
``` ```
var minimizedLocale = localeObj.minimize(); var minimizedLocale = localeObj.minimize();
``` ```
...@@ -105,7 +105,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -105,7 +105,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
2. Format the date and time.<br> 2. Format the date and time.<br>
Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result. Call the **format** method to format the date and time in the **DateTimeFormat** object. This method returns a string representing the formatting result.
``` ```
Date date = new Date(); Date date = new Date();
var formatResult = dateTimeFormat.format(date); var formatResult = dateTimeFormat.format(date);
...@@ -113,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -113,7 +113,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
3. Format a period.<br> 3. Format a period.<br>
Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result. Call the **formatRange** method to format the period in the **DateTimeFormat** object. This method requires input of two **Date** objects, which respectively indicate the start date and end date of a period. This method returns a string representing the formatting result.
``` ```
Date startDate = new Date(); Date startDate = new Date();
Date endDate = new Date(); Date endDate = new Date();
...@@ -122,7 +122,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date ...@@ -122,7 +122,7 @@ Use [DateTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the date
4. Obtain attributes of the **DateTimeFormat** object.<br> 4. Obtain attributes of the **DateTimeFormat** object.<br>
Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **DateTimeFormat** object. This method will return an array that contains all attributes and values of the object.
``` ```
var options = dateTimeFormat.resolvedOptions(); var options = dateTimeFormat.resolvedOptions();
``` ```
...@@ -162,7 +162,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for ...@@ -162,7 +162,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
2. Format a number.<br> 2. Format a number.<br>
Call the **format** method to format a number. A string is returned as the formatting result. Call the **format** method to format a number. A string is returned as the formatting result.
``` ```
var number = 1234.5678 var number = 1234.5678
var formatResult = numberFormat.format(number); var formatResult = numberFormat.format(number);
...@@ -170,7 +170,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for ...@@ -170,7 +170,7 @@ Use [NumberFormat](../reference/apis/js-apis-intl.md) APIs to format numbers for
3. Obtain attributes of the **NumberFormat** object.<br> 3. Obtain attributes of the **NumberFormat** object.<br>
Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **NumberFormat** object. This method will return an array that contains all attributes and values of the object.
``` ```
var options = numberFormat.resolvedOptions(); var options = numberFormat.resolvedOptions();
``` ```
...@@ -209,7 +209,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ...@@ -209,7 +209,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
2. Compare two strings.<br> 2. Compare two strings.<br>
Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths. Call the **compare** method to compare two input strings. This method returns a value as the comparison result. The return value **-1** indicates that the first string is shorter than the second string, the return value **1** indicates that the first string is longer than the second string, and the return value **0** indicates that the two strings are of equal lengths.
``` ```
var str1 = "first string"; var str1 = "first string";
var str2 = "second string"; var str2 = "second string";
...@@ -218,7 +218,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on ...@@ -218,7 +218,7 @@ Use [Collator](../reference/apis/js-apis-intl.md) APIs to sort strings based on
3. Obtain attributes of the **Collator** object.<br> 3. Obtain attributes of the **Collator** object.<br>
Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object. Call the **resolvedOptions** method to obtain attributes of the **Collator** object. This method will return an array that contains all attributes and values of the object.
``` ```
var options = collator.resolvedOptions(); var options = collator.resolvedOptions();
``` ```
...@@ -256,7 +256,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu ...@@ -256,7 +256,7 @@ Use [PluralRules](../reference/apis/js-apis-intl.md) APIs to determine the singu
2. Determine the singular-plural type.<br> 2. Determine the singular-plural type.<br>
Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**. Call the **select** method to determine the singular-plural type of an input number. This method will return a string representing the singular-plural type, which can be any of the following: **zero**, **one**, **two**, **few**, **many**, and **other**.
``` ```
var number = 1234.5678 var number = 1234.5678
var categoryResult = plurals.select(number); var categoryResult = plurals.select(number);
...@@ -297,7 +297,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -297,7 +297,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
2. Format the relative time.<br> 2. Format the relative time.<br>
Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result. Call the **format** method to format the relative time. This method receives a numeric value representing the time length and a string-form unit, like **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, and **second**. This method returns a string representing the formatting result.
``` ```
var number = 2; var number = 2;
var unit = "year" var unit = "year"
...@@ -306,7 +306,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -306,7 +306,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
3. Obtain each part of the relative time format.<br> 3. Obtain each part of the relative time format.<br>
Upon obtaining each part of the relative time format, customize the relative time formatting result. Upon obtaining each part of the relative time format, customize the relative time formatting result.
``` ```
var number = 2; var number = 2;
var unit = "year" var unit = "year"
...@@ -315,13 +315,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r ...@@ -315,13 +315,7 @@ Use [RelativeTimeFormat](../reference/apis/js-apis-intl.md) APIs to format the r
4. Obtain attributes of the **RelativeTimeFormat** object.<br> 4. Obtain attributes of the **RelativeTimeFormat** object.<br>
Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md). Call the **resolvedOptions** method to obtain attributes of the **RelativeTimeFormat** object. This method will return an array that contains all attributes and values of the object. For a full list of attributes, see [ RelativeTimeFormatResolvedOptions](../reference/apis/js-apis-intl.md).
``` ```
var options = numberFormat.resolvedOptions(); var options = numberFormat.resolvedOptions();
``` ```
## Samples
The following sample is provided to help you better understand how to develop internationalization capabilities:
-[`International`: Internationalization (JS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/UI/International)
...@@ -39,36 +39,36 @@ function printfDescription(obj) { ...@@ -39,36 +39,36 @@ function printfDescription(obj) {
// Set the player callbacks. // Set the player callbacks.
function setCallBack(audioPlayer) { function setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // The play() API can be invoked only after the dataLoad event callback is complete. The play event callback is then triggered. audioPlayer.play(); // The play() API can be invoked only after the 'dataLoad' event callback is complete. The 'play' event callback is then triggered.
}); });
audioPlayer.on('play', () => { // Set the play event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.pause(); // Trigger the pause event callback and pause the playback. audioPlayer.pause(); // Trigger the 'pause' event callback and pause the playback.
}); });
audioPlayer.on('pause', () => { // Set the pause event callback. audioPlayer.on('pause', () => { // Set the 'pause' event callback.
console.info('audio pause success'); console.info('audio pause success');
audioPlayer.seek(5000); // Trigger the timeUpdate event callback, and seek to 5000 ms for playback. audioPlayer.seek(5000); // Trigger the 'timeUpdate' event callback, and seek to 5000 ms for playback.
}); });
audioPlayer.on('stop', () => { // Set the stop event callback. audioPlayer.on('stop', () => { // Set the 'stop' event callback.
console.info('audio stop success'); console.info('audio stop success');
audioPlayer.reset(); // Trigger the reset event callback, and reconfigure the src attribute to switch to the next song. audioPlayer.reset(); // Trigger the 'reset' event callback, and reconfigure the src attribute to switch to the next song.
}); });
audioPlayer.on('reset', () => { // Set the reset event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio reset success'); console.info('audio reset success');
audioPlayer.release(); // Release the AudioPlayer resources. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}); });
audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the timeUpdate event callback. audioPlayer.on('timeUpdate', (seekDoneTime) => {// Set the 'timeUpdate' event callback.
if (typeof(seekDoneTime) == 'undefined') { if (typeof(seekDoneTime) == 'undefined') {
console.info('audio seek fail'); console.info('audio seek fail');
return; return;
} }
console.info('audio seek success, and seek time is ' + seekDoneTime); console.info('audio seek success, and seek time is ' + seekDoneTime);
audioPlayer.setVolume(0.5); // Trigger the volumeChange event callback. audioPlayer.setVolume(0.5); // Trigger the 'volumeChange' event callback.
}); });
audioPlayer.on('volumeChange', () => { // Set the volumeChange event callback. audioPlayer.on('volumeChange', () => { // Set the 'volumeChange' event callback.
console.info('audio volumeChange success'); console.info('audio volumeChange success');
audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode. audioPlayer.getTrackDescription((error, arrlist) => { // Obtain the audio track information in callback mode.
if (typeof (arrlist) != 'undefined') { if (typeof (arrlist) != 'undefined') {
...@@ -78,13 +78,13 @@ function setCallBack(audioPlayer) { ...@@ -78,13 +78,13 @@ function setCallBack(audioPlayer) {
} else { } else {
console.log(`audio getTrackDescription fail, error:${error.message}`); console.log(`audio getTrackDescription fail, error:${error.message}`);
} }
audioPlayer.stop(); // Trigger the stop event callback to stop the playback. audioPlayer.stop(); // Trigger the 'stop' event callback to stop the playback.
}); });
}); });
audioPlayer.on('finish', () => { // Set the finish event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
}); });
audioPlayer.on('error', (error) => { // Set the error event callback. audioPlayer.on('error', (error) => { // Set the 'error' event callback.
console.info(`audio error called, errName is ${error.name}`); console.info(`audio error called, errName is ${error.name}`);
console.info(`audio error called, errCode is ${error.code}`); console.info(`audio error called, errCode is ${error.code}`);
console.info(`audio error called, errMessage is ${error.message}`); console.info(`audio error called, errMessage is ${error.message}`);
...@@ -107,7 +107,7 @@ async function audioPlayerDemo() { ...@@ -107,7 +107,7 @@ async function audioPlayerDemo() {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
``` ```
...@@ -119,16 +119,16 @@ import fileIO from '@ohos.fileio' ...@@ -119,16 +119,16 @@ import fileIO from '@ohos.fileio'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the play event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
}); });
audioPlayer.on('finish', () => { // Set the finish event callback, which is triggered when the playback is complete. audioPlayer.on('finish', () => { // Set the 'finish' event callback, which is triggered when the playback is complete.
console.info('audio play finish'); console.info('audio play finish');
audioPlayer.release(); // Release the AudioPlayer resources. audioPlayer.release(); // Release the AudioPlayer instance.
audioPlayer = undefined; audioPlayer = undefined;
}); });
} }
...@@ -147,7 +147,7 @@ export class AudioDemo { ...@@ -147,7 +147,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
``` ```
...@@ -161,15 +161,15 @@ export class AudioDemo { ...@@ -161,15 +161,15 @@ export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
private isNextMusic = false; private isNextMusic = false;
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Set the play event callback. audioPlayer.on('play', () => { // Set the 'play' event callback.
console.info('audio play success'); console.info('audio play success');
audioPlayer.reset(); // Call the reset() API and trigger the reset event callback. audioPlayer.reset(); // Call the reset() API and trigger the 'reset' event callback.
}); });
audioPlayer.on('reset', () => { // Set the reset event callback. audioPlayer.on('reset', () => { // Set the 'reset' event callback.
console.info('audio play success'); console.info('audio play success');
if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented. if (!this.isNextMusic) { // When isNextMusic is false, changing songs is implemented.
this.nextMusic(audioPlayer); // Changing songs is implemented. this.nextMusic(audioPlayer); // Changing songs is implemented.
...@@ -193,7 +193,7 @@ export class AudioDemo { ...@@ -193,7 +193,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = nextFdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = nextFdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
async audioPlayerDemo() { async audioPlayerDemo() {
...@@ -210,7 +210,7 @@ export class AudioDemo { ...@@ -210,7 +210,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
``` ```
...@@ -223,12 +223,12 @@ import fileIO from '@ohos.fileio' ...@@ -223,12 +223,12 @@ import fileIO from '@ohos.fileio'
export class AudioDemo { export class AudioDemo {
// Set the player callbacks. // Set the player callbacks.
setCallBack(audioPlayer) { setCallBack(audioPlayer) {
audioPlayer.on('dataLoad', () => { // Set the dataLoad event callback, which is triggered when the src attribute is set successfully. audioPlayer.on('dataLoad', () => { // Set the 'dataLoad' event callback, which is triggered when the src attribute is set successfully.
console.info('audio set source success'); console.info('audio set source success');
audioPlayer.loop = true; // Set the loop playback attribute. audioPlayer.loop = true; // Set the loop playback attribute.
audioPlayer.play(); // Call the play() API to start the playback and trigger the play event callback. audioPlayer.play(); // Call the play() API to start the playback and trigger the 'play' event callback.
}); });
audioPlayer.on('play', () => { // Sets the play event callback to start loop playback. audioPlayer.on('play', () => { // Set the 'play' event callback to start loop playback.
console.info('audio play success'); console.info('audio play success');
}); });
} }
...@@ -247,17 +247,7 @@ export class AudioDemo { ...@@ -247,17 +247,7 @@ export class AudioDemo {
}).catch((err) => { }).catch((err) => {
console.info('open fd failed err is' + err); console.info('open fd failed err is' + err);
}); });
audioPlayer.src = fdPath; // Set the src attribute and trigger the dataLoad event callback. audioPlayer.src = fdPath; // Set the src attribute and trigger the 'dataLoad' event callback.
} }
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio playback:
- [`JsDistributedMusicPlayer`: Distributed Music Player (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/ability/JsDistributedMusicPlayer)
- [`JsAudioPlayer`: Audio Playback and Management (JS, API version 7)](https://gitee.com/openharmony/app_samples/tree/master/media/JsAudioPlayer)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -186,12 +186,3 @@ export class AudioRecorderDemo { ...@@ -186,12 +186,3 @@ export class AudioRecorderDemo {
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop audio recording:
- [`Recorder`: Recorder (eTS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/Recorder)
- [`JsRecorder`: Recorder (JS, API version 8)](https://gitee.com/openharmony/app_samples/tree/master/media/JSRecorder)
- [`eTsAudioPlayer`: Audio Player (eTS)](https://gitee.com/openharmony/app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets)
- [Audio Player](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS)
...@@ -15,19 +15,19 @@ For details about the APIs, see [Image Processing](../reference/apis/js-apis-ima ...@@ -15,19 +15,19 @@ For details about the APIs, see [Image Processing](../reference/apis/js-apis-ima
The full process includes creating an instance, reading image information, reading and writing pixel maps, updating data, packaging pixels, and releasing resources. The full process includes creating an instance, reading image information, reading and writing pixel maps, updating data, packaging pixels, and releasing resources.
```js ```js
const Color = new ArrayBuffer(96); // Create a buffer to store image pixel data. const color = new ArrayBuffer(96); // Create a buffer to store image pixel data.
let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data. let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } // Image pixel data.
// Create a PixelMap object. // Create a PixelMap object.
const Color = new ArrayBuffer(96); const color = new ArrayBuffer(96);
let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } }
image.createPixelMap(Color, opts, pixelmap => { image.createPixelMap(color, opts, pixelmap => {
expect(pixelmap !== null).assertTrue(); expect(pixelmap !== null).assertTrue();
console.info('TC_001-1 success'); console.info('TC_001-1 success');
done(); done();
}) })
// Read pixels. // Read pixels.
pixelmap.readPixels(area,(data) => { pixelmap.readPixels(area,(data) => {
if(data !== null) { if(data !== null) {
var bufferArr = new Uint8Array(area.pixels); var bufferArr = new Uint8Array(area.pixels);
var res = true; var res = true;
...@@ -50,39 +50,39 @@ pixelmap.readPixelsToBuffer(readBuffer,() => { ...@@ -50,39 +50,39 @@ pixelmap.readPixelsToBuffer(readBuffer,() => {
var bufferArr = new Uint8Array(readBuffer); var bufferArr = new Uint8Array(readBuffer);
var res = true; var res = true;
for (var i = 0; i < bufferArr.length; i++) { for (var i = 0; i < bufferArr.length; i++) {
if(res) { if(res) {
if (bufferArr[i] !== 0) { if (bufferArr[i] !== 0) {
res = false; res = false;
console.info('TC_020-1 Success'); console.info('TC_020-1 Success');
expect(true).assertTrue(); expect(true).assertTrue();
done(); done();
break; break;
} }
}
} }
}
// Write pixels. // Write pixels.
pixelmap.writePixels(area,() => { pixelmap.writePixels(area,() => {
const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }} const readArea = { pixels: new ArrayBuffer(20), offset: 0, stride: 8, region: { size: { height: 1, width: 2 }, x: 0, y: 0 }}
pixelmap.readPixels(readArea,() => { pixelmap.readPixels(readArea,() => {
var readArr = new Uint8Array(readArea.pixels); var readArr = new Uint8Array(readArea.pixels);
var res = true; var res = true;
for (var i = 0; i < readArr.length; i++) { for (var i = 0; i < readArr.length; i++) {
if(res) { if(res) {
if (readArr[i] !== 0) { if (readArr[i] !== 0) {
res = false; res = false;
console.info('TC_022-1 Success'); console.info('TC_022-1 Success');
expect(true).assertTrue(); expect(true).assertTrue();
done(); done();
break; break;
} }
}
} }
}
// Write pixels to the buffer. // Write pixels to the buffer.
pixelmap.writeBufferToPixels(writeColor).then(() => { pixelmap.writeBufferToPixels(writeColor).then(() => {
const readBuffer = new ArrayBuffer(96); const readBuffer = new ArrayBuffer(96);
pixelmap.readPixelsToBuffer(readBuffer).then (() => { pixelmap.readPixelsToBuffer(readBuffer).then (() => {
var bufferArr = new Uint8Array(readBuffer); var bufferArr = new Uint8Array(readBuffer);
var res = true; var res = true;
for (var i = 0; i < bufferArr.length; i++) { for (var i = 0; i < bufferArr.length; i++) {
...@@ -95,18 +95,18 @@ pixelmap.writePixels(area,() => { ...@@ -95,18 +95,18 @@ pixelmap.writePixels(area,() => {
break; break;
} }
} }
} }
// Obtain image information. // Obtain image information.
pixelmap.getImageInfo( imageInfo => { pixelmap.getImageInfo( imageInfo => {
if (imageInfo !== null) { if (imageInfo !== null) {
console.info('TC_024-1 imageInfo is ready'); console.info('TC_024-1 imageInfo is ready');
expect(imageInfo.size.height == 4).assertTrue(); expect(imageInfo.size.height == 4).assertTrue();
expect(imageInfo.size.width == 6).assertTrue(); expect(imageInfo.size.width == 6).assertTrue();
expect(imageInfo.pixelFormat == 4).assertTrue(); expect(imageInfo.pixelFormat == 4).assertTrue();
done(); done();
} }
}) })
// Release the PixelMap object. // Release the PixelMap object.
pixelmap.release(()=>{ pixelmap.release(()=>{
...@@ -116,7 +116,7 @@ pixelmap.release(()=>{ ...@@ -116,7 +116,7 @@ pixelmap.release(()=>{
}) })
// Create an image source (uri). // Create an image source (uri).
const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.jpg' const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg'
// Create an image source (fd). // Create an image source (fd).
const imageSourceApi = image.createImageSource(29); const imageSourceApi = image.createImageSource(29);
...@@ -136,7 +136,7 @@ imagePackerApi.packing(imageSourceApi, packOpts, data => { ...@@ -136,7 +136,7 @@ imagePackerApi.packing(imageSourceApi, packOpts, data => {
console.info('TC_062-1 finished'); console.info('TC_062-1 finished');
expect(data !== null).assertTrue(); expect(data !== null).assertTrue();
done(); done();
}) })
// Release the ImagePacker object. // Release the ImagePacker object.
imagePackerApi.release(); imagePackerApi.release();
...@@ -148,7 +148,7 @@ imagePackerApi.release(); ...@@ -148,7 +148,7 @@ imagePackerApi.release();
/data/local/tmp/test.jpg // Set the path for creating an image source. /data/local/tmp/test.jpg // Set the path for creating an image source.
// Create an image source using a path. // Create an image source using a path.
const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.jpg' const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg'
// Set parameters. // Set parameters.
let decodingOptions = { let decodingOptions = {
...@@ -171,9 +171,9 @@ imageSourceApi.createPixelMap(decodingOptions, pixelmap => { ...@@ -171,9 +171,9 @@ imageSourceApi.createPixelMap(decodingOptions, pixelmap => {
// Create a pixel map in promise mode. // Create a pixel map in promise mode.
imageSourceApi.createPixelMap().then(pixelmap => { imageSourceApi.createPixelMap().then(pixelmap => {
console.info('TC_050-11 createPixelMap '); console.info('TC_050-11 createPixelMap ');
expect(pixelmap !== null ).assertTrue(); expect(pixelmap !== null ).assertTrue();
done(); done();
}) })
// Capture error information when an exception occurs during function invoking. // Capture error information when an exception occurs during function invoking.
...@@ -181,7 +181,7 @@ catch(error => { ...@@ -181,7 +181,7 @@ catch(error => {
console.log('TC_050-11 error: ' + error); console.log('TC_050-11 error: ' + error);
expect().assertFail(); expect().assertFail();
done(); done();
}) })
// Obtain the number of bytes in each line of pixels. // Obtain the number of bytes in each line of pixels.
pixelmap.getBytesNumberPerRow( num => { pixelmap.getBytesNumberPerRow( num => {
...@@ -192,13 +192,13 @@ pixelmap.getBytesNumberPerRow( num => { ...@@ -192,13 +192,13 @@ pixelmap.getBytesNumberPerRow( num => {
// Obtain the total number of pixel bytes. // Obtain the total number of pixel bytes.
pixelmap.getPixelBytesNumber(num => { pixelmap.getPixelBytesNumber(num => {
console.info('TC_026-1 num is ' + num); console.info('TC_026-1 num is ' + num);
expect(num == expectNum).assertTrue(); expect(num == expectNum).assertTrue();
done(); done();
}) })
// Obtain the pixel map information. // Obtain the pixel map information.
pixelmap.getImageInfo( imageInfo => {}) pixelmap.getImageInfo( imageInfo => {})
// Print the failure information. // Print the failure information.
console.info('TC_024-1 imageInfo is empty'); console.info('TC_024-1 imageInfo is empty');
...@@ -206,17 +206,17 @@ expect(false).assertTrue() ...@@ -206,17 +206,17 @@ expect(false).assertTrue()
// Release the PixelMap object. // Release the PixelMap object.
pixelmap.release(()=>{ pixelmap.release(()=>{
expect(true).assertTrue(); expect(true).assertTrue();
console.log('TC_027-1 suc'); console.log('TC_027-1 suc');
done(); done();
}) })
// Capture release failure information. // Capture release failure information.
catch(error => { catch(error => {
console.log('TC_027-1 error: ' + error); console.log('TC_027-1 error: ' + error);
expect().assertFail(); expect().assertFail();
done(); done();
}) })
``` ```
### Encoding Scenario ### Encoding Scenario
...@@ -225,14 +225,14 @@ catch(error => { ...@@ -225,14 +225,14 @@ catch(error => {
/data/local/tmp/test.png // Set the path for creating an image source. /data/local/tmp/test.png // Set the path for creating an image source.
// Set the image source. // Set the image source.
const imageSourceApi = image.createImageSource(path);//'/data/local/tmp/test.png' const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.png'
// Print the error message if the image source fails to be created. // Print the error message if the image source fails to be created.
if (imageSourceApi == null) { if (imageSourceApi == null) {
console.info('TC_062 create image source failed'); console.info('TC_062 create image source failed');
expect(false).assertTrue(); expect(false).assertTrue();
done(); done();
} }
// Create an image packer if the image source is successfully created. // Create an image packer if the image source is successfully created.
const imagePackerApi = image.createImagePacker(); const imagePackerApi = image.createImagePacker();
...@@ -242,31 +242,58 @@ if (imagePackerApi == null) { ...@@ -242,31 +242,58 @@ if (imagePackerApi == null) {
console.info('TC_062 create image packer failed'); console.info('TC_062 create image packer failed');
expect(false).assertTrue(); expect(false).assertTrue();
done(); done();
} }
// Set encoding parameters if the image packer is successfully created. // Set encoding parameters if the image packer is successfully created.
let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg. let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg.
quality:98 }// Image quality, which ranges from 0 to 100. quality:98 } // Image quality, which ranges from 0 to 100.
// Encode the image. // Encode the image.
imagePackerApi.packing(imageSourceApi, packOpts) imagePackerApi.packing(imageSourceApi, packOpts)
.then( data => { .then( data => {
console.info('TC_062 finished'); console.info('TC_062 finished');
expect(data !== null).assertTrue(); expect(data !== null).assertTrue();
done(); done();
}) })
// Release the image packer after the encoding is complete. // Release the image packer after the encoding is complete.
imagePackerApi.release(); imagePackerApi.release();
// Obtain the image source information. // Obtain the image source information.
imageSourceApi.getImageInfo(imageInfo => { imageSourceApi.getImageInfo(imageInfo => {
console.info('TC_045 imageInfo'); console.info('TC_045 imageInfo');
expect(imageInfo !== null).assertTrue(); expect(imageInfo !== null).assertTrue();
done(); done();
}) })
// Update incremental data. // Update incremental data.
imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {}) imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> {})
``` ```
### Using ImageReceiver
Example scenario: The camera functions as the client to transmit image data to the server.
```js
public async init(surfaceId: any) {
// (Server code) Create an ImageReceiver object.
var receiver = image.createImageReceiver(8 * 1024, 8, image.ImageFormat.JPEG, 1);
// Obtain the surface ID.
var surfaceId = await receiver.getReceivingSurfaceId();
// Register a surface listener, which is triggered after the buffer of the surface is ready.
receiver.on('imageArrival', () => {
// Obtain the latest buffer of the surface.
receiver.readNextImage((err, img) => {
img.getComponent(4, (err, component) => {
// Consume component.byteBuffer. For example, save the content in the buffer as an image.
})
})
})
// Call a Camera API to transfer the surface ID to the camera, which then obtains the surface based on the surface ID and generates a surface buffer.
}
```
...@@ -2,10 +2,7 @@ ...@@ -2,10 +2,7 @@
## When to Use ## When to Use
You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some You can use OpenSL ES to develop the audio recording function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
[OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented yet is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
## How to Develop ## How to Develop
...@@ -27,8 +24,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -27,8 +24,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
(*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
``` ```
3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface. 3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface.
```c++ ```c++
...@@ -36,8 +31,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -36,8 +31,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineItf); result = (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineItf);
``` ```
4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance. 4. Configure the recorder information (including the input source **audiosource** and output source **audiosink**), and create a **pcmCapturerObject** instance.
```c++ ```c++
...@@ -81,21 +74,19 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -81,21 +74,19 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
``` ```
5. Obtain the **recordItf** instance of the **SL_IID_RECORD** interface. 5. Obtain the **recordItf** instance of the **SL_IID_RECORD** interface.
``` ```c++
SLRecordItf recordItf; SLRecordItf recordItf;
(*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf); (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_RECORD, &recordItf);
``` ```
6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. 6. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface.
``` ```c++
SLOHBufferQueueItf bufferQueueItf; SLOHBufferQueueItf bufferQueueItf;
(*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); (*pcmCapturerObject)->GetInterface(pcmCapturerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf);
``` ```
7. Register the **BufferQueueCallback** function. 7. Register the **BufferQueueCallback** function.
```c++ ```c++
...@@ -120,7 +111,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -120,7 +111,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
(*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);
``` ```
8. Start audio recording. 8. Start audio recording.
```c++ ```c++
...@@ -145,7 +135,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform ...@@ -145,7 +135,6 @@ To use OpenSL ES to develop the audio recording function in OpenHarmony, perform
} }
``` ```
9. Stop audio recording. 9. Stop audio recording.
```c++ ```c++
......
# OpenSL ES Audio Playback Development # OpenSL ES Audio Playback Development
## When to Use ## When to Use
You can use OpenSL ES to develop the audio playback function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned. You can use OpenSL ES to develop the audio playback function in OpenHarmony. Currently, only some [OpenSL ES APIs](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h) are implemented. If an API that has not been implemented is called, **SL_RESULT_FEATURE_UNSUPPORTED** will be returned.
## How to Develop ## How to Develop
To use OpenSL ES to develop the audio playback function in OpenHarmony, perform the following steps: To use OpenSL ES to develop the audio playback function in OpenHarmony, perform the following steps:
...@@ -20,8 +16,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -20,8 +16,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
#include <OpenSLES_Platform.h> #include <OpenSLES_Platform.h>
``` ```
2. Use the **slCreateEngine** API to obtain an **engine** instance. 2. Use the **slCreateEngine** API to obtain an **engine** instance.
```c++ ```c++
...@@ -30,8 +24,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -30,8 +24,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE); (*engineObject)->Realize(engineObject, SL_BOOLEAN_FALSE);
``` ```
3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface. 3. Obtain the **engineEngine** instance of the **SL_IID_ENGINE** interface.
```c++ ```c++
...@@ -39,8 +31,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -39,8 +31,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine); (*engineObject)->GetInterface(engineObject, SL_IID_ENGINE, &engineEngine);
``` ```
4. Configure the player and create an **AudioPlayer** instance. 4. Configure the player and create an **AudioPlayer** instance.
```c++ ```c++
...@@ -66,8 +56,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -66,8 +56,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE); (*pcmPlayerObject)->Realize(pcmPlayerObject, SL_BOOLEAN_FALSE);
``` ```
5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface. 5. Obtain the **bufferQueueItf** instance of the **SL_IID_OH_BUFFERQUEUE** interface.
``` ```
...@@ -75,8 +63,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -75,8 +63,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf);
``` ```
6. Open an audio file and register the **BufferQueueCallback** function. 6. Open an audio file and register the **BufferQueueCallback** function.
```c++ ```c++
...@@ -101,8 +87,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -101,8 +87,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_); (*bufferQueueItf)->RegisterCallback(bufferQueueItf, BufferQueueCallback, wavFile_);
``` ```
7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** interface and start playback. 7. Obtain the **playItf** instance of the **SL_PLAYSTATE_PLAYING** interface and start playback.
```c++ ```c++
...@@ -111,8 +95,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform ...@@ -111,8 +95,6 @@ To use OpenSL ES to develop the audio playback function in OpenHarmony, perform
(*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING); (*playItf)->SetPlayState(playItf, SL_PLAYSTATE_PLAYING);
``` ```
8. Stop audio playback. 8. Stop audio playback.
```c++ ```c++
......
...@@ -441,8 +441,3 @@ export class VideoPlayerDemo { ...@@ -441,8 +441,3 @@ export class VideoPlayerDemo {
} }
} }
``` ```
## Samples
The following samples are provided to help you better understand how to develop video playback:
- [`VideoPlayer`: Video Playback (eTS, API version 9)](https://gitee.com/openharmony/app_samples/tree/master/media/VideoPlayer)
...@@ -8,8 +8,6 @@ During video recording, audio and video signals are captured, encoded, and saved ...@@ -8,8 +8,6 @@ During video recording, audio and video signals are captured, encoded, and saved
![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png) ![en-us_image_video_recorder_state_machine](figures/en-us_image_video_recorder_state_machine.png)
**Figure 2** Layer 0 diagram of video recording **Figure 2** Layer 0 diagram of video recording
![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png) ![en-us_image_video_recorder_zero](figures/en-us_image_video_recorder_zero.png)
......
...@@ -200,9 +200,3 @@ The following steps describe how to use the text drawing and display feature of ...@@ -200,9 +200,3 @@ The following steps describe how to use the text drawing and display feature of
double position[2] = {10.0, 15.0}; double position[2] = {10.0, 15.0};
OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]); OH_Drawing_TypographyPaint(typography, cCanvas, position[0], position[1]);
``` ```
## Samples
The following samples are provided to help you better understand how to use the Native Drawing module:
* [2D Graphics Drawing Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/2d_graphics/drawing_c_sample.cpp)
* [Text Drawing and Painting Using Native Drawing](https://gitee.com/openharmony/graphic_graphic_2d/blob/master/rosen/samples/text/renderservice/drawing_text_c_sample.cpp)
# Using Native APIs in Application Projects # Using Native APIs in Application Projects
OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the **arkui_napi** repository are used to implement the interaction with JS. Currently, the **arkui_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository. OpenHarmony applications use JavaScript (JS) when calling native APIs. The native APIs (NAPIs) provided by the [ace_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository are used to implement interaction with JS. Currently, the **ace_napi** repository supports some third-party **Node.js** interfaces. The names of the NAPIs are the same as those in the third-party **Node.js**. For details about the interfaces supported, see `libnapi.ndk.json` in this repository.
## How to Develop ## How to Develop
The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **arkui_napi** repository for development. The IDE has a default project that uses NAPIs. You can choose `File` > `New` > `Create Project` to create a `Native C++` project. The **cpp** directory is generated in the **main** directory. You can use the NAPIs provided by the **ace_napi** repository for development.
You can `import` the native .so that contains the JS processing logic. For example, `import hello from 'libhello.so'` to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the `hello` object of the application to call the native capability. You can `import` the native .so that contains the JS processing logic. For example, `import hello from 'libhello.so'` to use the **libhello.so** capability. Then, the JS object created using the NAPI can be passed to the `hello` object of the application to call the native capability.
...@@ -74,7 +74,7 @@ export default storage; ...@@ -74,7 +74,7 @@ export default storage;
### Implementation ### Implementation
You can obtain the complete code from `sample/native_module_storage/` in the **arkui_napi** repository. You can obtain the complete code from `sample/native_module_storage/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module #### Registering the Module
...@@ -212,7 +212,7 @@ static napi_value JSStorageGet(napi_env env, napi_callback_info info) ...@@ -212,7 +212,7 @@ static napi_value JSStorageGet(napi_env env, napi_callback_info info)
napi_create_async_work( napi_create_async_work(
env, nullptr, resource, env, nullptr, resource,
// Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using theNAPI because the execution is asynchronous. // Callback 1: This callback contains the service logic to be asynchronously executed and is asynchronously executed by the NAPI. Do not operate JS objects using the NAPI because the execution is asynchronous.
[](napi_env env, void* data) { [](napi_env env, void* data) {
StorageAsyncContext* asyncContext = (StorageAsyncContext*)data; StorageAsyncContext* asyncContext = (StorageAsyncContext*)data;
auto itr = gKeyValueStorage.find(asyncContext->key); auto itr = gKeyValueStorage.find(asyncContext->key);
...@@ -307,7 +307,7 @@ export class NetServer { ...@@ -307,7 +307,7 @@ export class NetServer {
### Implementation ### Implementation
You can obtain the complete code from `sample/native_module_netserver/` in the **arkui_napi** repository. You can obtain the complete code from `sample/native_module_netserver/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module #### Registering the Module
...@@ -494,7 +494,7 @@ This example describes how to invoke a JS callback in a non-JS thread. For examp ...@@ -494,7 +494,7 @@ This example describes how to invoke a JS callback in a non-JS thread. For examp
### Implementation ### Implementation
You can obtain the complete code from `sample/native_module_callback/` in the **arkui_napi** repository. You can obtain the complete code from `sample/native_module_callback/` in the [OpenHarmony/arkui_napi](https://gitee.com/openharmony/arkui_napi/tree/master) repository.
#### Registering the Module #### Registering the Module
...@@ -562,7 +562,7 @@ void callbackTest(CallbackContext* context) ...@@ -562,7 +562,7 @@ void callbackTest(CallbackContext* context)
uv_queue_work( uv_queue_work(
loop, loop,
work, work,
// This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, the callback does not need to execute any task. // This callback is executed in another common thread to process tasks asynchronously. After the callback is complete, execute the next callback. In this scenario, this callback does not need to execute any task.
[](uv_work_t* work) {}, [](uv_work_t* work) {},
// This callback is executed in the JS thread bound to env. // This callback is executed in the JS thread bound to env.
[](uv_work_t* work, int status) { [](uv_work_t* work, int status) {
......
...@@ -169,9 +169,3 @@ if (this.subscriber != null) { ...@@ -169,9 +169,3 @@ if (this.subscriber != null) {
}) })
} }
``` ```
## Samples
The following sample is provided to help you better understand how to use the common event functionality:
- [`CommonEvent`: eTS Common Event (API 8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/CommonEvent)
...@@ -256,10 +256,3 @@ function cancelCallback(err) { ...@@ -256,10 +256,3 @@ function cancelCallback(err) {
Notification.cancel(1, "label", cancelCallback) Notification.cancel(1, "label", cancelCallback)
``` ```
## Samples
The following sample is provided to help you better understand how to develop notification functions:
[`Notification`: EtsNotification (API 8)](https://gitee.com/openharmony/app_samples/tree/master/common/Notification)
\ No newline at end of file
# APIs # APIs
- [API Reference Document Description](development-intro.md)
- Ability Framework - Ability Framework
- [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md)
...@@ -13,6 +15,7 @@ ...@@ -13,6 +15,7 @@
- [@ohos.application.appManager](js-apis-appmanager.md) - [@ohos.application.appManager](js-apis-appmanager.md)
- [@ohos.application.Configuration](js-apis-configuration.md) - [@ohos.application.Configuration](js-apis-configuration.md)
- [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md) - [@ohos.application.ConfigurationConstant](js-apis-configurationconstant.md)
- [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md)
- [@ohos.ability.featureAbility](js-apis-featureAbility.md) - [@ohos.ability.featureAbility](js-apis-featureAbility.md)
- [@ohos.application.formBindingData](js-apis-formbindingdata.md) - [@ohos.application.formBindingData](js-apis-formbindingdata.md)
- [@ohos.application.FormExtension](js-apis-formextension.md) - [@ohos.application.FormExtension](js-apis-formextension.md)
...@@ -47,7 +50,7 @@ ...@@ -47,7 +50,7 @@
- application/[ServiceExtensionContext](js-apis-service-extension-context.md) - application/[ServiceExtensionContext](js-apis-service-extension-context.md)
- application/[shellCmdResult](js-apis-application-shellCmdResult.md) - application/[shellCmdResult](js-apis-application-shellCmdResult.md)
- application/[MissionInfo](js-apis-application-missionInfo.md) - application/[MissionInfo](js-apis-application-missionInfo.md)
- Common Event and Notification - Common Event and Notification
- [@ohos.commonEvent](js-apis-commonEvent.md) - [@ohos.commonEvent](js-apis-commonEvent.md)
...@@ -55,7 +58,7 @@ ...@@ -55,7 +58,7 @@
- [@ohos.notification](js-apis-notification.md) - [@ohos.notification](js-apis-notification.md)
- [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md)
- application/[EventHub](js-apis-eventhub.md) - application/[EventHub](js-apis-eventhub.md)
- Bundle Management - Bundle Management
- [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle](js-apis-Bundle.md)
...@@ -70,14 +73,14 @@ ...@@ -70,14 +73,14 @@
- bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md) - bundle/[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)
- bundle/[Metadata](js-apis-bundle-Metadata.md) - bundle/[Metadata](js-apis-bundle-Metadata.md)
- bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md) - bundle/[ModuleInfo](js-apis-bundle-ModuleInfo.md)
- UI Page - UI Page
- [@ohos.animator](js-apis-animator.md) - [@ohos.animator](js-apis-animator.md)
- [@ohos.mediaquery](js-apis-mediaquery.md) - [@ohos.mediaquery](js-apis-mediaquery.md)
- [@ohos.prompt](js-apis-prompt.md) - [@ohos.prompt](js-apis-prompt.md)
- [@ohos.router](js-apis-router.md) - [@ohos.router](js-apis-router.md)
- Graphics - Graphics
- [@ohos.display ](js-apis-display.md) - [@ohos.display ](js-apis-display.md)
...@@ -85,7 +88,7 @@ ...@@ -85,7 +88,7 @@
- [@ohos.window](js-apis-window.md) - [@ohos.window](js-apis-window.md)
- [webgl](js-apis-webgl.md) - [webgl](js-apis-webgl.md)
- [webgl2](js-apis-webgl2.md) - [webgl2](js-apis-webgl2.md)
- Media - Media
- [@ohos.multimedia.audio](js-apis-audio.md) - [@ohos.multimedia.audio](js-apis-audio.md)
...@@ -93,41 +96,45 @@ ...@@ -93,41 +96,45 @@
- [@ohos.multimedia.image](js-apis-image.md) - [@ohos.multimedia.image](js-apis-image.md)
- [@ohos.multimedia.media](js-apis-media.md) - [@ohos.multimedia.media](js-apis-media.md)
- [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md)
- Resource Management - Resource Management
- [@ohos.i18n](js-apis-i18n.md) - [@ohos.i18n](js-apis-i18n.md)
- [@ohos.intl](js-apis-intl.md) - [@ohos.intl](js-apis-intl.md)
- [@ohos.resourceManager](js-apis-resource-manager.md) - [@ohos.resourceManager](js-apis-resource-manager.md)
- Resource Scheduling - Resource Scheduling
- [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md)
- [@ohos.workScheduler ](js-apis-workScheduler.md) - [@ohos.workScheduler ](js-apis-workScheduler.md)
- [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md)
- Custom Management - Custom Management
- [@ohos.configPolicy](js-apis-config-policy.md) - [@ohos.configPolicy](js-apis-config-policy.md)
- [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md) - [@ohos.enterpriseDeviceManager](js-apis-enterprise-device-manager.md)
- [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md)
- Security - Security
- [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md)
- [@ohos.security.huks ](js-apis-huks.md) - [@ohos.security.huks ](js-apis-huks.md)
- [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md)
- [@system.cipher](js-apis-system-cipher.md) - [@system.cipher](js-apis-system-cipher.md)
- Data Management - Data Management
- [@ohos.data.dataAbility ](js-apis-data-ability.md) - [@ohos.data.dataAbility ](js-apis-data-ability.md)
- [@ohos.data.dataShare](js-apis-data-dataShare.md)
- [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.data.distributedData](js-apis-distributed-data.md)
- [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md) - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- [@ohos.data.preferences](js-apis-data-preferences.md) - [@ohos.data.preferences](js-apis-data-preferences.md)
- [@ohos.data.rdb](js-apis-data-rdb.md) - [@ohos.data.rdb](js-apis-data-rdb.md)
- [@ohos.settings](js-apis-settings.md) - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md)
- data/rdb/[resultSet](js-apis-data-resultset.md) - data/rdb/[resultSet](js-apis-data-resultset.md)
- File Management - File Management
- [@ohos.document](js-apis-document.md) - [@ohos.document](js-apis-document.md)
...@@ -138,7 +145,7 @@ ...@@ -138,7 +145,7 @@
- [@ohos.storageStatistics](js-apis-storage-statistics.md) - [@ohos.storageStatistics](js-apis-storage-statistics.md)
- [@ohos.volumeManager](js-apis-volumemanager.md) - [@ohos.volumeManager](js-apis-volumemanager.md)
- [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.securityLabel](js-apis-securityLabel.md)
- Telephony Service - Telephony Service
- [@ohos.contact](js-apis-contact.md) - [@ohos.contact](js-apis-contact.md)
...@@ -148,14 +155,15 @@ ...@@ -148,14 +155,15 @@
- [@ohos.telephony.sim](js-apis-sim.md) - [@ohos.telephony.sim](js-apis-sim.md)
- [@ohos.telephony.sms](js-apis-sms.md) - [@ohos.telephony.sms](js-apis-sms.md)
- [@ohos.telephony.data](js-apis-telephony-data.md) - [@ohos.telephony.data](js-apis-telephony-data.md)
- Network Management - Network Management
- [@ohos.net.connection](js-apis-net-connection.md) - [@ohos.net.connection](js-apis-net-connection.md)
- [@ohos.net.http](js-apis-http.md) - [@ohos.net.http](js-apis-http.md)
- [@ohos.request](js-apis-request.md) - [@ohos.request](js-apis-request.md)
- [@ohos.net.socket](js-apis-socket.md) - [@ohos.net.socket](js-apis-socket.md)
- [@ohos.net.webSocket](js-apis-webSocket.md) - [@ohos.net.webSocket](js-apis-webSocket.md)
- Connectivity - Connectivity
- [@ohos.bluetooth](js-apis-bluetooth.md) - [@ohos.bluetooth](js-apis-bluetooth.md)
...@@ -166,7 +174,7 @@ ...@@ -166,7 +174,7 @@
- [@ohos.rpc](js-apis-rpc.md) - [@ohos.rpc](js-apis-rpc.md)
- [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifi](js-apis-wifi.md)
- [@ohos.wifiext](js-apis-wifiext.md) - [@ohos.wifiext](js-apis-wifiext.md)
- Basic Features - Basic Features
- [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility](js-apis-accessibility.md)
...@@ -185,7 +193,7 @@ ...@@ -185,7 +193,7 @@
- [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTime](js-apis-system-time.md)
- [@ohos.wallpaper](js-apis-wallpaper.md) - [@ohos.wallpaper](js-apis-wallpaper.md)
- [Timer](js-apis-timer.md) - [Timer](js-apis-timer.md)
- Device Management - Device Management
- [@ohos.batteryInfo ](js-apis-battery-info.md) - [@ohos.batteryInfo ](js-apis-battery-info.md)
...@@ -205,18 +213,19 @@ ...@@ -205,18 +213,19 @@
- [@ohos.power](js-apis-power.md) - [@ohos.power](js-apis-power.md)
- [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.runningLock](js-apis-runninglock.md)
- [@ohos.sensor](js-apis-sensor.md) - [@ohos.sensor](js-apis-sensor.md)
- [@ohos.settings](js-apis-settings.md)
- [@ohos.systemParameter](js-apis-system-parameter.md) - [@ohos.systemParameter](js-apis-system-parameter.md)
- [@ohos.thermal](js-apis-thermal.md) - [@ohos.thermal](js-apis-thermal.md)
- [@ohos.update](js-apis-update.md) - [@ohos.update](js-apis-update.md)
- [@ohos.usb](js-apis-usb.md) - [@ohos.usb](js-apis-usb.md)
- [@ohos.vibrator](js-apis-vibrator.md) - [@ohos.vibrator](js-apis-vibrator.md)
- Account Management - Account Management
- [@ohos.account.appAccount](js-apis-appAccount.md) - [@ohos.account.appAccount](js-apis-appAccount.md)
- [@ohos.account.distributedAccount](js-apis-distributed-account.md) - [@ohos.account.distributedAccount](js-apis-distributed-account.md)
- [@ohos.account.osAccount](js-apis-osAccount.md) - [@ohos.account.osAccount](js-apis-osAccount.md)
- Language Base Class Library - Language Base Class Library
- [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.convertxml](js-apis-convertxml.md)
...@@ -240,11 +249,12 @@ ...@@ -240,11 +249,12 @@
- [@ohos.util.Vector](js-apis-vector.md) - [@ohos.util.Vector](js-apis-vector.md)
- [@ohos.worker](js-apis-worker.md) - [@ohos.worker](js-apis-worker.md)
- [@ohos.xml](js-apis-xml.md) - [@ohos.xml](js-apis-xml.md)
- Test - Test
- [@ohos.application.testRunner](js-apis-testRunner.md) - [@ohos.application.testRunner](js-apis-testRunner.md)
- [@ohos.uitest](js-apis-uitest.md) - [@ohos.uitest](js-apis-uitest.md)
- APIs No Longer Maintained - APIs No Longer Maintained
- [@ohos.bytrace](js-apis-bytrace.md) - [@ohos.bytrace](js-apis-bytrace.md)
......
# API Reference Document Description
API references provide the description of APIs used for application development. This topic describes common fields in the API references to help you better use the reference document.
## Version Description
In API references, the earliest versions of APIs and components are specified in the following ways:
- For a new API or component, the version information is provided at the beginning of the reference document. Example: "The initial APIs of this module are supported since API version 7."
- For a new feature of an existing API or component, a superscript is added following the feature. For example, "uid<sup>8+</sup>" indicates that the **uid** attribute is supported since API version 8.
## Ability Framework Model Description
Ability is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. Ability framework models are classified into the FA model and stage model. For details, see [Ability Framework Overview](../../ability/ability-brief.md).
- If all the APIs of a module support only one model, the following description is provided at the beginning of the reference document: "The APIs of this module can be used only in the FA model." or "The APIs of this module can be used only in the stage model."
- If certain APIs of a module support only one model, the following description is provided individually for these APIs: "This API can be used only in the FA model." or "This API can be used only in the stage model."
- If both models are supported, no special description is provided.
## Available APIs
Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by non-system applications.
A description regarding system APIs will be provided in the document.
- If all the APIs of a module are system APIs, the following description is provided at the beginning of the reference document: "All the APIs of this module are system APIs."
- If a specific API of a module is a system API, the following description is provided individually for the API: "This is a system API."
## Permission Description
By default, applications can access limited system resources. However, in some cases, an application needs to access excess data (including personal data) and functions of the system or another application to implement extended functions. For details, see [Access Control Overview](../../security/accesstoken-overview.md).
To call APIs to access these resources, you must apply for the corresponding permissions by following the instructions provided in [Access Control Development](../../security/accesstoken-guidelines.md).
- If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx"
- If an application can call an API without any permission, no special description is provided.
To determine whether an application can apply for a specific permission, see [Permission List](../../security/permission-list.md).
## System Capability Description
System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SysCap](../../quick-start/syscap.md).
The following description is provided for each API in the reference document to describe the system capability of the API: "**System capability**: SystemCapability.xxx.xxx"
## Sample Code Language Description
OpenHarmony supports two development languages: JS and TS.
- When a code block is labeled with `js`, the sample code can be used in the JS and eTS projects.
- When a code block is labeled with `ts`, the sample code can be used only in the eTS project.
# AbilityManager
The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information.
> **NOTE**
>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module are system APIs and cannot be called by third-party applications.
# Modules to Import
```js
import AbilityManager from '@ohos.application.abilityManager'
```
## AbilityState
Enumerates the ability states.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
| Name| Value| Description|
| -------- | -------- | -------- |
| INITIAL | 0 | The ability is in the initial state.|
| FOREGROUND | 9 | The ability is in the foreground state. |
| BACKGROUND | 10 | The ability is in the background state. |
| FOREGROUNDING | 11 | The ability is in the foregrounding state. |
| BACKGROUNDING | 12 | The ability is in the backgrounding state. |
## updateConfiguration
updateConfiguration(config: Configuration, callback: AsyncCallback\<void>): void
Obtains the ability running information. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | Configuration | Yes | New configuration.|
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var config = {
language: 'chinese'
}
abilitymanager.updateConfiguration(config, () => {
console.log('------------ updateConfiguration -----------');
})
```
## updateConfiguration
updateConfiguration(config: Configuration): Promise\<void>
Updates the configuration. This API uses a promise to return the result.
**Permission required**: ohos.permission.UPDATE_CONFIGURATION
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| config | Configuration | Yes | New configuration.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<void> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var config = {
language: 'chinese'
}
abilitymanager.updateConfiguration(config).then(() => {
console.log('updateConfiguration success');
}).catch((err) => {
console.log('updateConfiguration fail');
})
```
## getAbilityRunningInfos
getAbilityRunningInfos(callback: AsyncCallback\<Array\<AbilityRunningInfo>>): void
Obtains the ability running information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<Array\<AbilityRunningInfo>> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos((err,data) => {
console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
## getAbilityRunningInfos
getAbilityRunningInfos(): Promise\<Array\<AbilityRunningInfo>>
Obtains the ability running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<AbilityRunningInfo>> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getAbilityRunningInfos().then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data))
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err)
});
```
## getExtensionRunningInfos<sup>9+</sup>
getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\<Array\<ExtensionRunningInfo>>): void
Obtains the extension running information. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
| callback | AsyncCallback\<Array\<AbilityRunningInfo>> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var upperLimit = 0;
abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => {
console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data));
});
```
## getExtensionRunningInfos<sup>9+</sup>
getExtensionRunningInfos(upperLimit: number): Promise\<Array\<ExtensionRunningInfo>>
Obtains the extension running information. This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_RUNNING_INFO
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| upperLimit | number | Yes| Maximum number of messages that can be obtained.|
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<Array\<AbilityRunningInfo>> | Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
var upperLimit = 0;
abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => {
console.log("getAbilityRunningInfos data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getAbilityRunningInfos err: " + err);
})
```
## getTopAbility<sup>9+</sup>
getTopAbility(callback: AsyncCallback\<ElementName>): void;
Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------- | ---------------------------------------- | ---- | -------------- |
| callback | AsyncCallback\<ElementName> | Yes | Callback used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getTopAbility((err,data) => {
console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data));
});
```
## getTopAbility<sup>9+</sup>
getTopAbility(): Promise\<ElementName>;
Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core
**Return value**
| Type | Description |
| ---------------------------------------- | ------- |
| Promise\<ElementName>| Promise used to return the result. |
**Example**
```js
import abilitymanager from '@ohos.application.abilityManager';
abilitymanager.getTopAbility().then((data) => {
console.log("getTopAbility data: " + JSON.stringify(data));
}).catch((err) => {
console.log("getTopAbility err: " + err);
})
```
# Animator # Animator
> **NOTE**<br> > **NOTE**
>
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
...@@ -22,7 +23,7 @@ Creates an **Animator** object. ...@@ -22,7 +23,7 @@ Creates an **Animator** object.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options. For details, see **AnimatorOptions**.| | options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -213,6 +214,8 @@ animator.oncancel(); ...@@ -213,6 +214,8 @@ animator.oncancel();
onrepeat: () => void onrepeat: () => void
Called when this animation repeats.
**System capability**: SystemCapability.ArkUI.ArkUI.Full **System capability**: SystemCapability.ArkUI.ArkUI.Full
**Example** **Example**
...@@ -220,8 +223,6 @@ onrepeat: () => void ...@@ -220,8 +223,6 @@ onrepeat: () => void
animator.onrepeat(); animator.onrepeat();
``` ```
Called when this animation repeats.
## AnimatorOptions ## AnimatorOptions
Defines animator options. Defines animator options.
...@@ -231,7 +232,7 @@ Defines animator options. ...@@ -231,7 +232,7 @@ Defines animator options.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.| | duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.|
| easing | string | Yes| Animation interpolation curve. The default value is **ease**.| | easing | string | Yes| Animation interpolation curve. The default value is **'ease'**.|
| delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.| | delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.|
| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed. | | fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed. |
| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.| | direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.|
......
...@@ -21,7 +21,7 @@ Creates an **AppAccountManager** instance. ...@@ -21,7 +21,7 @@ Creates an **AppAccountManager** instance.
**System capability**: SystemCapability.Account.AppAccount **System capability**: SystemCapability.Account.AppAccount
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ----------------- | ------------ | | ----------------- | ------------ |
...@@ -102,7 +102,7 @@ Adds an app account name and additional information (information that can be con ...@@ -102,7 +102,7 @@ Adds an app account name and additional information (information that can be con
| name | string | Yes | Name of the app account to add. | | name | string | Yes | Name of the app account to add. |
| extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| | extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| ------------------- | --------------------- | | ------------------- | --------------------- |
...@@ -198,7 +198,7 @@ Deletes an app account from the **AppAccountManager** service. This API uses a p ...@@ -198,7 +198,7 @@ Deletes an app account from the **AppAccountManager** service. This API uses a p
| ---- | ------ | ---- | ----------- | | ---- | ------ | ---- | ----------- |
| name | string | Yes | Name of the app account to delete.| | name | string | Yes | Name of the app account to delete.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -255,7 +255,7 @@ Disables an app account from accessing an app with the given bundle name. This A ...@@ -255,7 +255,7 @@ Disables an app account from accessing an app with the given bundle name. This A
| name | string | Yes | Name of the target app account.| | name | string | Yes | Name of the target app account.|
| bundleName | string | Yes | Bundle name of the app. | | bundleName | string | Yes | Bundle name of the app. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -312,7 +312,7 @@ Enables an app account to access an app with the given bundle name. This API use ...@@ -312,7 +312,7 @@ Enables an app account to access an app with the given bundle name. This API use
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| bundleName | string | Yes | Bundle name of the app.| | bundleName | string | Yes | Bundle name of the app.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -371,7 +371,7 @@ Checks whether an app account allows app data synchronization. This API uses a p ...@@ -371,7 +371,7 @@ Checks whether an app account allows app data synchronization. This API uses a p
| ---- | ------ | ---- | ------- | | ---- | ------ | ---- | ------- |
| name | string | Yes | Name of the target app account.| | name | string | Yes | Name of the target app account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :--------------------- | :-------------------- | | :--------------------- | :-------------------- |
...@@ -430,7 +430,7 @@ Sets a credential for an app account. This API uses a promise to return the resu ...@@ -430,7 +430,7 @@ Sets a credential for an app account. This API uses a promise to return the resu
| credentialType | string | Yes | Type of the credential to set.| | credentialType | string | Yes | Type of the credential to set.|
| credential | string | Yes | Credential to set. | | credential | string | Yes | Credential to set. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -487,7 +487,7 @@ Sets additional information for an app account. This API uses a promise to retur ...@@ -487,7 +487,7 @@ Sets additional information for an app account. This API uses a promise to retur
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| extraInfo | string | Yes | Additional information to set.| | extraInfo | string | Yes | Additional information to set.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -548,7 +548,7 @@ Sets whether to enable app data synchronization for an app account. This API use ...@@ -548,7 +548,7 @@ Sets whether to enable app data synchronization for an app account. This API use
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| isEnable | boolean | Yes | Whether to enable app data synchronization.| | isEnable | boolean | Yes | Whether to enable app data synchronization.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -606,7 +606,7 @@ Sets data to be associated with an app account. This API uses a promise to retur ...@@ -606,7 +606,7 @@ Sets data to be associated with an app account. This API uses a promise to retur
| key | string | Yes | Key of the data to set. The private key can be customized.| | key | string | Yes | Key of the data to set. The private key can be customized.|
| value | string | Yes | Value of the data to be set. | | value | string | Yes | Value of the data to be set. |
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :------------------ | :-------------------- | | :------------------ | :-------------------- |
...@@ -664,7 +664,7 @@ Obtains the credential of an app account. This API uses a promise to return the ...@@ -664,7 +664,7 @@ Obtains the credential of an app account. This API uses a promise to return the
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| credentialType | string | Yes | Type of the credential to obtain.| | credentialType | string | Yes | Type of the credential to obtain.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
...@@ -720,7 +720,7 @@ Obtains additional information of an app account. This API uses a promise to ret ...@@ -720,7 +720,7 @@ Obtains additional information of an app account. This API uses a promise to ret
| ---- | ------ | ---- | ------- | | ---- | ------ | ---- | ------- |
| name | string | Yes | Name of the target app account.| | name | string | Yes | Name of the target app account.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
...@@ -778,7 +778,7 @@ Obtains data associated with an app account. This API uses a promise to return t ...@@ -778,7 +778,7 @@ Obtains data associated with an app account. This API uses a promise to return t
| name | string | Yes | Name of the target app account. | | name | string | Yes | Name of the target app account. |
| key | string | Yes | Key of the data to obtain.| | key | string | Yes | Key of the data to obtain.|
**Return Value** **Return value**
| Type | Description | | Type | Description |
| :-------------------- | :-------------------- | | :-------------------- | :-------------------- |
......
# Data Share Extension Ability
**DataShareExtensionAbility** provides extension abilities for data share services based on the ExtensionAbility framework.
>**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 provided by this module are system APIs.
>
>The APIs of this module can be used only in the stage model.
## Modules to Import
```ts
import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility'
```
## onCreate
onCreate?(want: Want, callback: AsyncCallback&lt;void&gt;): void
Called to initialize service logic of the server when the DataShare client connects to the DataShareExtensionAbility server. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| want | [Want](js-apis-application-Want.md#want) | Yes | **Want** information, including the ability name and bundle name.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback that returns no value.|
**Example**
```ts
import rdb from '@ohos.data.rdb';
let DB_NAME = "DB00.db";
let TBL_NAME = "TBL00";
let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS "
+ TBL_NAME
+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)";
let rdbStore;
export default class DataShareExtAbility extends DataShareExtensionAbility {
onCreate(want: Want, callback: AsyncCallback<void>) {
rdb.getRdbStore(this.context, {
name: DB_NAME
}, 1, function (err, data) {
console.log('getRdbStore done, data : ' + data);
rdbStore = data;
rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) {
console.log('executeSql done, error message : ' + err);
});
if (callback) {
callback();
}
});
}
};
```
## getFileTypes
getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;): void
Called by the server to obtain the Multipurpose Internet Mail Extensions (MIME) types supported by a file. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------------- | ---------------------------------------- | ---- | ---------------------------------- |
| uri | string | Yes | URI of the file. |
| mimeTypeFilter | string | Yes | MIME types to match. |
| callback | AsyncCallback&lt;Array&lt;string&gt;&gt; | Yes | Callback invoked to return the MIME types obtained.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback<Array<string>>) {
let err = {"code":0};
let ret = new Array("type01", "type02", "type03");
callback(err, ret);
}
};
```
## openFile
openFile?(uri: string, mode: string, callback: AsyncCallback&lt;number&gt;): void
Called by the server to open a file. This method can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------------------------------ |
| uri | string | Yes | URI of the file to open. |
| mode | string | Yes | File open mode, including read-only mode and read/write mode.|
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the file descriptor. |
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
openFile(uri: string, mode: string, callback: AsyncCallback<number>) {
let err = {"code":0};
let fd = 0;
callback(err,fd);
}
};
```
## insert
insert?(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void
Called to insert data into the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri |string | Yes | URI of the data to insert.|
| valueBucket |[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| Data to insert.|
| callback |AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the index of the data inserted.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
insert(uri: string, valueBucket: ValuesBucket, callback: AsyncCallback<number>) {
if (value == null) {
console.info('invalid valueBuckets');
return;
}
rdbStore.insert(TBL_NAME, value, function (err, ret) {
console.info('callback ret:' + ret);
if (callback != undefined) {
callback(err, ret);
}
});
}
};
```
## update
update?(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback&lt;number&gt;): void
Called by the server to update data in the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the data to update.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.|
| valueBucket | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| New data.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of updated data records.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
update(uri: string, predicates: dataSharePredicates.DataSharePredicates, valueBucket: ValuesBucket, callback: AsyncCallback<number>) {
if (predicates == null || predicates == undefined) {
return;
}
rdbStore.update(TBL_NAME, value, predicates, function (err, ret) {
if (callback != undefined) {
callback(err, ret);
}
});
}
};
```
## delete
delete?(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void
Called by the server to delete data from the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------------------------------------------------------------ | ---- | ---------------------------------- |
| uri | string | Yes | URI of the data to delete. |
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of data records deleted.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
delete(uri: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>) {
if (predicates == null || predicates == undefined) {
return;
}
rdbStore.delete(TBL_NAME, predicates, function (err, ret) {
if (callback != undefined) {
callback(err, ret);
}
});
}
};
```
## query
query?(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void
Called by the server to query data from the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the data to query.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.|
| columns | Array&lt;string&gt; | Yes| Columns to query. If this parameter is empty, all columns will be queried.|
| callback | AsyncCallback&lt;Object&gt; | Yes| Callback invoked to return the result set.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
query(uri: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<Object>) {
if (predicates == null || predicates == undefined) {
return;
}
rdbStore.query(TBL_NAME, predicates, columns, function (err, resultSet) {
if (resultSet != undefined) {
console.info('resultSet.rowCount: ' + resultSet.rowCount);
}
if (callback != undefined) {
callback(err, resultSet);
}
});
}
};
```
## getType
getType?(uri: string, callback: AsyncCallback&lt;string&gt;): void
Called by the server to obtain the MIME type corresponding to the given URI. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ------ | ------ | ------ |
| uri | string | Yes | URI of the target data.|
| callback | AsyncCallback&lt;string&gt; | Yes| Callback invoked to return the MIME type obtained.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
getType(uri: string, callback: AsyncCallback<string>) {
let err = {"code":0};
let ret = "image";
callback(err, ret);
}
};
```
## BatchInsert
BatchInsert?(uri: string, valueBuckets: Array&lt;ValuesBucket&gt;, callback: AsyncCallback&lt;number&gt;): void
Called by the server to insert batch data into the database. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| ------------ | ------------------------------------------------------------ | ---- | -------------------------------- |
| uri | string | Yes | URI of the data to insert. |
| valueBuckets | Array&lt;[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)&gt; | Yes | Data to insert. |
| callback | AsyncCallback&lt;number&gt; | Yes | Callback invoked to return the number of inserted data records.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
batchInsert(uri: string, valueBuckets: Array<ValuesBucket>, callback: AsyncCallback<number>) {
if (valueBuckets == null || valueBuckets.length == undefined) {
console.info('invalid valueBuckets');
return;
}
let resultNum = valueBuckets.length
valueBuckets.forEach(vb => {
rdbStore.insert(TBL_NAME, vb, function (err, ret) {
if (callback != undefined) {
callback(err, resultNum);
}
});
});
}
};
```
## normalizeUri
normalizeUri?(uri: string, callback: AsyncCallback&lt;string&gt;): void
Called by the server to normalize the specified URI. This API can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ----------------------- |
| uri | string | Yes | [URI](js-apis-uri.md#uri) to normalize.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. If the operation is successful, the normalized URI is returned. Otherwise, **null** is returned.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
normalizeUri(uri: string, callback: AsyncCallback<string>) {
let err = {"code":0};
let ret = "normalize+" + uri;
callback(err, ret);
}
};
```
## denormalizeUri
denormalizeUri?(uri: string, callback: AsyncCallback&lt;string&gt;): void
Called by the server to denormalize the specified URI. This method can be overridden as required.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ----------------------- |
| uri | string | Yes | [URI](js-apis-uri.md#uri) to denormalize.|
| callback | AsyncCallback&lt;string&gt; | Yes | Callback used to return the result. If the operation is successful, the URI obtained is returned. If the URI passed in is returned, denormalization is not required. If denormalization is not supported, **null** is returned.|
**Example**
```ts
export default class DataShareExtAbility extends DataShareExtensionAbility {
denormalizeUri(uri: string, callback: AsyncCallback<string>) {
let err = {"code":0};
let ret = "denormalize+" + uri;
callback(err, ret);
}
};
```
# MissionInfo
> **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.
## Modules to Import
```js
import MissionInfo from '@ohos.application.missionInfo'
```
## MissionInfo
Provides the mission information.
**System capability**: SystemCapability.Ability.AbilityBase
| Name| Type| Readable| Writable| Description|
| -------- | -------- | -------- | -------- | -------- |
| missionId | number | Yes| Yes| Mission ID.|
| runningState | number | Yes| Yes| Running state of the mission.|
| lockedState | boolean | Yes| Yes| Locked state of the mission.|
| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.|
| want | [Want](js-apis-application-Want.md) | Yes| Yes| **Want** information of the mission.|
| label | string | Yes| Yes| Label of the mission.|
| iconPath | string | Yes| Yes| Path of the mission icon.|
| continuable | boolean | Yes| Yes| Whether the mission is continuable.|
...@@ -2273,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result. ...@@ -2273,7 +2273,43 @@ Writes the buffer. This API uses an asynchronous callback to return the result.
``` ```
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
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
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data)=> {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize;
audioRenderer.getBufferSize().then((data)=> {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info.('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
});
console.info('Buffer size:'+bufferSize);
var context = featureAbility.getContext();
var path = await context.getCacheDir();
var filePath = path+"/StarWars10s-2C-48000-4SW.wav"
let ss = fileio.createStreamSync(filePath, 'r'); let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
ss.readSync(buf); ss.readSync(buf);
...@@ -2305,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result. ...@@ -2305,7 +2341,42 @@ Writes the buffer. This API uses a promise to return the result.
``` ```
import audio from '@ohos.multimedia.audio'; import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio'; import fileio from '@ohos.fileio';
import featureAbility from '@ohos.ability.featureAbility'
var audioStreamInfo = {
samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels:audio.AudioChannel.CHANNEL_2,
sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
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
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize;
audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
});
console.info('BufferSize: ' + bufferSize);
var context = featureAbility.getContext();
var path = await context.getCacheDir();
var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; var filePath = 'data/StarWars10s-2C-48000-4SW.wav';
let ss = fileio.createStreamSync(filePath, 'r'); let ss = fileio.createStreamSync(filePath, 'r');
let buf = new ArrayBuffer(bufferSize); let buf = new ArrayBuffer(bufferSize);
...@@ -2408,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a ...@@ -2408,12 +2479,39 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a
**Example** **Example**
``` ```
import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
var audioStreamInfo = {
samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000,
channels:audio.AudioChannel.CHANNEL_2,
sampleFormat.audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE,
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
}
var audioRenderer;
audio.createAudioRenderer(audioRendererOptions).then((data) => {
audioRenderer = data;
console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRenderLog: AudioRenderer Created: ERROR: '+err.message);
});
var bufferSize; var bufferSize;
await audioRenderer.getBufferSize().then(async function (data) => { audioRenderer.getBufferSize().then((data) => {
console.info('AudioFrameworkRenderLog: getBufferSize :SUCCESS '+data); console.info('AudioFrameworkRenderLog: getBufferSize: SUCCESS '+data);
bufferSize=data; bufferSize=data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRenderLog: getBufferSize :ERROR : '+err.message); console.info('AudioFrameworkRenderLog: getBufferSize: ERROR: '+err.message);
}); });
``` ```
...@@ -2542,7 +2640,8 @@ Sets the audio interruption mode for the application. This API uses a promise to ...@@ -2542,7 +2640,8 @@ Sets the audio interruption mode for the application. This API uses a promise to
**Example** **Example**
``` ```
audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE).then(() => { const audioManager = audio.getAudioManager();
audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE).then(() => {
console.log('Promise returned to indicate a successful volume setting.'); console.log('Promise returned to indicate a successful volume setting.');
}); });
``` ```
...@@ -2564,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t ...@@ -2564,7 +2663,8 @@ Sets the audio interruption mode for the application. This API uses a callback t
**Example** **Example**
``` ```
audioManager.setInterruptMode(audio.InterruptType.SHARE_MODE,()=>{ const audioManager = audio.getAudioManager();
audioManager.setInterruptMode(audio.InterruptMode.SHARE_MODE,()=>{
console.log('Callback returned to indicate a successful volume setting.'); console.log('Callback returned to indicate a successful volume setting.');
}); });
``` ```
...@@ -2654,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th ...@@ -2654,7 +2754,7 @@ Subscribes to mark reached events. When the number of frames rendered reaches th
``` ```
audioRenderer.on('markReach', 1000, (position) => { audioRenderer.on('markReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -2701,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches ...@@ -2701,7 +2801,7 @@ Subscribes to period reached events. When the period of frame rendering reaches
``` ```
audioRenderer.on('periodReach', 1000, (position) => { audioRenderer.on('periodReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -2935,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result. ...@@ -2935,13 +3035,35 @@ Starts capturing. This API uses a promise to return the result.
**Example** **Example**
``` ```
import audio from '@ohos.multimedia.audio';
import fileio from '@ohos.fileio';
var audioStreamInfo = {
samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100,
channels: audio.AudioChannel.CHANNEL_2,
sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE,
encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW
}
var audioCapturerInfo = {
source: audio.SourceType.SOURCE_TYPE_MIC,
capturerFlags = 1
}
var audioCapturer;
audio.createAudioCapturer(audioCapturerOptions).then((data) => {
audioCapturer = data;
console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS');
}).catch((err) => {
console.info('AudioFrameworkRecLog: AudioCapturer Created: ERROR: '+err.message);
});
audioCapturer.start().then(() => { audioCapturer.start().then(() => {
console.info('AudioFrameworkRecLog: ---------START---------'); console.info('AudioFrameworkRecLog: ---------START---------');
console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); console.info('AudioFrameworkRecLog: AudioCapturer: STATE: '+audioCapturer.state);
console.info('AudioFrameworkRecLog: Capturer started :SUCCESS '); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS ');
if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) {
stateFlag = true; console.info('AudioFrameworkRecLog: AudioCapturer is in Running State');
} }
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer start :ERROR : '+err.message);
...@@ -2994,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result. ...@@ -2994,15 +3116,13 @@ Stops capturing. This API uses a promise to return the result.
``` ```
audioCapturer.stop().then(() => { audioCapturer.stop().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: ---------STOP RECORD---------');
console.info('AudioFrameworkRecLog: Capturer stopped : SUCCESS'); console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS');
if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){
stateFlag=true; console.info('AudioFrameworkRecLog: State is Stopped': ');
console.info('AudioFrameworkRecLog: resultFlag : '+stateFlag);
} }
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
stateFlag=false;
}); });
``` ```
...@@ -3054,11 +3174,9 @@ audioCapturer.release().then(() => { ...@@ -3054,11 +3174,9 @@ audioCapturer.release().then(() => {
console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------');
console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); console.info('AudioFrameworkRecLog: Capturer release : SUCCESS');
console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state); console.info('AudioFrameworkRecLog: AudioCapturer : STATE : '+audioCapturer.state);
stateFlag=true;
console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag); console.info('AudioFrameworkRecLog: stateFlag : '+stateFlag);
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecLog: Capturer stop:ERROR : '+err.message); console.info('AudioFrameworkRecLog: Capturer stop: ERROR: '+err.message);
stateFlag=false
}); });
``` ```
...@@ -3082,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result. ...@@ -3082,6 +3200,13 @@ Reads the buffer. This API uses an asynchronous callback to return the result.
**Example** **Example**
``` ```
var bufferSize;
audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize: EROOR: '+err.message);
});
audioCapturer.read(bufferSize, true, async(err, buffer) => { audioCapturer.read(bufferSize, true, async(err, buffer) => {
if (!err) { if (!err) {
console.log("Success in reading the buffer data"); console.log("Success in reading the buffer data");
...@@ -3114,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result. ...@@ -3114,6 +3239,14 @@ Reads the buffer. This API uses a promise to return the result.
**Example** **Example**
``` ```
var bufferSize;
audioCapturer.getBufferSize().then((data) => {
console.info('AudioFrameworkRecLog: getBufferSize: SUCCESS '+data);
bufferSize = data;
}).catch((err) => {
console.info('AudioFrameworkRecLog: getBufferSize: ERROR '+err.message);
});
console.info('Buffer size: ' + bufferSize);
audioCapturer.read(bufferSize, true).then((buffer) => { audioCapturer.read(bufferSize, true).then((buffer) => {
console.info('buffer read successfully'); console.info('buffer read successfully');
}).catch((err) => { }).catch((err) => {
...@@ -3217,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a ...@@ -3217,12 +3350,12 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a
**Example** **Example**
``` ```
await audioCapturer.getBufferSize().then(async function (bufferSize) { var bufferSize;
console.info('AudioFrameworkRecordLog: getBufferSize :SUCCESS '+ bufferSize); audioCapturer.getBufferSize().then((data) => {
var buffer = await audioCapturer.read(bufferSize, true); console.info('AudioFrameworkRecLog: getBufferSize :SUCCESS '+ data);
console.info('Buffer read is ' + buffer ); bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.info('AudioFrameworkRecordLog: getBufferSize :ERROR : '+err.message); console.info('AudioFrameworkRecLog: getBufferSize :ERROR : '+ err.message);
}); });
``` ```
...@@ -3247,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th ...@@ -3247,7 +3380,7 @@ Subscribes to mark reached events. When the number of frames captured reaches th
``` ```
audioCapturer.on('markReach', 1000, (position) => { audioCapturer.on('markReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
...@@ -3293,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th ...@@ -3293,7 +3426,7 @@ Subscribes to mark reached events. When the period of frame capturing reaches th
``` ```
audioCapturer.on('periodReach', 1000, (position) => { audioCapturer.on('periodReach', 1000, (position) => {
if (position == "1000") { if (position == 1000) {
console.log('ON Triggered successfully'); console.log('ON Triggered successfully');
} }
}); });
......
...@@ -201,7 +201,7 @@ Obtains the connection state of a profile. ...@@ -201,7 +201,7 @@ Obtains the connection state of a profile.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| --------- | --------- | ---- | ------------------------------------- | | --------- | --------- | ---- | ------------------------------------- |
| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| | ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.|
**Return value** **Return value**
...@@ -447,7 +447,7 @@ Sets the device pairing confirmation. ...@@ -447,7 +447,7 @@ Sets the device pairing confirmation.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------- | ---- | -------------------------------- | | ------ | ------- | ---- | -------------------------------- |
| device | string | Yes | Address of the remote device, for example, XX:XX:XX:XX:XX:XX.| | device | string | Yes | Address of the target remote device, for example, XX:XX:XX:XX:XX:XX.|
| accept | boolean | Yes | Whether to accept the pairing request. The value **true** means to accept the pairing request, and the value **false** means the opposite. | | accept | boolean | Yes | Whether to accept the pairing request. The value **true** means to accept the pairing request, and the value **false** means the opposite. |
**Return value** **Return value**
...@@ -1039,9 +1039,9 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); ...@@ -1039,9 +1039,9 @@ let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE);
## bluetooth.getProfile<sup>9+</sup><a name="getProfile"></a> ## bluetooth.getProfile<sup>9+</sup><a name="getProfile"></a>
getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile getProfile(profileId: ProfileId): A2dpSourceProfile | HandsFreeAudioGatewayProfile | HidHostProfile | PanProfile
Obtains a profile instance. **HidHostProfile** is added in API version 9. Obtains a profile instance. API version 9 is added with **HidHostProfile** and **PanProfile**.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
...@@ -1055,7 +1055,7 @@ Obtains a profile instance. **HidHostProfile** is added in API version 9. ...@@ -1055,7 +1055,7 @@ Obtains a profile instance. **HidHostProfile** is added in API version 9.
| Type | Description | | Type | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------------------------------------------------------ | ------------------------------------------------------------ |
| [A2dpSourceProfile](#A2dpSourceProfile), [HandsFreeAudioGatewayProfile](#HandsFreeAudioGatewayProfile), or [HidHostProfile](#HidHostProfile) | Profile object obtained. **A2dpSourceProfile**, **HandsFreeAudioGatewayProfile**, and **HidHostProfile** are supported.| | [A2dpSourceProfile](#A2dpSourceProfile), [HandsFreeAudioGatewayProfile](#HandsFreeAudioGatewayProfile), [HidHostProfile](#HidHostProfile), or [PanProfile](#PanProfile)| Profile instance obtained, which can be **A2dpSourceProfile**, **HandsFreeAudioGatewayProfile**, **HidHostProfile**, or **PanProfile**.|
**Example** **Example**
...@@ -1344,7 +1344,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. ...@@ -1344,7 +1344,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device to connect.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1374,7 +1374,7 @@ Disconnects an A2DP connection. ...@@ -1374,7 +1374,7 @@ Disconnects an A2DP connection.
| Name | Type | Mandatory | Description | | Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- | | ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the remote device to disconnect.| | device | string | Yes | Address of the target device.|
**Return value** **Return value**
...@@ -1737,6 +1737,162 @@ hidHost.off('connectionStateChange', onReceiveEvent); ...@@ -1737,6 +1737,162 @@ hidHost.off('connectionStateChange', onReceiveEvent);
``` ```
## PanProfile
Before using a method of **PanProfile**, you need to create an instance of this class by using the **getProfile()** method.
### disconnect<sup>9+</sup><a name="disconnect"></a>
disconnect(device: string): boolean
Disconnects from the Personal Area Network (PAN) service of a device.
This is a system API.
**Required permissions**: ohos.permission.USE_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| device | string | Yes | Address of the target device.|
**Return value**
| Type | Description |
| --------------------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX');
```
### on('connectionStateChange')<sup>9+</sup>
on(type: "connectionStateChange", callback: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
Subscribes to the PAN connection state change events.
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ---------------------------------------- |
| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.|
| callback | Callback&lt;[StateChangeParam](#StateChangeParam)&gt; | Yes | Callback used to return the PAN connection state change event. |
**Return value**
No value is returned.
**Example**
```js
function onReceiveEvent(data) {
console.info('pan state = '+ JSON.stringify(data));
}
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
panProfile.on('connectionStateChange', onReceiveEvent);
```
### off('connectionStateChange')<sup>9+</sup>
off(type: "connectionStateChange", callback?: Callback&lt;[StateChangeParam](#StateChangeParam)&gt;): void
Unsubscribes from the PAN connection state change events.
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ----------------------------------------------------- | ---- | --------------------------------------------------------- |
| type | string | Yes | Event type. The value **connectionStateChange** indicates a PAN connection state change event.|
| callback | Callback&lt;[StateChangeParam](#StateChangeParam)&gt; | No | Callback used to return the PAN connection state change event. |
**Return value**
No value is returned.
**Example**
```js
function onReceiveEvent(data) {
console.info('pan state = '+ JSON.stringify(data));
}
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
panProfile.on('connectionStateChange', onReceiveEvent);
panProfile.off('connectionStateChange', onReceiveEvent);
```
### setTethering<sup>9+</sup><a name="setTethering"></a>
setTethering(value: boolean): boolean
Sets tethering.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------- |
| value | boolean | Yes | Whether to set tethering over a Bluetooth PAN.|
**Return value**
| Type | Description |
| --------------------- | --------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
let ret = panProfile.setTethering(true);
```
### isTetheringOn<sup>9+</sup><a name="isTetheringOn"></a>
isTetheringOn(): boolean
Obtains the tethering status.
This is a system API.
**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH
**System capability**: SystemCapability.Communication.Bluetooth.Core
**Return value**
| Type | Description |
| --------------------- | --------------------------------- |
| boolean | Returns **true** if tethering is available over a Bluetooth PAN; return **false** otherwise.|
**Example**
```js
let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK);
let ret = panProfile.isTetheringOn();
```
## GattServer ## GattServer
Implements the Generic Attribute Profile (GATT) server. Before using a method of this class, you need to create a **GattServer** instance using the **createGattServer()** method. Implements the Generic Attribute Profile (GATT) server. Before using a method of this class, you need to create a **GattServer** instance using the **createGattServer()** method.
...@@ -2346,6 +2502,7 @@ let gattServer = bluetooth.BLE.createGattServer(); ...@@ -2346,6 +2502,7 @@ let gattServer = bluetooth.BLE.createGattServer();
gattServer.off("descriptorWrite"); gattServer.off("descriptorWrite");
``` ```
### on('connectStateChange') ### on('connectStateChange')
on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void on(type: "connectStateChange", callback: Callback&lt;BLEConnectChangedState&gt;): void
...@@ -2562,7 +2719,7 @@ gattClientDevice.getServices().then(result => { ...@@ -2562,7 +2719,7 @@ gattClientDevice.getServices().then(result => {
readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback&lt;BLECharacteristic&gt;): void readCharacteristicValue(characteristic: BLECharacteristic, callback: AsyncCallback&lt;BLECharacteristic&gt;): void
Reads the characteristic value of the specific service of the remote BLE device. This API uses an asynchronous callback to return the result. Reads the characteristic value of the specific service of the peer BLE device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2616,7 +2773,7 @@ device.readCharacteristicValue(characteristic, readCcc); ...@@ -2616,7 +2773,7 @@ device.readCharacteristicValue(characteristic, readCcc);
readCharacteristicValue(characteristic: BLECharacteristic): Promise&lt;BLECharacteristic&gt; readCharacteristicValue(characteristic: BLECharacteristic): Promise&lt;BLECharacteristic&gt;
Reads the characteristic value of the specific service of the remote BLE device. This API uses a promise to return the result. Reads the characteristic value of the specific service of the peer BLE device. This API uses a promise to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2663,7 +2820,7 @@ device.readCharacteristicValue(characteristic); ...@@ -2663,7 +2820,7 @@ device.readCharacteristicValue(characteristic);
readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback&lt;BLEDescriptor&gt;): void readDescriptorValue(descriptor: BLEDescriptor, callback: AsyncCallback&lt;BLEDescriptor&gt;): void
Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses an asynchronous callback to return the result. Reads the descriptor contained in the specific characteristic of the peer BLE device. This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -2707,7 +2864,7 @@ device.readDescriptorValue(descriptor, readDesc); ...@@ -2707,7 +2864,7 @@ device.readDescriptorValue(descriptor, readDesc);
readDescriptorValue(descriptor: BLEDescriptor): Promise&lt;BLEDescriptor&gt; readDescriptorValue(descriptor: BLEDescriptor): Promise&lt;BLEDescriptor&gt;
Reads the descriptor contained in the specific characteristic of the remote BLE device. This API uses a promise to return the result. Reads the descriptor contained in the specific characteristic of the peer BLE device. This API uses a promise to return the result.
**Required permissions**: ohos.permission.USE_BLUETOOTH **Required permissions**: ohos.permission.USE_BLUETOOTH
...@@ -3154,7 +3311,7 @@ Enumerates the scan modes. ...@@ -3154,7 +3311,7 @@ Enumerates the scan modes.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Default Value | Description |
| ---------------------------------------- | ---- | --------------- | | ---------------------------------------- | ---- | --------------- |
| SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_NONE | 0 | No scan mode. |
| SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. |
...@@ -3169,7 +3326,7 @@ Enumerates the pairing states. ...@@ -3169,7 +3326,7 @@ Enumerates the pairing states.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Default Value | Description |
| ------------------ | ---- | ------ | | ------------------ | ---- | ------ |
| BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_INVALID | 0 | Invalid pairing.|
| BOND_STATE_BONDING | 1 | Pairing. | | BOND_STATE_BONDING | 1 | Pairing. |
...@@ -3195,7 +3352,7 @@ Enumerates the SPP link types. ...@@ -3195,7 +3352,7 @@ Enumerates the SPP link types.
**System capability**: SystemCapability.Communication.Bluetooth.Core **System capability**: SystemCapability.Communication.Bluetooth.Core
| Name | Default Value | Description | | Name | Default Value | Description |
| ---------- | ---- | ------------- | | ---------- | ---- | ------------- |
| SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.|
......
# DefaultAppManager
The **DefaultAppManager** module provides APIs to query whether the current application is the default application of a specific type.
> **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.
## Modules to Import
```
import defaultAppMgr from '@ohos.bundle.defaultAppManager'
```
## defaultAppMgr.ApplicationType
Enumerates the application types.
**System capability**: SystemCapability.BundleManager.BundleFramework
| Name | Type | Description |
| -------- | -------- | -------------------------------------- |
| BROWSER | string | Default browser. |
| IMAGE | string | Default image viewer. |
| AUDIO | string | Default audio player. |
| VIDEO | string | Default video player. |
| PDF | string | Default PDF reader. |
| WORD | string | Default Word viewer. |
| EXCEL | string | Default Excel viewer. |
| PPT | string | Default PowerPoint viewer. |
## defaultAppMgr.isDefaultApplication
isDefaultApplication(type: string): Promise\<boolean>
Checks whether this application is the default application of a system-defined application type. This API uses a promise to return the result.
**System capability**: SystemCapability.BundleManager.BundleFramework
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). |
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<boolean> | Promise used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.|
**Example**
```js
defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data));
}).catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.isDefaultApplication
isDefaultApplication(type: string, callback: AsyncCallback\<boolean>): void
Checks whether this application is the default application of a system-defined application type. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.BundleManager.BundleFramework
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------------------------------- | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.|
**Example**
```js
defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. IsDefaultApplication ? ' + JSON.stringify(data));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, userId?: number): Promise\<BundleInfo>
Obtains the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Return value**
| Type | Description |
| ------------------------- | ------------------ |
| Promise\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Promise used to return the default application.|
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful. bundleInfo: ' + JSON.stringify(data));
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.getDefaultApplication("image/png")
.then((data) => {
console.info('Operation successful. bundleInfo: ' + JSON.stringify(data));
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, userId: number, callback: AsyncCallback\<BundleInfo>) : void
Obtains the default application of a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. |
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
defaultAppMgr.getDefaultApplication("image/png", 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
```
## defaultAppMgr.getDefaultApplication
getDefaultApplication(type: string, callback: AsyncCallback\<BundleInfo>) : void
Obtains the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.GET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the default application. |
**Example**
```js
defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
defaultAppMgr.getDefaultApplication("image/png", (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful. bundleInfo:' + JSON.stringify(data));
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, userId?: number): Promise\<void>
Sets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
})
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
})
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, userId: number, callback: AsyncCallback\<void>) : void;
Sets the default application for a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.setDefaultApplication
setDefaultApplication(type: string, elementName: ElementName, callback: AsyncCallback\<void>) : void;
Sets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | Information about the element to be set as the default application. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.setDefaultApplication("image/png", {
bundleName: "com.test.app",
moduleName: "module01",
abilityName: "MainAbility"
}, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, userId?: number): Promise\<void>
Resets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses a promise to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | No | User ID. The default value is the user ID of the caller. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER)
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
defaultAppMgr.resetDefaultApplication("image/png")
.then((data) => {
console.info('Operation successful.');
})
.catch((error) => {
console.error('Operation failed. Cause: ' + JSON.stringify(error));
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, userId: number, callback: AsyncCallback\<void>) : void;
Resets the default application for a user based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| userId | number | Yes | User ID. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.resetDefaultApplication("image/png", 100, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
## defaultAppMgr.resetDefaultApplication
resetDefaultApplication(type: string, callback: AsyncCallback\<void>) : void;
Resets the default application based on a system-defined application type or a file type that complies with the media type format (either specified by **type** or **subtype**). This API uses an asynchronous callback to return the result.
**Required permissions**: ohos.permission.SET_DEFAULT_APPLICATION
**System capability**: SystemCapability.BundleManager.BundleFramework
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name | Type | Mandatory | Description |
| ----------- | ------ | ---- | --------------------------------------- |
| type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype) or a file type that complies with the media type format. |
| callback | AsyncCallback\<void> | Yes | Callback used to return the result. |
**Example**
```js
defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
defaultAppMgr.resetDefaultApplication("image/png", (err, data) => {
if (err) {
console.error('Operation failed. Cause: ' + JSON.stringify(err));
return;
}
console.info('Operation successful.');
});
```
# Performance Tracing # 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 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. > - 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'; ...@@ -17,7 +17,7 @@ import bytrace from '@ohos.bytrace';
startTrace(name: string, taskId: number, expectedTime?: number): void 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 **System capability**: SystemCapability.Developtools.Bytrace
...@@ -25,11 +25,12 @@ Starts a trace task. **expectedTime** is an optional parameter, which specifies ...@@ -25,11 +25,12 @@ Starts a trace task. **expectedTime** is an optional parameter, which specifies
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the trace task to start.| | name | string | Yes| Name of a timeslice trace task.|
| taskId | number | Yes| Task ID.| | taskId | number | Yes| ID of a timeslice trace task.|
| expectedTime | number | No| Expected duration of the trace, in ms.| | 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. > 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** **Example**
...@@ -44,7 +45,7 @@ bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is ...@@ -44,7 +45,7 @@ bytrace.startTrace("myTestFunc", 1, 5); // The expected duration of the trace is
finishTrace(name: string, taskId: number): void finishTrace(name: string, taskId: number): void
Stops a trace task. Marks the end of a timeslice trace task.
**System capability**: SystemCapability.Developtools.Bytrace **System capability**: SystemCapability.Developtools.Bytrace
...@@ -52,10 +53,11 @@ Stops a trace task. ...@@ -52,10 +53,11 @@ Stops a trace task.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| name | string | Yes| Name of the trace task to start.| | name | string | Yes| Name of a timeslice trace task.|
| taskId | number | Yes| Task ID.| | 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**. > To stop a trace task, the values of name and task ID in **finishTrace** must be the same as those in **startTrace**.
**Example** **Example**
...@@ -91,7 +93,7 @@ bytrace.finishTrace("myTestFunc", 1); ...@@ -91,7 +93,7 @@ bytrace.finishTrace("myTestFunc", 1);
traceByValue(name: string, count: number): void 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 **System capability**: SystemCapability.Developtools.Bytrace
......
...@@ -347,7 +347,7 @@ After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera ...@@ -347,7 +347,7 @@ After **[camera.getCameraManager](#cameragetcameramanager)** is called, a camera
```js ```js
async function getCameraInfo("cameraId") { async function getCameraInfo("cameraId") {
var cameraManager = await camera.getCameraManager(); var cameraManager = await camera.getCameraManager(context);
var cameras = await cameraManager.getCameras(); var cameras = await cameraManager.getCameras();
var cameraObj = cameras[0]; var cameraObj = cameras[0];
var cameraId = cameraObj.cameraId; var cameraId = cameraObj.cameraId;
...@@ -2231,6 +2231,10 @@ Captures a photo with the specified capture settings. This API uses an asynchron ...@@ -2231,6 +2231,10 @@ Captures a photo with the specified capture settings. This API uses an asynchron
**Example** **Example**
```js ```js
let settings:PhotoCaptureSetting = {
quality = 1,
rotation = 0
}
photoOutput.capture(settings, (err) => { photoOutput.capture(settings, (err) => {
if (err) { if (err) {
console.error('Failed to capture the photo ${err.message}'); console.error('Failed to capture the photo ${err.message}');
...@@ -2359,7 +2363,7 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu ...@@ -2359,7 +2363,7 @@ Listens for frame shutter events. This API uses an asynchronous callback to retu
**Example** **Example**
```js ```js
photoOutput.on('frameShutter', (frameShutterInfo) => { photoOutput.on('frameShutter', (err, frameShutterInfo) => {
console.log('photo capture end, captureId : ' + frameShutterInfo.captureId); console.log('photo capture end, captureId : ' + frameShutterInfo.captureId);
console.log('Timestamp for frame : ' + frameShutterInfo.timestamp); console.log('Timestamp for frame : ' + frameShutterInfo.timestamp);
}) })
...@@ -2383,7 +2387,7 @@ Listens for photo capture end events. This API uses an asynchronous callback to ...@@ -2383,7 +2387,7 @@ Listens for photo capture end events. This API uses an asynchronous callback to
**Example** **Example**
```js ```js
photoOutput.on('captureEnd', (captureEndInfo) => { photoOutput.on('captureEnd', (err, captureEndInfo) => {
console.log('photo capture end, captureId : ' + captureEndInfo.captureId); console.log('photo capture end, captureId : ' + captureEndInfo.captureId);
console.log('frameCount : ' + captureEndInfo.frameCount); console.log('frameCount : ' + captureEndInfo.frameCount);
}) })
...@@ -2407,7 +2411,7 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error ...@@ -2407,7 +2411,7 @@ Listens for **PhotoOutput** errors. This API uses a callback to return the error
**Example** **Example**
```js ```js
photoOutput.on('error', (photoOutputError) => { photoOutput.on('error', (err, photoOutputError) => {
console.log('Photo output error code: ' + photoOutputError.code); console.log('Photo output error code: ' + photoOutputError.code);
}) })
``` ```
......
# Standard NFC Card Emulation # Standard NFC Card Emulation
Implements Near-Field Communication (NFC) card emulation. The cardEmulation module implements Near-Field Communication (NFC) card emulation.
> **NOTE**<br> > **NOTE**<br>
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## **Modules to Import** ## Modules to Import
``` ```
import cardEmulation from '@ohos.nfc.cardEmulation'; import cardEmulation from '@ohos.nfc.cardEmulation';
......
# Data Share Result Set
The **DataShareResultSet** module provides methods for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type.
>**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.
## Modules to Import
```ts
import DataShareResultSet from '@ohos.data.DataShareResultSet';
```
## How to Use
You can call [query()](js-apis-data-dataShare.md#query) to obtain the **DataShareResultSet** object.
```ts
import dataShare from '@ohos.data.dataShare';
import dataSharePredicates from '@ohos.data.dataSharePredicates'
let dataShareHelper;
let uri = ("datashare:///com.samples.datasharetest.DataShare");
await dataShare.createDataShareHelper(this.context, uri, (err, data) => {
if (err != undefined) {
console.info("createDataShareHelper fail, error message : " + err);
} else {
console.info("createDataShareHelper end, data : " + data);
dataShareHelper = data;
}
});
let columns = ["*"];
let da = new dataSharePredicates.DataSharePredicates();
let resultSet;
da.equalTo("name", "ZhangSan");
dataShareHelper.query(uri, da, columns).then((data) => {
console.log("query end, data : " + data);
resultSet = data;
}).catch((err) => {
console.log("query fail, error message : " + err);
});
```
## Attributes
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Type | Mandatory| Description |
| ----------- | ------------- | ---- | ------------------------ |
| columnNames | Array&lt;string&gt; | Yes | Names of all columns in the result set. |
| columnCount | number | Yes | Number of columns in the result set. |
| rowCount | number | Yes | Number of rows in the result set. |
| isClosed | boolean | Yes | Whether the result set is closed.|
## goToFirstRow
goToFirstRow(): boolean
Moves to the first row of the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Return value**
| Type | Description |
| :------ | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let isGoTOFirstRow = resultSet.goToFirstRow();
console.info('resultSet.goToFirstRow: ' + isGoTOFirstRow);
```
## goToLastRow
goToLastRow(): boolean
Moves to the last row of the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Return value**
| Type| Description|
| -------- | -------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let isGoToLastRow = resultSet.goToLastRow();
console.info('resultSet.goToLastRow: ' + isGoToLastRow);
```
## goToNextRow
goToNextRow(): boolean
Moves to the next row in the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let isGoToNextRow = resultSet.goToNextRow();
console.info('resultSet.goToNextRow: ' + isGoToNextRow);
```
## goToPreviousRow
goToPreviousRow(): boolean
Moves to the previous row in the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let isGoToPreviousRow = resultSet.goToPreviousRow();
console.info('resultSet.goToPreviousRow: ' + isGoToPreviousRow);
```
## goTo
goTo(offset:number): boolean
Moves based on the specified offset.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| Description |
| ---------- | -------- | -------- | ------------------------------------------------------------ |
| offset | number | Yes | Offset relative to the current position. A negative value means to move backward, and a positive value means to move forward.|
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let goToNum = 1;
let isGoTo = resultSet.goTo(goToNum);
console.info('resultSet.goTo: ' + isGoTo);
```
## goToRow
goToRow(position: number): boolean
Moves to the specified row in the result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| Description |
| ---------- | -------- | -------- | ------------------------ |
| position | number | Yes | Destination position to move.|
**Return value**
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
let goToRowNum = 2
let isGoToRow = resultSet.goToRow(goToRowNum);
console.info('resultSet.goToRow: ' + isGoToRow);
```
## getBlob
getBlob(columnIndex: number): Uint8Array
Obtains the value in the specified column in the current row as a byte array.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | ----------------------- |
| columnIndex | number | Yes | Index of the target column, starting from 0.|
**Return value**
| Type | Description |
| ---------- | -------------------------------- |
| Uint8Array | Value obtained.|
**Example**
```ts
let columnIndex = 1
let goToFirstRow = resultSet.goToFirstRow();
let getBlob = resultSet.getBlob(columnIndex);
console.info('resultSet.getBlob: ' + getBlob);
```
## getString
getString(columnIndex: number): *string*
Obtains the value in the specified column in the current row as a string.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | ----------------------- |
| columnIndex | number | Yes | Index of the target column, starting from 0.|
**Return value**
| Type | Description |
| ------ | ---------------------------- |
| string | Value obtained.|
**Example**
```ts
let columnIndex = 1
let goToFirstRow = resultSet.goToFirstRow();
let getString = resultSet.getString(columnIndex);
console.info('resultSet.getString: ' + getString);
```
## getLong
getLong(columnIndex: number): number
Obtains the value in the specified column in the current row as a long integer.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | ----------------------- |
| columnIndex | number | Yes | Index of the target column, starting from 0.|
**Return value**
| Type | Description |
| ------ | -------------------------- |
| number | Value obtained.|
**Example**
```ts
let columnIndex = 1
let goToFirstRow = resultSet.goToFirstRow();
let getLong = resultSet.getLong(columnIndex);
console.info('resultSet.getLong: ' + getLong);
```
## getDouble
getDouble(columnIndex: number): number
Obtains the value in the specified column in the current row as a double-precision floating-point number.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | ----------------------- |
| columnIndex | number | Yes | Index of the target column, starting from 0.|
**Return value**
| Type | Description |
| ------ | ---------------------------- |
| number | Value obtained.|
**Example**
```ts
let columnIndex = 1
let goToFirstRow = resultSet.goToFirstRow();
let getDouble = resultSet.getDouble(columnIndex);
console.info('resultSet.getDouble: ' + getDouble);
```
## close
close(): void
Closes this result set.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Example**
```ts
resultSet.close();
```
## getColumnIndex
getColumnIndex(columnName: string): number
Obtains the column index based on the column name.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name**| **Type**| **Mandatory**| Description |
| ---------- | -------- | -------- | -------------------------- |
| columnName | string | Yes | Column name.|
**Return value**
| Type | Description |
| ------ | ------------------ |
| number | Column index obtained.|
**Example**
```ts
let ColumnName = "name"
let getColumnIndex = resultSet.getColumnIndex(ColumnName)
console.info('resultSet.getColumnIndex: ' + getColumnIndex);
```
## getColumnName
getColumnName(columnIndex: number): *string*
Obtains the column name based on the column index.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | -------------------------- |
| columnIndex | number | Yes | Column index.|
**Return value**
| Type | Description |
| ------ | ------------------ |
| string | Column name obtained.|
**Example**
```ts
let columnIndex = 1
let getColumnName = resultSet.getColumnName(columnIndex)
console.info('resultSet.getColumnName: ' + getColumnName);
```
## getDataType
getDataType(columnIndex: number): DataType
Obtains the data type based on the specified column index.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
**Parameters**
| **Name** | **Type**| **Mandatory**| Description |
| ----------- | -------- | -------- | -------------------------- |
| columnIndex | number | Yes | Column index.|
**Return value**
| Type | Description |
| --------------------- | ------------------ |
| [DataType](#datatype) | Data type obtained.|
**Example**
```ts
let columnIndex = 1;
let getDataType = resultSet.getDataType(columnIndex);
console.info('resultSet.getDataType: ' + getDataType);
```
## DataType
Enumerates the data types.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Value| Description |
| ----------- | ------ | -------------------- |
| TYPE_NULL | 0 | Null. |
| TYPE_LONG | 1 | Long integer. |
| TYPE_DOUBLE | 2 | Double-precision floating-point number.|
| TYPE_STRING | 3 | String.|
| TYPE_BLOB | 4 | Byte array.|
# Value Bucket
The **ValueBucket** holds data in key-value (KV) pairs. You can use it to insert data into a database.
>**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.
## Modules to Import
```ts
import { ValueType } from '@ohos.data.ValuesBucket';
import { ValuesBucket } from '@ohos.data.ValuesBucket';
```
## ValueType
Enumerates the value types allowed by the database.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Description |
| ------- | -------------------- |
| number | The value is a number. |
| string | The value is a string.|
| boolean | The value is of Boolean type.|
## ValuesBucket
Holds a set of KV pairs.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
| Name | Type | Mandatory| Description |
| ------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| [key: string] | [ValueType](#valuetype)\| Uint8Array \| null | Yes | KV pairs in a **ValuesBucket**. The key is of the string type. The value can be a number, string, Boolean value, Unit8Array, or **null**.|
...@@ -29,7 +29,7 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul ...@@ -29,7 +29,7 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.| | version | number | Yes| RDB store version.|
| callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.| | callback | AsyncCallback&lt;[RdbStore](#rdbstore)&gt; | Yes| Callback invoked to return the RDB store obtained.|
...@@ -59,7 +59,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set ...@@ -59,7 +59,7 @@ Obtains an RDB store. This API uses a promise to return the result. You can set
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | Context | Yes|Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| | config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.|
| version | number | Yes| RDB store version.| | version | number | Yes| RDB store version.|
...@@ -92,7 +92,7 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul ...@@ -92,7 +92,7 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
...@@ -118,7 +118,7 @@ Deletes an RDB store. This API uses a promise to return the result. ...@@ -118,7 +118,7 @@ Deletes an RDB store. This API uses a promise to return the result.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| context | Context | Yes| Context of the application or functionality.<br>See [Context](js-apis-Context.md) for versions earlier than API version 9.<br>See [Context](js-apis-ability-context.md) for API version 9 or later.| | context | Context | Yes| Application context.<br>For the application context of the FA model, see [Context](js-apis-Context.md).<br>For the application context of the stage model, see [Context](js-apis-ability-context.md).|
| name | string | Yes| Name of the RDB store to delete.| | name | string | Yes| Name of the RDB store to delete.|
**Return value** **Return value**
...@@ -1018,7 +1018,7 @@ const valueBucket = { ...@@ -1018,7 +1018,7 @@ const valueBucket = {
} }
let promise = rdbStore.insert("EMPLOYEE", valueBucket) let promise = rdbStore.insert("EMPLOYEE", valueBucket)
promise.then(async (ret) => { promise.then(async (ret) => {
console.log("Insert first done: " + ret) console.log("Inserted first row: " + ret)
}).catch((err) => { }).catch((err) => {
console.log("Failed to insert data, err: " + err) console.log("Failed to insert data, err: " + err)
}) })
...@@ -1029,16 +1029,16 @@ promise.then(async (ret) => { ...@@ -1029,16 +1029,16 @@ promise.then(async (ret) => {
update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void update(values: ValuesBucket, predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void
Updates data in the database based on the specified RdbPredicates object. This API uses an asynchronous callback to return the result. Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1064,14 +1064,14 @@ rdbStore.update(valueBucket, predicates, function (err, ret) { ...@@ -1064,14 +1064,14 @@ rdbStore.update(valueBucket, predicates, function (err, ret) {
update(values: ValuesBucket, predicates: RdbPredicates):Promise&lt;number&gt; update(values: ValuesBucket, predicates: RdbPredicates):Promise&lt;number&gt;
Updates data in the database based on the specified RdbPredicates object. This API uses a promise to return the result. Updates data in the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.| | predicates | [RdbPredicates](#rdbpredicates) | Yes| Update conditions specified by the **RdbPredicates** object.|
**Return value** **Return value**
...@@ -1100,7 +1100,7 @@ promise.then(async (ret) => { ...@@ -1100,7 +1100,7 @@ promise.then(async (ret) => {
### update<sup>9+</sup> ### update<sup>9+</sup>
update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void
Updates data in the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1108,9 +1108,9 @@ Updates data in the database based on the specified **DataSharePredicates** obje ...@@ -1108,9 +1108,9 @@ Updates data in the database based on the specified **DataSharePredicates** obje
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| | predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.|
| callback | AsyncCallback&lt;number&gt; | Yes| Callback used to return the number of rows updated.| | callback | AsyncCallback&lt;number&gt; | Yes| Callback invoked to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1135,7 +1135,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { ...@@ -1135,7 +1135,7 @@ rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) {
update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise&lt;number&gt; update(table: string, values: ValuesBucket, predicates: DataSharePredicates):Promise&lt;number&gt;
Updates data in the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1143,7 +1143,7 @@ Updates data in the database based on the specified **DataSharePredicates** obje ...@@ -1143,7 +1143,7 @@ Updates data in the database based on the specified **DataSharePredicates** obje
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| table | string | Yes| Name of the target table.| | table | string | Yes| Name of the target table.|
| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to be updated in the database. The key-value pair is associated with the column name in the target table.| | values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.|
| predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| | predicates | [DataSharePredicates](js-apis-data-DataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.|
**Return value** **Return value**
...@@ -1175,7 +1175,7 @@ promise.then(async (ret) => { ...@@ -1175,7 +1175,7 @@ promise.then(async (ret) => {
delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void delete(predicates: RdbPredicates, callback: AsyncCallback&lt;number&gt;):void
Deletes data from the database based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result. Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1203,7 +1203,7 @@ rdbStore.delete(predicates, function (err, rows) { ...@@ -1203,7 +1203,7 @@ rdbStore.delete(predicates, function (err, rows) {
delete(predicates: RdbPredicates):Promise&lt;number&gt; delete(predicates: RdbPredicates):Promise&lt;number&gt;
Deletes data from the database based on the specified **RdbPredicates** object. This API uses a promise to return the result. Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1215,7 +1215,7 @@ Deletes data from the database based on the specified **RdbPredicates** object. ...@@ -1215,7 +1215,7 @@ Deletes data from the database based on the specified **RdbPredicates** object.
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1234,7 +1234,7 @@ promise.then((rows) => { ...@@ -1234,7 +1234,7 @@ promise.then((rows) => {
delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void delete(table: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;):void
Deletes data from the database based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1262,7 +1262,7 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { ...@@ -1262,7 +1262,7 @@ rdbStore.delete("EMPLOYEE", predicates, function (err, rows) {
delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt; delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise&lt;number&gt;
Deletes data from the database based on the specified **DataSharePredicates** object. This API uses a promise to return the result. Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1275,7 +1275,7 @@ Deletes data from the database based on the specified **DataSharePredicates** ob ...@@ -1275,7 +1275,7 @@ Deletes data from the database based on the specified **DataSharePredicates** ob
**Return value** **Return value**
| Type| Description| | Type| Description|
| -------- | -------- | | -------- | -------- |
| Promise&lt;number&gt; | Promise used to return the number of rows updated.| | Promise&lt;number&gt; | Promise used to return the number of rows updated.|
**Example** **Example**
```js ```js
...@@ -1294,7 +1294,7 @@ promise.then((rows) => { ...@@ -1294,7 +1294,7 @@ promise.then((rows) => {
query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(predicates: RdbPredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1324,7 +1324,7 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e ...@@ -1324,7 +1324,7 @@ rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (e
query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(predicates: RdbPredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
Queries data in the database based on specified conditions. This API uses a promise to return the result. Queries data in the RDB store based on specified conditions. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1356,7 +1356,7 @@ Queries data in the database based on specified conditions. This API uses a prom ...@@ -1356,7 +1356,7 @@ Queries data in the database based on specified conditions. This API uses a prom
query(predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void query(predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;ResultSet&gt;):void
Queries data in the database based on specified conditions. This API uses an asynchronous callback to return the result. Queries data in the RDB store based on specified conditions. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1386,7 +1386,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], ...@@ -1386,7 +1386,7 @@ rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"],
query(predicates: DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt; query(predicates: DataSharePredicates, columns?: Array&lt;string&gt;):Promise&lt;ResultSet&gt;
Queries data in the database based on specified conditions. This API uses a promise to return the result. Queries data in the RDB store based on specified conditions. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
...@@ -1625,14 +1625,14 @@ try { ...@@ -1625,14 +1625,14 @@ try {
backup(destName:string, callback: AsyncCallback&lt;void&gt;):void backup(destName:string, callback: AsyncCallback&lt;void&gt;):void
Backs up the database with the specified name. This API uses an asynchronous callback to return the result. Backs up an RDB store. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| destName | string | Yes| Name of the database backup file.| | destName | string | Yes| Name of the RDB store backup file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
...@@ -1650,14 +1650,14 @@ rdbStore.backup("dbBackup.db", function(err) { ...@@ -1650,14 +1650,14 @@ rdbStore.backup("dbBackup.db", function(err) {
backup(destName:string): Promise&lt;void&gt; backup(destName:string): Promise&lt;void&gt;
Backs up the database with the specified name. This API uses a promise to return the result. Backs up an RDB store. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| destName | string | Yes| Name of the database backup file.| | destName | string | Yes| Name of the RDB store backup file.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -1678,14 +1678,14 @@ promiseBackup.then(()=>{ ...@@ -1678,14 +1678,14 @@ promiseBackup.then(()=>{
restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void restore(srcName:string, callback: AsyncCallback&lt;void&gt;):void
Restores a database from a specified database backup file. This API uses an asynchronous callback to return the result. Restores an RDB store using a backup file. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| srcName | string | Yes| Name of the database backup file.| | srcName | string | Yes| Name of the RDB store backup file.|
| callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback invoked to return the result.|
**Example** **Example**
...@@ -1703,14 +1703,14 @@ rdbStore.restore("dbBackup.db", function(err) { ...@@ -1703,14 +1703,14 @@ rdbStore.restore("dbBackup.db", function(err) {
restore(srcName:string): Promise&lt;void&gt; restore(srcName:string): Promise&lt;void&gt;
Restores a database from a specified database backup file. This API uses a promise to return the result. Restores an RDB store using a backup file. This API uses a promise to return the result.
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| srcName | string | Yes| Name of the database backup file.| | srcName | string | Yes| Name of the RDB store backup file.|
**Return value** **Return value**
| Type| Description| | Type| Description|
...@@ -1809,7 +1809,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err, ...@@ -1809,7 +1809,7 @@ rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE", function (err,
console.info('Failed to obtain DistributedTableName, err: ' + err) console.info('Failed to obtain DistributedTableName, err: ' + err)
return return
} }
console.info('Obtained DistributedTableName successfully, tableName=.' + tableName) console.info('Obtained distributed table name successfully, tableName=.' + tableName)
}) })
``` ```
...@@ -1839,7 +1839,7 @@ Obtains the distributed table name for a remote device based on the local table ...@@ -1839,7 +1839,7 @@ Obtains the distributed table name for a remote device based on the local table
```js ```js
let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE") let promise = rdbStore.obtainDistributedTableName("12345678abcde", "EMPLOYEE")
promise.then((tableName) => { promise.then((tableName) => {
console.info('Obtained DistributedTableName successfully, tableName= ' + tableName) console.info('Obtained distributed table name successfully, tableName= ' + tableName)
}).catch((err) => { }).catch((err) => {
console.info('Failed to obtain DistributedTableName, err: ' + err) console.info('Failed to obtain DistributedTableName, err: ' + err)
}) })
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status. The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br> > **NOTE**<br>
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version.
......
# User File Access and Management # User File Access and Management
The fileManager module provides APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files.
>**NOTE**<br/> >**NOTE**<br/>
> >
>- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. >- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>- The APIs of this module are system APIs and cannot be called by third-party applications. Currently, these APIs can be called only by **filepicker**. >- The APIs of this module are system APIs and cannot be called by third-party applications. Currently, these APIs can be called only by **filepicker**.
Provides service APIs for accessing and managing user files. It interworks with the underlying file management services to implement media library and external card management, and provides capabilities for applications to query and create user files.
## Modules to Import ## Modules to Import
```js ```js
......
...@@ -287,7 +287,7 @@ Defines the information about an input device. ...@@ -287,7 +287,7 @@ Defines the information about an input device.
| Name | Type | Description | | Name | Type | Description |
| -------- | ------------------------- | --------------------------------- | | -------- | ------------------------- | --------------------------------- |
| type | [ChangeType](#changetype) | Device change type, which indicates whether an input device is inserted or removed. | | type | [ChangedType](#changedtype) | Device change type, which indicates whether an input device is inserted or removed. |
| deviceId | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| | deviceId | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.|
## InputDeviceData ## InputDeviceData
......
...@@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -92,7 +92,7 @@ This is a system API and cannot be called by third-party applications.
```js ```js
var child = process.runCmd('ls'); var child = process.runCmd('ls');
var result = child.wait(); var result = child.wait();
child.getOutput.then(val=>{ child.getOutput().then(val=>{
console.log("child.getOutput = " + val); console.log("child.getOutput = " + val);
}) })
``` ```
...@@ -119,7 +119,7 @@ This is a system API and cannot be called by third-party applications. ...@@ -119,7 +119,7 @@ This is a system API and cannot be called by third-party applications.
```js ```js
var child = process.runCmd('madir test.text'); var child = process.runCmd('madir test.text');
var result = child.wait(); var result = child.wait();
child.getErrorOutput.then(val=>{ child.getErrorOutput().then(val=>{
console.log("child.getErrorOutput= " + val); console.log("child.getErrorOutput= " + val);
}) })
``` ```
...@@ -286,7 +286,7 @@ Obtains the thread priority based on the specified TID. ...@@ -286,7 +286,7 @@ Obtains the thread priority based on the specified TID.
**Example** **Example**
```js ```js
var tid = process.getTid(); var tid = process.tid;
var pres = process.getThreadPriority(tid); var pres = process.getThreadPriority(tid);
``` ```
...@@ -617,5 +617,5 @@ Sends a signal to the specified process to terminate it. ...@@ -617,5 +617,5 @@ Sends a signal to the specified process to terminate it.
```js ```js
var pres = process.pid var pres = process.pid
var result = that.kill(28, pres) var result = process.kill(28, pres)
``` ```
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册