提交 a3406372 编写于 作者: IT_newip's avatar IT_newip

Merge branch 'master' of https://gitee.com/openharmony/docs

...@@ -210,6 +210,7 @@ zh-cn/application-dev/reference/apis/js-apis-router.md @HelloCrease ...@@ -210,6 +210,7 @@ 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-effectKit.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-screen.md @ge-yafang
zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-windowAnimationManager.md @ge-yafang
......
...@@ -47,5 +47,6 @@ ...@@ -47,5 +47,6 @@
- Native APIs - Native APIs
- [Standard Libraries](reference/native-lib/third_party_libc/musl.md) - [Standard Libraries](reference/native-lib/third_party_libc/musl.md)
- [Node_API](reference/native-lib/third_party_napi/napi.md) - [Node_API](reference/native-lib/third_party_napi/napi.md)
- [FAQs](faqs/Readme-EN.md)
- Contribution - Contribution
- [How to Contribute](../contribute/documentation-contribution.md) - [How to Contribute](../contribute/documentation-contribution.md)
...@@ -7,9 +7,11 @@ ...@@ -7,9 +7,11 @@
The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model. The OpenHarmony application framework has two models: Feature Ability (FA) model and stage model. Correspondingly, there are two sets of context mechanisms. **application/BaseContext** is a common context base class. It uses the **stageMode** attribute to specify whether the context is used for the stage model.
- FA model - FA model
Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance. Only the methods in **app/Context** can be used for the context in the FA model. Both the application-level context and ability-level context are instances of this type. If an ability-level method is invoked in the application-level context, an error occurs. Therefore, you must pay attention to the actual meaning of the **Context** instance.
- Stage model - Stage model
The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model). The stage model has the following types of contexts: **application/Context**, **application/ApplicationContext**, **application/AbilityStageContext**, **application/ExtensionContext**, **application/AbilityContext**, and **application/FormExtensionContext**. For details about these contexts and how to use them, see [Context in the Stage Model](#context-in-the-stage-model).
![contextIntroduction](figures/contextIntroduction.png) ![contextIntroduction](figures/contextIntroduction.png)
......
# Ability Call Development # Ability Call Development
## When to Use ## When to Use
Ability call is an extension of the ability capabilities. It enables an ability to be invoked by external systems. In this way, the ability can be displayed as a UI page on the foreground and created and run on the background. You can use the **Call** APIs to implement data sharing between different abilities through inter-process communication (IPC). There are two roles in the ability call: caller and callee. The following scenarios are involved in the ability call development: Ability call is an extension of the ability capability. It enables an ability to be invoked by and communicate with external systems. The ability invoked can be either started in the foreground or created and run in the background. You can use the ability call to implement data sharing between two abilities (caller ability and callee ability) through inter-process communication (IPC).
- Creating a callee
- Accessing the callee
The following figure shows the ability call process. The core API used for the ability call is `startAbilityByCall`, which differs from `startAbility` in the following ways:
- `startAbilityByCall` supports ability startup in the foreground and background, whereas `startAbility` supports ability startup in the foreground only.
- The caller ability can use the `Caller` object returned by `startAbilityByCall` to communicate with the callee ability, but `startAbility` does not provide the communication capability.
Ability call is usually used in the following scenarios:
- Communicating with the callee ability
- Starting the callee ability in the background
**Table 1** Terms used in the ability call
|Term|Description|
|:------|:------|
|Caller ability|Ability that triggers the ability call.|
|Callee ability|Ability invoked by the ability call.|
|Caller |Object returned by `startAbilityByCall` and used by the caller ability to communicate with the callee ability.|
|Callee |Object held by the callee ability to communicate with the caller ability.|
|IPC |Inter-process communication.|
The ability call process is as follows:
- The caller ability uses `startAbilityByCall` to obtain a `Caller` object and uses `call()` of the `Caller` object to send data to the callee ability.
- The callee ability, which holds a `Callee` object, uses `on()` of the `Callee` object to register a callback. This callback is invoked when the callee ability receives data from the caller ability.
![stage-call](figures/stage-call.png) ![stage-call](figures/stage-call.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> > **NOTE**<br/>
> The startup mode of the callee must be **singleton**. > The launch type of the callee ability must be `singleton`.
> Currently, only system applications and Service Extension abilities can use the **Call** APIs to access the callee. > Currently, only system applications can use the ability call.
## Available APIs ## Available APIs
The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller). The table below describes the ability call APIs. For details, see [Ability](../reference/apis/js-apis-application-ability.md#caller).
**Table 1** Ability call APIs **Table 2** Ability call APIs
|API|Description| |API|Description|
|:------|:------| |:------|:------|
|startAbilityByCall(want: Want): Promise\<Caller>|Obtains the caller interface of the specified ability and, if the specified ability is not running, starts the ability in the background.| |startAbilityByCall(want: Want): Promise\<Caller>|Starts an ability in the foreground (through the `want` configuration) or background (default) and obtains the `Caller` object for communication with the ability. For details, see [AbilityContext](../reference/apis/js-apis-ability-context.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-service-extension-context.md#serviceextensioncontextstartabilitybycall).|
|on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee registers a method.| |on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee ability registers a method.|
|off(method: string): void|Callback invoked when the callee deregisters a method.| |off(method: string): void|Callback invoked when the callee ability deregisters a method.|
|call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee.| |call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee ability.|
|callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.| |callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.|
|release(): void|Releases the caller interface.| |release(): void|Releases the `Caller` object.|
|onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.| |onRelease(callback: OnReleaseCallBack): void|Callback invoked when the `Caller` object is released.|
## How to Develop ## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/> The procedure for developing the ability call is as follows:
> The sample code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently. 1. Create a callee ability.
### Creating a Callee 2. Access the callee ability.
For the callee, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use the **on** API to register a listener. When data does not need to be received, use the **off** API to deregister the listener. > **NOTE**
1. Configure the ability startup mode. >
> The code snippets provided in the **How to Develop** section are used to show specific development steps. They may not be able to run independently.
### Creating a Callee Ability
For the callee ability, implement the callback to receive data and the methods to marshal and unmarshal data. When data needs to be received, use `on()` to register a listener. When data does not need to be received, use `off()` to deregister the listener.
**1. Configure the ability launch type.**
Set the ability of the callee to **singleton** in the **module.json5** file. Set `launchType` of the callee ability to `singleton` in the `module.json5` file.
|JSON Field|Description| |JSON Field|Description|
|:------|:------| |:------|:------|
|"launchType"|Ability startup mode. Set this parameter to **singleton**.| |"launchType"|Ability launch type. Set this parameter to `singleton`.|
An example of the ability configuration is as follows: An example of the ability configuration is as follows:
```json ```json
...@@ -51,13 +71,13 @@ An example of the ability configuration is as follows: ...@@ -51,13 +71,13 @@ An example of the ability configuration is as follows:
"visible": true "visible": true
}] }]
``` ```
2. Import the **Ability** module. **2. Import the Ability module.**
``` ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
``` ```
3. Define the agreed sequenceable data. **3. Define the agreed sequenceable data.**
The data formats sent and received by the caller and callee must be consistent. In the following example, the data consists of numbers and strings. The sample code snippet is as follows: The data formats sent and received by the caller and callee abilities must be consistent. In the following example, the data formats are number and string. The code snippet is as follows:
```ts ```ts
export default class MySequenceable { export default class MySequenceable {
num: number = 0 num: number = 0
...@@ -81,23 +101,23 @@ export default class MySequenceable { ...@@ -81,23 +101,23 @@ export default class MySequenceable {
} }
} }
``` ```
4. Implement **Callee.on** and **Callee.off**. **4. Implement `Callee.on` and `Callee.off`.**
The time to register a listener for the callee depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate** of the ability and deregistered in **onDestroy**. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code snippet is as follows: The time to register a listener for the callee ability depends on your application. The data sent and received before the listener is registered and that after the listener is deregistered are not processed. In the following example, the `MSG_SEND_METHOD` listener is registered in `onCreate` of the ability and deregistered in `onDestroy`. After receiving sequenceable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The code snippet is as follows:
```ts ```ts
const TAG: string = '[CalleeAbility]' const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
function sendMsgCallback(data) { function sendMsgCallback(data) {
Logger.log(TAG, 'CalleeSortFunc called') console.log('CalleeSortFunc called')
// Obtain the sequenceable data sent by the caller. // Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '') let receivedData = new MySequenceable(0, '')
data.readSequenceable(receivedData) data.readSequenceable(receivedData)
Logger.log(TAG, `receiveData[${receivedData.num}, ${receivedData.str}]`) console.log(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// Process the data. // Process the data.
// Return the sequenceable data result to the caller. // Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`) return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`)
} }
...@@ -106,7 +126,7 @@ export default class CalleeAbility extends Ability { ...@@ -106,7 +126,7 @@ export default class CalleeAbility extends Ability {
try { try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback) this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
} catch (error) { } catch (error) {
Logger.error(TAG, `${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`) console.log(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`)
} }
} }
...@@ -120,15 +140,27 @@ export default class CalleeAbility extends Ability { ...@@ -120,15 +140,27 @@ export default class CalleeAbility extends Ability {
} }
``` ```
### Accessing the Callee ### Accessing the Callee Ability
1. Import the **Ability** module. **1. Import the Ability module.**
``` ```ts
import Ability from '@ohos.application.Ability' import Ability from '@ohos.application.Ability'
``` ```
2. Obtain the caller interface. **2. Obtain the `Caller` object.**
The **context** attribute of the ability implements **startAbilityByCall** to obtain the caller interface of the ability. The following example uses **this.context** to obtain the **context** attribute of the **Ability** instance, uses **startAbilityByCall** to start the callee, obtain the caller interface, and register the **onRelease** listener of the caller. You need to implement processing based on service requirements. The sample code snippet is as follows: The `context` attribute of the ability implements `startAbilityByCall` to obtain the `Caller` object for communication. The following example uses `this.context` to obtain the `context` attribute of the ability, uses `startAbilityByCall` to start the callee ability, obtain the `Caller` object, and register the `onRelease` listener of the caller ability. You need to implement processing based on service requirements. The code snippet is as follows:
```ts ```ts
// Register the onRelease listener of the caller ability.
private regOnRelease(caller) {
try {
caller.onRelease((msg) => {
console.log(`caller onRelease is called ${msg}`)
})
console.log('caller register OnRelease succeed')
} catch (error) {
console.log(`caller register OnRelease failed with ${error}`)
}
}
async onButtonGetCaller() { async onButtonGetCaller() {
try { try {
this.caller = await context.startAbilityByCall({ this.caller = await context.startAbilityByCall({
...@@ -136,73 +168,74 @@ async onButtonGetCaller() { ...@@ -136,73 +168,74 @@ async onButtonGetCaller() {
abilityName: 'CalleeAbility' abilityName: 'CalleeAbility'
}) })
if (this.caller === undefined) { if (this.caller === undefined) {
Logger.error(TAG, 'get caller failed') console.log('get caller failed')
return return
} }
Logger.log(TAG, 'get caller success') console.log('get caller success')
this.regOnRelease(this.caller) this.regOnRelease(this.caller)
} catch (error) { } catch (error) {
Logger.error(TAG, `get caller failed with ${error}`) console.log(`get caller failed with ${error}`)
} }
}.catch((error) => { }
console.error(TAG + 'get caller failed with ' + error)
})
``` ```
In the cross-device scenario, you need to specify the ID of the peer device. The sample code snippet is as follows: In the cross-device scenario, you need to specify the ID of the peer device. The code snippet is as follows:
```ts ```ts
let TAG = '[MainAbility] ' async onButtonGetRemoteCaller() {
var caller = undefined var caller = undefined
let context = this.context var context = this.context
context.startAbilityByCall({ context.startAbilityByCall({
deviceId: getRemoteDeviceId(), deviceId: getRemoteDeviceId(),
bundleName: 'com.samples.CallApplication', bundleName: 'com.samples.CallApplication',
abilityName: 'CalleeAbility' abilityName: 'CalleeAbility'
}).then((data) => { }).then((data) => {
if (data != null) { if (data != null) {
caller = data caller = data
console.log(TAG + 'get remote caller success') console.log('get remote caller success')
// Register the onRelease listener of the caller. // Register the onRelease listener of the caller ability.
caller.onRelease((msg) => { caller.onRelease((msg) => {
console.log(TAG + 'remote caller onRelease is called ' + msg) console.log(`remote caller onRelease is called ${msg}`)
}) })
console.log(TAG + 'remote caller register OnRelease succeed') console.log('remote caller register OnRelease succeed')
} }
}).catch((error) => { }).catch((error) => {
console.error(TAG + 'get remote caller failed with ' + error) console.error(`get remote caller failed with ${error}`)
}) })
}
``` ```
Obtain the ID of the peer device from **DeviceManager**. Note that the **getTrustedDeviceListSync** API is open only to system applications. The sample code snippet is as follows: Obtain the ID of the peer device from `DeviceManager`. Note that the `getTrustedDeviceListSync` API is open only to system applications. The code snippet is as follows:
```ts ```ts
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass; var dmClass;
function getRemoteDeviceId() { function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) { if (typeof dmClass === 'object' && dmClass != null) {
var list = dmClass.getTrustedDeviceListSync(); var list = dmClass.getTrustedDeviceListSync()
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') { if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null"); console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null")
return; return
} }
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId); console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId)
return list[0].deviceId; return list[0].deviceId
} else { } else {
console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null"); console.log("MainAbility onButtonClick getRemoteDeviceId err: dmClass is null")
} }
} }
``` ```
In the cross-device scenario, the application must also apply for the data synchronization permission from end users. The sample code snippet is as follows: In the cross-device scenario, your application must also apply for the data synchronization permission from end users. The code snippet is as follows:
```ts ```ts
let context = this.context requestPermission() {
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'] let context = this.context
context.requestPermissionsFromUser(permissions).then((data) => { let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) context.requestPermissionsFromUser(permissions).then((data) => {
}).catch((error) => { console.log("Succeed to request permission from user with data: "+ JSON.stringify(data))
console.log("Failed to request permission from user with error: "+ JSON.stringify(error)) }).catch((error) => {
}) console.log("Failed to request permission from user with error: "+ JSON.stringify(error))
})
}
``` ```
3. Send agreed sequenceable data. **3. Send agreed sequenceable data.**
The sequenceable data can be sent to the callee with or without a return value. The method and sequenceable data must be consistent with those of the callee. The following example describes how to invoke the **Call** API to send data to the callee. The sample code snippet is as follows: The sequenceable data can be sent to the callee ability with or without a return value. The method and sequenceable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability. The code snippet is as follows:
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
async onButtonCall() { async onButtonCall() {
...@@ -210,12 +243,12 @@ async onButtonCall() { ...@@ -210,12 +243,12 @@ async onButtonCall() {
let msg = new MySequenceable(1, 'origin_Msg') let msg = new MySequenceable(1, 'origin_Msg')
await this.caller.call(MSG_SEND_METHOD, msg) await this.caller.call(MSG_SEND_METHOD, msg)
} catch (error) { } catch (error) {
Logger.error(TAG, `caller call failed with ${error}`) console.log(`caller call failed with ${error}`)
} }
} }
``` ```
In the following, **CallWithResult** is used to send data **originMsg** to the callee and assign the data processed by the **CallSendMsg** method to **backMsg**. The sample code snippet is as follows: In the following, `CallWithResult` is used to send data `originMsg` to the callee ability and assign the data processed by the `CallSendMsg` method to `backMsg`. The code snippet is as follows:
```ts ```ts
const MSG_SEND_METHOD: string = 'CallSendMsg' const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = '' originMsg: string = ''
...@@ -224,26 +257,28 @@ async onButtonCallWithResult(originMsg, backMsg) { ...@@ -224,26 +257,28 @@ async onButtonCallWithResult(originMsg, backMsg) {
try { try {
let msg = new MySequenceable(1, originMsg) let msg = new MySequenceable(1, originMsg)
const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg) const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg)
Logger.log(TAG, 'caller callWithResult succeed') console.log('caller callWithResult succeed')
let result = new MySequenceable(0, '') let result = new MySequenceable(0, '')
data.readSequenceable(result) data.readSequenceable(result)
backMsg(result.str) backMsg(result.str)
Logger.log(TAG, `caller result is [${result.num}, ${result.str}]`) console.log(`caller result is [${result.num}, ${result.str}]`)
} catch (error) { } catch (error) {
Logger.error(TAG, `caller callWithResult failed with ${error}`) console.log(`caller callWithResult failed with ${error}`)
} }
} }
``` ```
4. Release the caller interface. **4. Release the `Caller` object.**
When the caller interface is no longer required, call the **release** API to release it. The sample code snippet is as follows: When the `Caller` object is no longer required, use `release()` to release it. The code snippet is as follows:
```ts ```ts
try { releaseCall() {
this.caller.release() try {
this.caller = undefined this.caller.release()
Logger.log(TAG, 'caller release succeed') this.caller = undefined
} catch (error) { console.log('caller release succeed')
Logger.error(TAG, `caller release failed with ${error}`) } catch (error) {
console.log(`caller release failed with ${error}`)
}
} }
``` ```
...@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share ...@@ -13,7 +13,7 @@ The **DataShare** module allows an application to manage its own data and share
|query?(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void|Queries data from the database.| |query?(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;Object&gt;): void|Queries data from the database.|
|delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void|Deletes data from the database.| |delete?(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void|Deletes data from the database.|
For more details, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md). For more information, see [DataShareExtensionAbility](../reference/apis/js-apis-application-DataShareExtensionAbility.md).
**Table 2** APIs of the data consumer **Table 2** APIs of the data consumer
...@@ -25,11 +25,11 @@ For more details, see [DataShareExtensionAbility](../reference/apis/js-apis-appl ...@@ -25,11 +25,11 @@ For more details, see [DataShareExtensionAbility](../reference/apis/js-apis-appl
| query(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;DataShareResultSet&gt;): void | Queries data from the database. | | query(uri: string, predicates: DataSharePredicates, columns: Array&lt;string&gt;, callback: AsyncCallback&lt;DataShareResultSet&gt;): void | Queries data from the database. |
| delete(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void | Deletes one or more data records from the database.| | delete(uri: string, predicates: DataSharePredicates, callback: AsyncCallback&lt;number&gt;): void | Deletes one or more data records from the database.|
For more details, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md). For more information, see [DataShareHelper](../reference/apis/js-apis-data-dataShare.md).
## When to Use ## When to Use
There are two roles in **DataShare**. There are two roles in **DataShare**:
- Data provider: adds, deletes, modifies, and queries data, opens files, and shares data. - Data provider: adds, deletes, modifies, and queries data, opens files, and shares data.
- Data consumer: accesses the data provided by the provider using **DataShareHelper**. - Data consumer: accesses the data provided by the provider using **DataShareHelper**.
...@@ -41,10 +41,10 @@ Examples are given below. ...@@ -41,10 +41,10 @@ Examples are given below.
1. Import the dependencies. 1. Import the dependencies.
```ts ```ts
import Extension from '@ohos.application.DataShareExtensionAbility' import Extension from '@ohos.application.DataShareExtensionAbility';
import rdb from '@ohos.data.rdb'; import rdb from '@ohos.data.rdb';
import fileIo from '@ohos.fileio' import fileIo from '@ohos.fileio';
import dataSharePredicates from '@ohos.data.dataSharePredicates' import dataSharePredicates from '@ohos.data.dataSharePredicates';
``` ```
2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API. 2. Override **DataShareExtensionAbility** APIs based on actual requirements. For example, if the data provider provides only data query, override only the **query()** API.
...@@ -80,7 +80,7 @@ Examples are given below. ...@@ -80,7 +80,7 @@ Examples are given below.
} }
// Override the query() API. // Override the query() API.
query(uri, predicates, columns, callback) { query(uri, predicates, columns, callback) {
if (predicates == null || predicates == undefined) { if (predicates == null || predicates == undefined) {
console.info('invalid predicates'); console.info('invalid predicates');
} }
...@@ -144,48 +144,49 @@ Examples are given below. ...@@ -144,48 +144,49 @@ Examples are given below.
let dseUri = ("datashare:///com.samples.datasharetest.DataShare"); let dseUri = ("datashare:///com.samples.datasharetest.DataShare");
``` ```
2. Create a **DataShareHelper** instance. 3. Create a **DataShareHelper** instance.
```ts ```ts
let dsHelper; let dsHelper;
let abilityContext; let abilityContext;
export default class MainAbility extends Ability { export default class MainAbility extends Ability {
onWindowStageCreate(windowStage) { onWindowStageCreate(windowStage) {
abilityContext = this.context; abilityContext = this.context;
dataShare.createDataShareHelper(abilityContext, dseUri, (err,data)=>{ dataShare.createDataShareHelper(abilityContext, dseUri, (err, data)=>{
dsHelper = data; dsHelper = data;
}); });
} }
} }
``` ```
3. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data. 4. Use the APIs provided by **DataShareHelper** to access the services provided by the provider, for example, adding, deleting, modifying, and querying data.
```ts ```ts
// Construct a piece of data. // Construct a piece of data.
var valuesBucket = {"name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1,2,3])}; var valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) };
var updateBucket = {"name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1,2,3])}; var updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) };
let da = new dataSharePredicates.DataSharePredicates(); let da = new dataSharePredicates.DataSharePredicates();
var valArray =new Array("*"); var valArray = new Array("*");
let people = new Array( let people = new Array(
{"name": "LiSi", "age": 41, "Binary": ar}, { "name": "LiSi", "age": 41, "Binary": ar },
{"name": "WangWu", "age": 21, "Binary": arr}, { "name": "WangWu", "age": 21, "Binary": arr },
{"name": "ZhaoLiu", "age": 61, "Binary": arr}); { "name": "ZhaoLiu", "age": 61, "Binary": arr });
// Insert a piece of data. // Insert a piece of data.
dsHelper.insert(dseUri, valuesBucket, (err,data) => { dsHelper.insert(dseUri, valuesBucket, (err, data) => {
console.log("dsHelper insert result: " + data); console.log("dsHelper insert result: " + data);
}); });
// Delete data. // Delete data.
dsHelper.delete(dseUri, da, (err,data) => { dsHelper.delete(dseUri, da, (err, data) => {
console.log("dsHelper delete result: " + data); console.log("dsHelper delete result: " + data);
}); });
// Update data. // Update data.
dsHelper.update(dseUri, da, updateBucket, (err,data) => { dsHelper.update(dseUri, da, updateBucket, (err, data) => {
console.log("dsHelper update result: " + data); console.log("dsHelper update result: " + data);
}); });
// Query data. // Query data.
dsHelper.query(dseUri, da, valArray, (err,data) => { dsHelper.query(dseUri, da, valArray, (err, data) => {
console.log("dsHelper query result: " + data); console.log("dsHelper query result: " + data);
}); });
``` ```
...@@ -2,14 +2,13 @@ ...@@ -2,14 +2,13 @@
## When to Use ## When to Use
Distributed data objects allow data traversing across devices to be processed like local variables by shielding complex data interaction between devices. For the devices that form a Super Device, when data in the distributed data object of an application is added, deleted, or modified on a device, the data for the same application is also updated on the other devices. The devices can listen for data changes and online and offline status changes of other devices. The **distributedDataObject** module provides APIs to implement data collaboration of the same application across multiple devices. In addition, the devices that form a Super Device can listen for object status and data changes with each other.
The distributed data objects support basic data types, such as number, string, and Boolean, as well as complex data types, such as array and nested basic types.
For example, when the data of the a distributed data object is added, deleted, or modified for application A on device 1, application A on device 2 can obtain the updated data. In addition, device 2 can listen for data changes and online/offline of the data objects on device 1.
## 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). For details about the APIs, see [Distributed Data Object](../reference/apis/js-apis-data-distributedobject.md).
### Creating a Distributed Data Object Instance ### Creating a Distributed Data Object Instance
...@@ -17,7 +16,7 @@ Call **createDistributedObject()** to create a distributed data object instance. ...@@ -17,7 +16,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>- **source**: attributes of the **distributedObject** set.<br>- **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.|
...@@ -26,35 +25,36 @@ Call **createDistributedObject()** to create a distributed data object instance. ...@@ -26,35 +25,36 @@ Call **createDistributedObject()** to create a distributed data object instance.
Call **genSessionId()** to generate a session ID randomly. The generated session ID can be used to set the session ID of a distributed data object. Call **genSessionId()** to generate a session ID randomly. The generated session ID can be used to set the session ID of a distributed data object.
**Table 2** API for generating a session ID randomly **Table 2** API for generating a session ID randomly
| Package | API | Description | | Package| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| ohos.data.distributedDataObject| genSessionId(): string | Generates a session ID, which can be used as the session ID of a distributed data object.| | ohos.data.distributedDataObject| genSessionId(): string | Generates a session ID, which can be used as the session ID of a distributed data object.|
### Setting a SessionID for Distributed Data Objects ### Setting a SessionID for a Distributed Data Object
Call **setSessionId()** to set a session ID for a distributed data object. The session ID is a unique identifier for one collaboration across devices. The distributed data objects to be synchronized must be associated with the same session ID. Call **setSessionId()** to set a session ID for a distributed data object. The session ID is a unique identifier for one collaboration across devices. The distributed data objects to be synchronized must be associated with the same session ID.
**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>**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 a distributed data object.<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. In the case of data change, 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.<br>**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 the data changes to unsubscribe from. If this parameter is not specified, all data changes of this distributed data object will be unsubscribed from.|
### Observing Online or Offline Status ### Observing Online or Offline Status
Call **on()** to subscribe to status changes of a distributed data object. The status can be online or offline. When the status changes, a callback will be invoked to return the status. You can use **off()** to unsubscribe from the status changes. Call **on()** to subscribe to status changes of a distributed data object. The status can be online or offline. When the status changes, a callback will be invoked to return the status. You can use **off()** to unsubscribe from the status changes.
**Table 5** APIs for observing status changes of a distributed data object **Table 5** APIs for observing status changes of a distributed data object
| Class | API | Description | | Class| API| Description|
| -------- | -------- | -------- | | -------- | -------- | -------- |
| DistributedDataObject| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to the status changes of a distributed data object.| | DistributedDataObject| on(type: 'status', callback: Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }>): void | Subscribes to the status changes of a distributed data object.|
| DistributedDataObject| off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }>): void | Unsubscribes from status changes of a distributed data object.| | DistributedDataObject| off(type: 'status', callback?: Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }>): void | Unsubscribes from status changes of a distributed data object.|
...@@ -63,7 +63,7 @@ Call **on()** to subscribe to status changes of a distributed data object. The s ...@@ -63,7 +63,7 @@ Call **on()** to subscribe to status changes of a distributed data object. The s
Call **save()** to save a distributed data object. When the application is active, the saved data will not be released. When the application exits and restarts, the data saved on the device will be restored. Call **save()** to save a distributed data object. When the application is active, the saved data will not be released. When the application exits and restarts, the data saved on the device will be restored.
Call **revokeSave()** to revoke a distributed data object that is no longer required. If the distributed data object is saved on the local device, **revokeSave()** will delete the data from all trusted devices. If the distributed data object is not saved on the local device, **revokeSave()** will delete the data from the local device. Call **revokeSave()** to delete a distributed data object that is no longer required. If the distributed data object is saved on the local device, **revokeSave()** will delete the data from all trusted devices. If the distributed data object is not saved on the local device, **revokeSave()** will delete the data from the local device.
The saved data will be released in the following cases: The saved data will be released in the following cases:
...@@ -71,13 +71,11 @@ The saved data will be released in the following cases: ...@@ -71,13 +71,11 @@ 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.|
| 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(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation.|
| DistributedDataObject | revokeSave(callback: AsyncCallback&lt;RevokeSaveSuccessResponse&gt;): void | Revokes the data saving operation. This API uses an asynchronous callback to return the result. |
| DistributedDataObject | revokeSave(): Promise&lt;RevokeSaveSuccessResponse&gt; | Revokes the data saving operation. This API uses a promise to return the result. |
## How to Develop ## How to Develop
...@@ -89,12 +87,14 @@ The following example shows how to implement distributed data object synchroniza ...@@ -89,12 +87,14 @@ The following example shows how to implement distributed data object synchroniza
import distributedObject from '@ohos.data.distributedDataObject'; import distributedObject from '@ohos.data.distributedDataObject';
``` ```
2. Request the permission. 2. Apply for the permission.
Add the required permission (FA model) in the **config.json** file.
The sample code is as follows:
Add the required permission in the **config.json** file. The sample code is as follows: ```json
{
```
{
"module": { "module": {
"reqPermissions": [ "reqPermissions": [
{ {
...@@ -103,106 +103,125 @@ The following example shows how to implement distributed data object synchroniza ...@@ -103,106 +103,125 @@ The following example shows how to implement distributed data object synchroniza
] ]
} }
} }
``` ```
This permission must also be authorized by the user through a dialog box when the application is started for the first time. The sample code is as follows:
For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).
```
This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
```json
import featureAbility from '@ohos.ability.featureAbility'; import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() { function grantPermission() {
console.info('grantPermission'); console.info('grantPermission');
let context = featureAbility.getContext(); let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) { context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`) console.info(`result.requestCode=${result.requestCode}`)
}) })
console.info('end grantPermission'); console.info('end grantPermission');
} }
grantPermission();
``` grantPermission();
```
3. Obtain a distributed data object instance. 3. Obtain a distributed data object instance.
The sample code is as follows: The sample code is as follows:
```js ```js
var local_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, var local_object = distributedObject.createDistributedObject({
parent:undefined, list:undefined}); name: undefined,
age: undefined,
isVis: true,
parent: undefined,
list: undefined
});
var sessionId = distributedObject.genSessionId(); var sessionId = distributedObject.genSessionId();
``` ```
4. Add the distributed data object instance to the synchronization network.
4. Add the synchronization network. The data objects in the synchronization network include the local and remote objects.
The sample code is as follows: The data objects in the synchronization network include the local and remote objects.
The sample code is as follows:
```js ```js
// Local object // Local object
var local_object = distributedObject.createDistributedObject({name:"jack", age:18, isVis:true, var local_object = distributedObject.createDistributedObject({
parent:{mother:"jack mom", father:"jack Dad"}, list:[{mother:"jack mom"}, {father:"jack Dad"}]}); name: "jack",
age: 18,
isVis: true,
parent: { mother: "jack mom", father: "jack Dad" },
list: [{ mother: "jack mom" }, { father: "jack Dad" }]
});
local_object.setSessionId(sessionId); local_object.setSessionId(sessionId);
// Remote object // Remote object
var remote_object = distributedObject.createDistributedObject({name:undefined, age:undefined, isVis:true, var remote_object = distributedObject.createDistributedObject({
parent:undefined, list:undefined}); name: undefined,
remote_object.setSessionId(sessionId); age: undefined,
isVis: true,
parent: undefined,
list: undefined
});
// After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18. // After learning that the device goes online, the remote object synchronizes data. That is, name changes to jack and age to 18.
remote_object.setSessionId(sessionId);
``` ```
5. Observe the data changes of the distributed data object. 5. Observe the data changes of the distributed data object.
You can subscribe to data changes of the peer object. When the data in the peer object changes, a callback will be called to return the data changes. You can subscribe to data changes of the remote object. When the data in the remote object changes, a callback will be called to return the data changes.
The sample code is as follows: The sample code is as follows:
```js ```js
function changeCallback(sessionId, changeData) { function changeCallback(sessionId, changeData) {
console.info("change" + sessionId); console.info("change" + sessionId);
if (changeData != null && changeData != undefined) { if (changeData != null && changeData != undefined) {
changeData.forEach(element => { changeData.forEach(element => {
console.info("changed !" + element + " " + local_object[element]); console.info("changed !" + element + " " + local_object[element]);
}); });
} }
} }
// To refresh the page in changeCallback, correctly bind (this) to the changeCallback. // To refresh the page in changeCallback, correctly bind (this) to the changeCallback.
local_object.on("change", this.changeCallback.bind(this)); local_object.on("change", this.changeCallback.bind(this));
``` ```
6. Modify object attributes. 6. Modify attributes of the distributed data object.
The object attributes support basic data types (such as number, Boolean, and string) and complex data types (array and nested basic types). 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
local_object.name = "jack"; local_object.name = "jack";
local_object.age = 19; local_object.age = 19;
local_object.isVis = false; local_object.isVis = false;
local_object.parent = {mother:"jack mom", father:"jack Dad"}; local_object.parent = { mother: "jack mom", father: "jack Dad" };
local_object.list = [{mother:"jack mom"}, {father:"jack Dad"}]; local_object.list = [{ mother: "jack mom" }, { father: "jack Dad" }];
``` ```
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**<br>
> > For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified. Example:
> For the distributed data object of the complex type, only the root attribute can be modified. The subordinate attributes cannot be modified.
Example:
```js ```js
// Supported modification. // Supported modification.
local_object.parent = {mother:"mom", father:"dad"}; local_object.parent = { mother: "mom", father: "dad" };
// Modification not supported. // Modification not supported.
local_object.parent.mother = "mom"; local_object.parent.mother = "mom";
``` ```
7. Access the distributed data object. 7. Access the distributed data object.
Obtain the distributed data object attribute, which is the latest data on the network. Obtain the distributed data object attributes, which are the latest data on the network.
The sample code is as follows: The sample code is as follows:
```js ```js
console.info("name " + local_object["name"]); console.info("name " + local_object["name"]);
``` ```
...@@ -221,7 +240,6 @@ The following example shows how to implement distributed data object synchroniza ...@@ -221,7 +240,6 @@ The following example shows how to implement distributed data object synchroniza
``` ```
9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline. 9. Subscribe to the status (online/offline) changes of the distributed data object. A callback will be invoked to report the status change when the target distributed data object goes online or offline.
The sample code is as follows: The sample code is as follows:
```js ```js
...@@ -234,53 +252,29 @@ The following example shows how to implement distributed data object synchroniza ...@@ -234,53 +252,29 @@ The following example shows how to implement distributed data object synchroniza
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 ```js
// Save a distributed data object.
``` g_object.save("local").then((result) => {
​```js console.info("save sessionId " + result.sessionId);
// Save a distributed data object. console.info("save version " + result.version);
local_object.save("local", (result, data) => { console.info("save deviceId " + result.deviceId);
console.log("save callback"); }, (result) => {
console.info("save sessionId " + data.sessionId); console.info("save local failed.");
console.info("save version " + data.version); });
console.info("save deviceId " + data.deviceId); // Revoke the data saving operation.
}); g_object.revokeSave().then((result) => {
// Revoke the data saving operation. console.info("revokeSave success.");
local_object.revokeSave((result, data) => { }, (result) => {
console.log("revokeSave callback"); console.info("revokeSave failed.");
console.info("revokeSave sessionId " + data.sessionId); });
}); ```
​```
```
- Promise
```
​```js
// Save a distributed data object.
g_object.save("local").then((result) => {
console.info("save sessionId " + result.sessionId);
console.info("save version " + result.version);
console.info("save deviceId " + result.deviceId);
}, (result)=>{
console.info("save local failed.");
});
// Revoke the data saving operation.
g_object.revokeSave().then((result) => {
console.info("revokeSave success.");
}, (result)=>{
console.info("revokeSave failed.");
});
​```
```
11. Unsubscribe from the status changes of the distributed data object. 11. Unsubscribe from the status changes of the distributed data object.
You can specify the callback to unregister. If you do not specify the callback, this API unregisters all callbacks of this distributed data object. You can specify the callback to unregister. If you do not specify the callback, this API unregisters all status change callbacks of this distributed data object.
The sample code is as follows: The sample code is as follows:
```js ```js
// Unregister the specified status change callback. // Unregister the specified status change callback.
local_object.off("status", this.statusCallback); local_object.off("status", this.statusCallback);
...@@ -288,9 +282,12 @@ The following example shows how to implement distributed data object synchroniza ...@@ -288,9 +282,12 @@ The following example shows how to implement distributed data object synchroniza
local_object.off("status"); local_object.off("status");
``` ```
12. Remove a distributed data object from the synchronization network. Data changes on the local object will not be synchronized to the removed distributed data object. 12. Remove a distributed data object from the synchronization network.
The sample code is as follows: Data changes on the local object will not be synchronized to the removed distributed data object.
```js
local_object.setSessionId(""); The sample code is as follows:
```
```js
local_object.setSessionId("");
```
# Distributed Data Object Overview # Distributed Data Object Overview
The distributed data object management framework is an object-oriented in-memory data management framework. It provides application developers with basic data object management capabilities, such as creating, querying, deleting, modifying, and subscribing to in-memory objects. This management framework also provides distributed capabilities to implement data object collaboration for the same application between multiple devices that form a Super Device. The distributed data object management framework provides object-oriented in-memory data management. It provides basic data management capabilities, such as creating, querying, deleting, and modifying distributed data objects, and observing data and status changes of the distributed data objects. This management framework also provides distributed capabilities to implement data object collaboration for the same application between multiple devices that form a Super Device.
## Key Concepts ## Basic Concepts
- **Distributed in-memory database** - **Distributed in-memory database**
The distributed in-memory database caches data in the memory, so that applications can quickly access data. This database, however, does not store data persistently. If the database is closed, the data is not retained. The distributed in-memory database caches data in the memory so that applications can quickly access data. This database, however, does not store data persistently. If the database is closed, the data is not retained.
- **Distributed data object** - **Distributed data object**
A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading or assigning values to distributed data objects is automatically mapped to the **put** or **get** operation of the corresponding database. A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **put** and **get** operations in the corresponding database, respectively.
The distributed data object can be in the following states in its lifecycle: The distributed data object can be in the following states in its lifecycle:
- **Uninitialized**: The distributed data object is not instantiated or has been destroyed. - **Uninitialized**: The distributed data object is not instantiated or has been destroyed.
- **Local**: The data table is created, but the data cannot be synchronized. - **Local**: The data table is created, but the data cannot be synchronized.
- **Distributed**: The data table is created, there are at least two online with the same session ID, and data can be synchronized across devices. If the device is offline or the session ID is empty, the distributed data object changes to the local state. - **Distributed**: The data table is created, and there are at least two online devices with the same session ID. In this case, data can be synchronized across devices. If a device is offline or the session ID is empty, the distributed data object changes to the local state.
## Working Principles ## Working Principles
The distributed data objects are encapsulated into JS objects in distributed in-memory databases, which allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization. The distributed data objects are encapsulated into JS objects in distributed in-memory databases. This allows the distributed data objects to be operated in the same way as local variables. The system automatically implements cross-device data synchronization.
**Figure 1** Working mechanism **Figure 1** Working mechanism
...@@ -34,7 +34,7 @@ The distributed data objects are encapsulated into JS objects in distributed in- ...@@ -34,7 +34,7 @@ The distributed data objects are encapsulated into JS objects in distributed in-
## Constraints ## Constraints
- Data synchronization can be implemented across devices only for the applications with the same bundleName. - Data synchronization can be implemented across devices only for the applications with the same **bundleName**.
- Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects. - Each distributed data object occupies 100 KB to 150 KB of memory. Therefore, you are advised not to create too many distributed data objects.
......
...@@ -6,113 +6,144 @@ The Distributed Data Service (DDS) implements synchronization of application dat ...@@ -6,113 +6,144 @@ 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). For details about the APIs, see [Distributed Data Management](../reference/apis/js-apis-distributed-data.md).
**Table 1** APIs provided by the DDS **Table 1** APIs provided by the DDS
| API | Description | | API | Description |
| ------------------------------------------------------------ | ----------------------------------------------- | | ------------------------------------------------------------ | ----------------------------------------------- |
| createKVManager(config:KVManagerConfig,callback:AsyncCallback&lt;KVManager&gt;):void<br>createKVManager(config:KVManagerConfig):Promise&lt;KVManager> | Creates a **KVManager** object for database management.| | createKVManager(config: KVManagerConfig, callback: AsyncCallback&lt;KVManager&gt;): void<br>createKVManager(config: KVManagerConfig): Promise&lt;KVManager> | Creates a **KVManager** object for database management.|
| getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options,callback:AsyncCallback&lt;T&gt;):void<br>getKVStore&lt;TextendsKVStore&gt;(storeId:string,options:Options):Promise&lt;T&gt; | Obtains a KV store with the specified **Options** and **storeId**.| | getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options, callback: AsyncCallback&lt;T&gt;): void<br>getKVStore&lt;TextendsKVStore&gt;(storeId: string, options: Options): Promise&lt;T&gt; | Obtains a KV store with the specified **Options** and **storeId**.|
| 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. | | 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. |
| delete(key:string,callback:AsyncCallback&lt;void&gt;):void<br>delete(key:string):Promise&lt;void> | Deletes data. | | delete(key: string, callback: AsyncCallback&lt;void&gt;): void<br>delete(key: string): Promise&lt;void> | Deletes data. |
| get(key:string,callback:AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;):void<br>get(key:string):Promise&lt;Uint8Array\|string\|boolean\|number> | Queries data. | | get(key: string, callback: AsyncCallback&lt;Uint8Array\|string\|boolean\|number&gt;): void<br>get(key: string): Promise&lt;Uint8Array\|string\|boolean\|number> | Queries 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. | | 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. |
| sync(deviceIdList:string[],mode:SyncMode,allowedDelayMs?:number):void | Triggers database synchronization in manual mode. | | sync(deviceIdList: string[], mode: SyncMode, allowedDelayMs?: number): void | Triggers database synchronization in manual mode. |
## How to Develop ## How to Develop
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. Apply for the required permission if data synchronization is required.
2. Create a **KvManager** instance based on the specified **KvManagerConfig** object. Add the permission required (FA model) in the **config.json** file. The sample code is as follows:
(1) Create a **KvManagerConfig** object based on the application context. ```json
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.DISTRIBUTED_DATASYNC"
}
]
}
}
```
For the apps based on the stage model, see [Declaring Permissions](../security/accesstoken-guidelines.md#stage-model).
This permission must also be granted by the user when the application is started for the first time. The sample code is as follows:
```js
import featureAbility from '@ohos.ability.featureAbility';
function grantPermission() {
console.info('grantPermission');
let context = featureAbility.getContext();
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
console.info('end grantPermission');
}
grantPermission();
```
3. Create a **kvManager** instance based on the specified **kvManagerConfig** object.
1. Create a **kvManagerConfig** object based on the application context.
2. Create a **kvManager** instance.
(2) Create a **KvManager** instance.
The sample code is as follows: The sample code is as follows:
``` ```js
let kvManager; let kvManager;
try { try {
const kvManagerConfig = { const kvManagerConfig = {
bundleName : 'com.example.datamanagertest', bundleName: 'com.example.datamanagertest',
userInfo : { userInfo: {
userId : '0', userId: '0',
userType : distributedData.UserType.SAME_USER_ID userType: distributedData.UserType.SAME_USER_ID
}
} }
distributedData.createKVManager(kvManagerConfig, function (err, manager) { }
if (err) { distributedData.createKVManager(kvManagerConfig, function (err, manager) {
console.log("createKVManager err: " + JSON.stringify(err)); if (err) {
return; console.log("createKVManager err: " + JSON.stringify(err));
} return;
console.log("createKVManager success"); }
kvManager = manager; console.log("createKVManager success");
}); kvManager = manager;
});
} catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error: " + e);
} }
``` ```
3. Create and obtain a single KV store.
(1) Declare the ID of the single KV store to create. 4. Create and obtain a single KV store.
(2) Create a single KV store. You are advised to disable automatic synchronization (**autoSync:false**) and call **sync** when a synchronization is required. 1. Declare the ID of the single KV store to create.
2. Create a single KV store. You are advised to disable automatic synchronization (`autoSync:false`) and call `sync` when a synchronization is required.
The sample code is as follows: The sample code is as follows:
```js ```js
let kvStore; let kvStore;
try { try {
const options = { const options = {
createIfMissing : true, createIfMissing: true,
encrypt : false, encrypt: false,
backup : false, backup: false,
autoSync : false, autoSync: false,
kvStoreType : distributedData.KVStoreType.SINGLE_VERSION, kvStoreType: distributedData.KVStoreType.SINGLE_VERSION,
securityLevel : distributedData.SecurityLevel.S0, securityLevel: distributedData.SecurityLevel.S0
}; };
kvManager.getKVStore('storeId', options, function (err, store) { kvManager.getKVStore('storeId', options, function (err, store) {
if (err) { if (err) {
console.log("getKVStore err: " + JSON.stringify(err)); console.log("getKVStore err: " + JSON.stringify(err));
return; return;
} }
console.log("getKVStore success"); console.log("getKVStore success");
kvStore = store; kvStore = store;
}); });
} catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error: " + e);
} }
``` ```
> **NOTE** > **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.
5. Subscribe to changes in the distributed data.
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));
}); });
``` ```
5. Write data to the single KV store. 6. Write data to the single KV store.
(1) Construct the key and value to be written into the single KV store.
(2) Write key-value pairs into the single KV store. 1. Construct the `Key` and `Value` to be written into the single KV store.
2. Write key-value pairs into the single KV store.
The following is the sample code for writing key-value pairs of the string type into the single KV store: The following is the sample code for writing key-value pairs of the string type into the single KV store:
...@@ -120,52 +151,54 @@ The following uses a single KV store as an example to describe the development p ...@@ -120,52 +151,54 @@ The following uses a single KV store as an example to describe the development p
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';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.log("put err: " + JSON.stringify(err)); console.log("put err: " + JSON.stringify(err));
return; return;
} }
console.log("put success"); console.log("put success");
}); });
}catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error: " + e);
} }
``` ```
6. Query data in the single KV store. 7. Query data in the single KV store.
(1) Construct the key to be queried from the single KV store.
(2) Query data from the single KV store. 1. Construct the `Key` to be queried from the single KV store.
2. Query data from the single KV store.
The following is the sample code for querying data of the string type from the single KV store: 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';
try { try {
kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err,data) { kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) {
if (err != undefined) { if (err != undefined) {
console.log("put err: " + JSON.stringify(err)); console.log("put err: " + JSON.stringify(err));
return; return;
} }
console.log("put success"); console.log("put success");
kvStore.get(KEY_TEST_STRING_ELEMENT, function (err,data) { kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) {
console.log("get success data: " + data); console.log("get success data: " + data);
}); });
}); });
}catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error: " + e);
} }
``` ```
7. Synchronize data to other devices.<br/> 8. Synchronize data to other devices.
Select the devices in the same network and the synchronization mode to synchronize data. Select the devices in the same network and the synchronization mode to synchronize data.
> **NOTE** > **NOTE**<br>
> >
> The APIs of the `deviceManager` module are system interfaces. > The APIs of the `deviceManager` module are system interfaces.
The following is the example code for synchronizing data in a single KV store:
The following is the sample code for synchronizing data in a single KV store:
```js ```js
import deviceManager from '@ohos.distributedHardware.deviceManager'; import deviceManager from '@ohos.distributedHardware.deviceManager';
...@@ -185,8 +218,8 @@ The following uses a single KV store as an example to describe the development p ...@@ -185,8 +218,8 @@ The following uses a single KV store as an example to describe the development p
try{ try{
// 1000 indicates that the maximum delay is 1000 ms. // 1000 indicates that the maximum delay is 1000 ms.
kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000); kvStore.sync(deviceIds, distributedData.SyncMode.PUSH_ONLY, 1000);
}catch (e) { } catch (e) {
console.log("An unexpected error occurred. Error:" + e); console.log("An unexpected error occurred. Error: " + e);
} }
} }
}); });
......
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
> **NOTE** > **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. > 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
...@@ -88,8 +88,30 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -88,8 +88,30 @@ Use the following APIs to delete a **Preferences** instance or data file.
2. Obtain a **Preferences** instance. 2. Obtain a **Preferences** instance.
Read the specified file and load its data to the **Preferences** instance for data operations. Read the specified file and load its data to the **Preferences** instance for data operations.
FA model:
```js ```js
let promise = data_preferences.getPreferences(this.context, 'mystore'); // Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
var context = featureAbility.getContext()
let promise = data_preferences.getPreferences(context, 'mystore');
```
Stage model:
```ts
// Obtain the context.
import Ability from '@ohos.application.Ability'
var context
class MainAbility extends Ability{
onWindowStageCreate(windowStage){
context = this.context
}
}
let promise = data_preferences.getPreferences(context, 'mystore');
``` ```
3. Write data. 3. Write data.
...@@ -115,12 +137,12 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -115,12 +137,12 @@ Use the following APIs to delete a **Preferences** instance or data file.
```js ```js
promise.then((preferences) => { promise.then((preferences) => {
let getPromise = preferences.get('startup', 'default'); let getPromise = preferences.get('startup', 'default');
getPromise.then((value) => { getPromise.then((value) => {
console.info("The value of 'startup' is " + value); console.info("The value of 'startup' is " + value);
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the value of 'startup'. Cause: " + err); console.info("Failed to get the value of 'startup'. Cause: " + err);
}) })
}).catch((err) => { }).catch((err) => {
console.info("Failed to get the preferences.") console.info("Failed to get the preferences.")
}); });
...@@ -139,24 +161,24 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -139,24 +161,24 @@ Use the following APIs to delete a **Preferences** instance or data file.
Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data.
```js ```js
var observer = function (key) { var observer = function (key) {
console.info("The key" + key + " changed."); console.info("The key" + key + " changed.");
} }
preferences.on('change', observer); preferences.on('change', observer);
preferences.put('startup', 'auto', function (err) { preferences.put('startup', 'auto', function (err) {
if (err) { if (err) {
console.info("Failed to put the value of 'startup'. Cause: " + err); console.info("Failed to put the value of 'startup'. Cause: " + err);
return; return;
} }
console.info("Put the value of 'startup' successfully."); console.info("Put the value of 'startup' successfully.");
preferences.flush(function (err) { preferences.flush(function (err) {
if (err) { if (err) {
console.info("Failed to flush data. Cause: " + err); console.info("Failed to flush data. Cause: " + err);
return; return;
} }
console.info("Flushed data successfully."); // The observer will be called. console.info("Flushed data successfully."); // The observer will be called.
}) })
}) })
``` ```
7. Delete the specified file. 7. Delete the specified file.
...@@ -164,10 +186,10 @@ Use the following APIs to delete a **Preferences** instance or data file. ...@@ -164,10 +186,10 @@ Use the following APIs to delete a **Preferences** instance or data file.
Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored. Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored.
```js ```js
let proDelete = data_preferences.deletePreferences(context, 'mystore'); let proDelete = data_preferences.deletePreferences(context, 'mystore');
proDelete.then(() => { proDelete.then(() => {
console.info("Deleted data successfully."); console.info("Deleted data successfully.");
}).catch((err) => { }).catch((err) => {
console.info("Failed to delete data. Cause: " + err); console.info("Failed to delete data. Cause: " + err);
}) })
``` ```
...@@ -30,9 +30,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -30,9 +30,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 2** API for inserting data **Table 2** API for inserting data
| Class | API | Description | | Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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>If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.<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>If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.<br>- **table**: name of the target table.<br>- **values**: data to be inserted into the table.|
- **Updating Data** - **Updating Data**
...@@ -40,9 +41,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -40,9 +41,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 3** API for updating data **Table 3** API for updating data
| Class | API | Description |
| Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | update(values:ValuesBucket,predicates:RdbPredicates):Promise&lt;number&gt; | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br/>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **predicates**: conditions for updating data.<br/>Return value: number of rows updated. | | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise&lt;number&gt; | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the result.<br>the number of rows updated.<br>- **values**: data to update, which is stored in **ValuesBucket**.<br>- **predicates**: conditions for updating data.|
- **Deleting Data** - **Deleting Data**
...@@ -50,11 +52,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -50,11 +52,10 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 4** API for deleting data **Table 4** API for deleting data
| Class | API | Description |
| -------- | ------------------------------------------------------ | ------------------------------------------------------------ | | Class | API | Description |
| 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.<br/>Return value: number of rows updated. | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| 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<br>the number of rows updated.<br>- **predicates**: conditions for deleting data.|
- **Querying Data** - **Querying Data**
...@@ -65,10 +66,11 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th ...@@ -65,10 +66,11 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 5** APIs for querying data **Table 5** APIs for querying data
| Class | API | Description | | Class | API | Description |
| -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbStore | query(predicates:RdbPredicates,columns?:Array&lt;string&gt;):Promise&lt;ResultSet&gt; | Queries data from the RDB store based on specified conditions. 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 from the RDB store based on specified conditions. 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;):Promise&lt;ResultSet&gt; | Queries data 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 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 | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array&lt;string&gt;): Promise&lt;ResultSet&gt; | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.<br>- **device**: network ID of the remote device.<br>- **table**: name of the table to be queried.<br>- **predicates**: **RdbPredicates** that specifies the query condition.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.| | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array&lt;string&gt;): Promise&lt;ResultSet&gt; | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.<br>- **device**: network ID of the remote device.<br>- **table**: name of the table to be queried.<br>- **predicates**: **RdbPredicates** that specifies the query condition.<br>- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
### Using Predicates ### Using Predicates
...@@ -81,11 +83,11 @@ The following lists common predicates. For more information about predicates, se ...@@ -81,11 +83,11 @@ The following lists common predicates. For more information about predicates, se
| Class | API | Description | | Class | API | Description |
| ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | | ------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
| RdbPredicates | equalTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| | RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
| RdbPredicates | notEqualTo(field:string,value:ValueType):RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| | RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
| RdbPredicates | or():RdbPredicates | Adds the OR condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.| | RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the OR condition.|
| RdbPredicates | and():RdbPredicates | Adds the AND condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.| | RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** with the AND condition.|
| RdbPredicates | contains(field:string,value:string):RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.| | RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to match a string containing the specified value.<br>- **field**: column name in the database table.<br>- **value**: value to match the **RdbPredicates**.<br>- **RdbPredicates**: **RdbPredicates** object that matches the specified field.|
### Using the Result Set ### Using the Result Set
...@@ -101,12 +103,12 @@ For details about how to use result set APIs, see [Result Set](../reference/apis ...@@ -101,12 +103,12 @@ For details about how to use result set APIs, see [Result Set](../reference/apis
| Class | API | Description | | Class | API | Description |
| --------- | ---------------------------------------------------- | ------------------------------------------ | | --------- | ---------------------------------------------------- | ------------------------------------------ |
| ResultSet | goToFirstRow():boolean | Moves to the first row of the result set. | | ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set. |
| ResultSet | getString(columnIndex:number):string | Obtains the value in the form of a string based on the specified column and current row. | | ResultSet | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. |
| ResultSet | getBlob(columnIndex:number):Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.| | ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.|
| ResultSet | getDouble(columnIndex:number):number | Obtains the value in the form of double based on the specified column and current row. | | ResultSet | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. |
| ResultSet | getLong(columnIndex:number):number | Obtains the value in the form of a long integer based on the specified column and current row. | | ResultSet | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. |
| ResultSet | close():void | Closes the result set. | | ResultSet | close(): void | Closes the result set. |
...@@ -164,7 +166,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -164,7 +166,7 @@ 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): 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.| | 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**
...@@ -172,7 +174,7 @@ You can obtain the distributed table name for a remote device based on the local ...@@ -172,7 +174,7 @@ 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): Promise&lt;void&gt; | Restores an RDB store from a backup file. This API uses a promise to return the result.<br>- **srcName**: name of the backup file used to restore the RDB store.| | RdbStore | restore(srcName: string): Promise&lt;void&gt; | Restores an RDB store from a backup file. This API uses a promise to return the result.<br>- **srcName**: name of the backup file used to restore the RDB store.|
**Transaction** **Transaction**
...@@ -180,9 +182,9 @@ Table 15 Transaction APIs ...@@ -180,9 +182,9 @@ Table 15 Transaction APIs
| Class | API | Description | | Class | API | Description |
| -------- | ----------------------- | --------------------------------- | | -------- | ----------------------- | --------------------------------- |
| RdbStore | beginTransaction():void | Starts the transaction before executing SQL statements.| | RdbStore | beginTransaction(): void | Starts the transaction before executing SQL statements.|
| RdbStore | commit():void | Commits the executed SQL statements. | | RdbStore | commit(): void | Commits the executed SQL statements. |
| RdbStore | rollBack():void | Rolls back the SQL statements that have been executed. | | RdbStore | rollBack(): void | Rolls back the SQL statements that have been executed. |
## How to Develop ## How to Develop
...@@ -200,10 +202,10 @@ Table 15 Transaction APIs ...@@ -200,10 +202,10 @@ Table 15 Transaction APIs
import data_rdb from '@ohos.data.rdb' import data_rdb from '@ohos.data.rdb'
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)"; const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
const STORE_CONFIG = {name: "rdbstore.db"} const STORE_CONFIG = { name: "rdbstore.db" }
data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) { data_rdb.getRdbStore(this.context, STORE_CONFIG, 1, function (err, rdbStore) {
rdbStore.executeSql(CREATE_TABLE_TEST) rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.') console.info('create table done.')
}) })
``` ```
...@@ -217,7 +219,7 @@ Table 15 Transaction APIs ...@@ -217,7 +219,7 @@ Table 15 Transaction APIs
```js ```js
var u8 = new Uint8Array([1, 2, 3]) var u8 = new Uint8Array([1, 2, 3])
const valueBucket = {"name": "Tom", "age": 18, "salary": 100.5, "blobType": u8} const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 }
let insertPromise = rdbStore.insert("test", valueBucket) let insertPromise = rdbStore.insert("test", valueBucket)
``` ```
...@@ -316,6 +318,7 @@ Table 15 Transaction APIs ...@@ -316,6 +318,7 @@ Table 15 Transaction APIs
console.log('device=' + device[i] + 'data changed') console.log('device=' + device[i] + 'data changed')
} }
} }
try { try {
rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver) rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver)
} catch (err) { } catch (err) {
...@@ -366,9 +369,7 @@ Table 15 Transaction APIs ...@@ -366,9 +369,7 @@ Table 15 Transaction APIs
(1) Back up the current RDB store. (1) Back up the current RDB store.
(2) Restore the RDB store using the backup file. The sample code is as follows:
The sample code is as follows:
```js ```js
let promiseBackup = rdbStore.backup("dbBackup.db") let promiseBackup = rdbStore.backup("dbBackup.db")
...@@ -378,6 +379,10 @@ Table 15 Transaction APIs ...@@ -378,6 +379,10 @@ Table 15 Transaction APIs
console.info('Backup failed, err: ' + err) console.info('Backup failed, err: ' + err)
}) })
``` ```
(2) Restore the RDB store using the backup file.
The sample code is as follows:
```js ```js
let promiseRestore = rdbStore.restore("dbBackup.db") let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(() => { promiseRestore.then(() => {
...@@ -386,4 +391,3 @@ Table 15 Transaction APIs ...@@ -386,4 +391,3 @@ Table 15 Transaction APIs
console.info('Restore failed, err: ' + err) console.info('Restore failed, err: ' + err)
}) })
``` ```
...@@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra ...@@ -23,4 +23,4 @@ The vibrator is a Misc device that consists of four modules: Vibrator API, Vibra
## Constraints ## Constraints
When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The sensitivity level of this permission is **system_grant**. When using a vibrator, you must declare the **ohos.permission.VIBRATE** permission before you can control the vibration effect. The authorization mode of this permission is **system_grant**.
# FAQs
- [Ability Framework Development](faqs-ability.md)
- [Graphics and Image Development](faqs-graphics.md)
- [File Management Development](faqs-file-management.md)
- [Data Management Development](faqs-data-management.md)
- [Native API Usage](faqs-native.md)
- [Usage of Third- and Fourth-Party Libraries](faqs-third-party-library.md)
# Ability Framework Development
## Is a guide similar to the Data ability development in the FA model available for the stage model?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
A guide is available for the **DataShareExtensionAbility** class in the stage model, which provides APIs for sharing data with other applications and managing the data.
Reference: [DataShare Development](../database/database-datashare-guidelines.md)
## What should I do if the UI does not respond when an ability is started?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
1. If the ability is started using **startAbility**, check whether the **abilityName** field in **want** uses the bundle name as the prefix. If yes, delete the bundle name.
2. Make sure the ability's home page file configured by **onWindowStageCreate** in the **MainAbility.ts** file is defined in the **main_pages.json** file.
3. You are advised to use the SDK and OpenHarmony SDK versions released on the same day.
Reference: [Release Testing Version](https://gitee.com/openharmony-sig/oh-inner-release-management/blob/master/Release-Testing-Version.md)
## How do I prevent "this" in a method from changing to "undefined" when the method is called?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Method 1: Add **.bind(this)** when calling the method.
Method 2: Use the arrow function.
## What should I do when the message "must have required property 'startWindowIcon'" is displayed?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Configure the **startWindowIcon** attribute under **abilities** in the **module.json5** file.
Reference: [Application Package Structure Configuration File](../quick-start/stage-structure.md)
Example:
```
{
"module": {
// Do something.
"abilities": [{
// Do something.
"startWindowIcon": "$media:space",
"startWindowBackground": "$color:white",
}]
}
}
```
## How do I obtain a notification when the device orientation changes?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Implement the **onConfigurationUpdated** callback in the **Ability** class. The callback is triggered when the system language, color mode, or display parameters (such as the orientation and density) change.
Reference: [Ability Development](../ability/stage-ability.md)
# Device Management Development
## How Do I Save PixelMap data to a database?
Applicable to: OpenHarmony SDK 3.2.3.5
You can convert a **PixelMap** into a **ArrayBuffer** and save the **ArrayBuffer** to your database.
Reference: [readPixelsToBuffer](../reference/apis/js-apis-image.md#readpixelstobuffer7-1)
## How Do I Obtain RDB Store Files?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Run the hdc_std command to copy the .db, .db-shm, and .db-wal files from **/data/app/el2/100/database/Bundle name/entry/db/**, and then use the SQLite tool to open the files.
Example:
```
hdc_std file recv /data/app/el2/100/database/com.xxxx.xxxx/entry/db/test.db ./test.db
```
# File Management Development
## What If There is No Return Value or Error Captured After getAlbums Is Called?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
The **ohos.permission.READ_MEDIA** permission is required for calling **getAlbums**, and this permission needs user authorization. For details, see OpenHarmony [Application Permission List](../security/permission-list.md).
1. Configure the required permission in the **module.json5** file.
```
"requestPermissions": [
{
"name": "ohos.permission.READ_MEDIA"
}
]
```
2. Add the code for user authorization before the **MainAbility.ts -> onWindowStageCreate** page is loaded.
```
private requestPermissions() {
let permissionList: Array<string> = [
"ohos.permission.READ_MEDIA"
];
this.context.requestPermissionsFromUser(permissionList)
.then(data => {
console.info(`request permission data result = ${data.authResults}`)
})
.catch(err => {
console.error(`fail to request permission error:${err}`)
})
}
```
# Graphics and Image Development
## Why do the isStatusBarLightIcon and isNavigationBarLightIcon attributes not take effect when window.setSystemBarProperties() is called?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
In effect, the **isStatusBarLightIcon** and **isNavigationBarLightIcon** attributes turn the font white when set to **true**. If **statusBarContentColor** is also set in **window.setSystemBarProperties()**, the **isStatusBarLightIcon** attribute does not take effect. Similarly, if **navigationBarContentColor** is set, the **isNavigationBarLightIcon** attribute does not take effect.
## How do I set the style of the system bar?
Applicable to: OpenHarmony SDK 3.2.3.5, stage model of API version 9
Import the **\@ohos.window** module, and call **window.setSystemBarProperties()**.
# Native API Usage
## When a native HAP is running, the error message "Obj is not a valid object" is displayed for the imported namespace. What should I do?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
Check the **abiFilters** parameter value in the **build-profile.json5** file in the root directory of the module (not the root directory of the project). If the device is 32-bit, the value must be **armeabi-v7a**. If the device is 64-bit, the value must be **arm64-v8a**.
## How do I obtain the value of version in the package.json file of a module in the C++ code developed using native APIs?
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
1. In the script file **hvigorfile.js** of Hvigor, use **subModule.getPackageJsonPath** to obtain the location of the **package.json** file in the module.
2. Use Node.js to read the **version** field in the **package.json** file and write the value to the **buildOption.cppFlags** field in the **build-profile.json5** file.
Example
```
// Module-level hvigorfile.js
const subModule = require('@ohos/hvigor')(__filename)
const fs = require("fs-extra")
const path = require("path")
const packageJsonPath = subModule.getPackageJsonPath()
const buildProfilePath = path.resolve(packageJsonPath, '../build-profile.json5')
const packageJsonData = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'))
let buildProfileData = fs.readFileSync(buildProfilePath, 'utf8')
buildProfileData = buildProfileData.replace(/\"cppFlags\"\:(.*)\,/, `"cppFlags": "-D NWEBEX_VERSION=${packageJsonData.version}",`)
fs.writeFileSync(buildProfilePath, buildProfileData, 'utf8')
const ohosPlugin = require('@ohos/hvigor-ohos-plugin').hapTasks(subModule) // The plug-in executes the C++ build task and reads the build-profile.json5 file.
module.exports = {
ohos: ohosPlugin
}
```
```
// Read the hello.cpp file.
#define _NWEBEX_VERSION(v) #v
#define _NWEBEX_VER2STR(v) _NWEBEX_VERSION(v)
static napi_value Add(napi_env env, napi_callback_info info)
{
napi_value fixed_version_value = nullptr;
napi_create_string_utf8(env, _NWEBEX_VER2STR(NWEBEX_VERSION), NAPI_AUTO_LENGTH, &fixed_version_value);
return fixed_version_value;
}
```
# Usage of Third- and Fourth-Party Libraries
## What does the following error message mean : "Stage model module... does not support including OpenHarmony npm packages or modules in FA model. OpenHarmony build tasks will not be executed, and OpenHarmony resources will not be packed."
Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9
The third- and fourth-party libraries are not yet compatible with the stage model of API version 9 and cannot be used.
...@@ -54,7 +54,7 @@ await cameraManager.getCameras((err, cameras) => { ...@@ -54,7 +54,7 @@ await cameraManager.getCameras((err, cameras) => {
cameraArray = cameras cameraArray = cameras
}) })
for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex) { for(let cameraIndex = 0; cameraIndex < cameraArray.length; cameraIndex++) {
console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID. console.log('cameraId : ' + cameraArray[cameraIndex].cameraId) // Obtain the camera ID.
console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position. console.log('cameraPosition : ' + cameraArray[cameraIndex].cameraPosition) // Obtain the camera position.
console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type. console.log('cameraType : ' + cameraArray[cameraIndex].cameraType) // Obtain the camera type.
......
...@@ -285,7 +285,7 @@ You can implement page redirection through the page router, which finds the targ ...@@ -285,7 +285,7 @@ You can implement page redirection through the page router, which finds the targ
1. Connect the development board running the OpenHarmony standard system to the computer. 1. Connect the development board running the OpenHarmony standard system to the computer.
2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signaure**. Wait until the automatic signing is complete, and click **OK**. See the following figure. 2. Choose **File** > **Project Structure...** > **Project** > **SigningConfigs**, and select **Automatically generate signature**. Wait until the automatic signing is complete, and click **OK**. See the following figure.
![06](figures/06.png) ![06](figures/06.png)
......
...@@ -5,8 +5,8 @@ The **AbilityContext** module, inherited from **Context**, implements the contex ...@@ -5,8 +5,8 @@ The **AbilityContext** module, inherited from **Context**, implements the contex
This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a dialog box. This module provides APIs for accessing ability-specific resources. You can use the APIs to start and terminate an ability, obtain the caller interface, and request permissions from users by displaying a dialog box.
> **NOTE** > **NOTE**
> >
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version.
> The APIs of this module can be used only in the stage model. > The APIs of this module can be used only in the stage model.
## Usage ## Usage
...@@ -78,7 +78,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca ...@@ -78,7 +78,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```js ```js
var want = { var want = {
"deviceId": "", "deviceId": "",
...@@ -127,7 +127,7 @@ Starts an ability. This API uses a promise to return the result. ...@@ -127,7 +127,7 @@ Starts an ability. This API uses a promise to return the result.
windowMode: 0, windowMode: 0,
}; };
this.context.startAbility(want, options) this.context.startAbility(want, options)
.then((data) => { .then(() => {
console.log('Operation successful.') console.log('Operation successful.')
}).catch((error) => { }).catch((error) => {
console.log('Operation failed.'); console.log('Operation failed.');
...@@ -407,8 +407,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re ...@@ -407,8 +407,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re
"abilityName": "MainAbility" "abilityName": "MainAbility"
}; };
this.context.startServiceExtensionAbility(want) this.context.startServiceExtensionAbility(want)
.then((data) => { .then(() => {
console.log('---------- startServiceExtensionAbility success, data: -----------', data); console.log('---------- startServiceExtensionAbility success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- startServiceExtensionAbility fail, err: -----------', err); console.log('---------- startServiceExtensionAbility fail, err: -----------', err);
...@@ -477,8 +477,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ...@@ -477,8 +477,8 @@ Starts a new Service Extension ability with the account ID specified. This API u
}; };
var accountId = 100; var accountId = 100;
this.context.startServiceExtensionAbilityWithAccount(want,accountId) this.context.startServiceExtensionAbilityWithAccount(want,accountId)
.then((data) => { .then(() => {
console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data); console.log('---------- startServiceExtensionAbilityWithAccount success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err); console.log('---------- startServiceExtensionAbilityWithAccount fail, err: -----------', err);
...@@ -539,8 +539,8 @@ Stops a Service Extension ability in the same application. This API uses a promi ...@@ -539,8 +539,8 @@ Stops a Service Extension ability in the same application. This API uses a promi
"abilityName": "MainAbility" "abilityName": "MainAbility"
}; };
this.context.stopServiceExtensionAbility(want) this.context.stopServiceExtensionAbility(want)
.then((data) => { .then(() => {
console.log('---------- stopServiceExtensionAbility success, data: -----------', data); console.log('---------- stopServiceExtensionAbility success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- stopServiceExtensionAbility fail, err: -----------', err); console.log('---------- stopServiceExtensionAbility fail, err: -----------', err);
...@@ -610,8 +610,8 @@ Stops a Service Extension ability in the same application with the account ID sp ...@@ -610,8 +610,8 @@ Stops a Service Extension ability in the same application with the account ID sp
}; };
var accountId = 100; var accountId = 100;
this.context.stopServiceExtensionAbilityWithAccount(want,accountId) this.context.stopServiceExtensionAbilityWithAccount(want,accountId)
.then((data) => { .then(() => {
console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data); console.log('---------- stopServiceExtensionAbilityWithAccount success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err); console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err);
...@@ -658,8 +658,8 @@ Terminates this ability. This API uses a promise to return the result. ...@@ -658,8 +658,8 @@ Terminates this ability. This API uses a promise to return the result.
**Example** **Example**
```js ```js
this.context.terminateSelf().then((data) => { this.context.terminateSelf().then(() => {
console.log('success:' + JSON.stringify(data)); console.log('success');
}).catch((error) => { }).catch((error) => {
console.log('failed:' + JSON.stringify(error)); console.log('failed:' + JSON.stringify(error));
}); });
...@@ -848,11 +848,11 @@ Disconnects a connection. This API uses a promise to return the result. ...@@ -848,11 +848,11 @@ Disconnects a connection. This API uses a promise to return the result.
| Promise\<void> | Promise used to return the result.| | Promise\<void> | Promise used to return the result.|
**Example** **Example**
```js ```js
var connectionNumber = 0; var connectionNumber = 0;
this.context.disconnectAbility(connectionNumber).then((data) => { this.context.disconnectAbility(connectionNumber).then(() => {
console.log('disconnectAbility success, data: ', data); console.log('disconnectAbility success');
}).catch((err) => { }).catch((err) => {
console.log('disconnectAbility fail, err: ', err); console.log('disconnectAbility fail, err: ', err);
}); });
...@@ -888,7 +888,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r ...@@ -888,7 +888,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r
startAbilityByCall(want: Want): Promise&lt;Caller&gt;; startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
Starts an ability in the foreground or background and obtains the caller interface for communication with the ability. Starts an ability in the foreground or background and obtains the caller object for communicating with the ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.Core **System capability**: SystemCapability.Ability.AbilityRuntime.Core
...@@ -905,11 +905,11 @@ Starts an ability in the foreground or background and obtains the caller interfa ...@@ -905,11 +905,11 @@ Starts an ability in the foreground or background and obtains the caller interfa
| Promise&lt;Caller&gt; | Promise used to return the caller object to communicate with.| | Promise&lt;Caller&gt; | Promise used to return the caller object to communicate with.|
**Example** **Example**
```js ```js
let caller = undefined; let caller = undefined;
// Start an ability in the background without passing parameters. // Start an ability in the background by not passing parameters.
var wantBackground = { var wantBackground = {
bundleName: "com.example.myservice", bundleName: "com.example.myservice",
moduleName: "entry", moduleName: "entry",
...@@ -1050,8 +1050,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu ...@@ -1050,8 +1050,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu
windowMode: 0, windowMode: 0,
}; };
this.context.startAbilityWithAccount(want, accountId, options) this.context.startAbilityWithAccount(want, accountId, options)
.then((data) => { .then(() => {
console.log('---------- startAbilityWithAccount success, data: -----------', data); console.log('---------- startAbilityWithAccount success -----------');
}) })
.catch((err) => { .catch((err) => {
console.log('---------- startAbilityWithAccount fail, err: -----------', err); console.log('---------- startAbilityWithAccount fail, err: -----------', err);
...@@ -1074,13 +1074,13 @@ Requests permissions from the user by displaying a dialog box. This API uses an ...@@ -1074,13 +1074,13 @@ Requests permissions from the user by displaying a dialog box. This API uses an
| callback | AsyncCallback&lt;[PermissionRequestResult](js-apis-permissionrequestresult.md)&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;[PermissionRequestResult](js-apis-permissionrequestresult.md)&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```js ```js
var permissions=['com.example.permission'] var permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions,(result) => { this.context.requestPermissionsFromUser(permissions,(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
}); });
``` ```
...@@ -1105,7 +1105,7 @@ Requests permissions from the user by displaying a dialog box. This API uses a p ...@@ -1105,7 +1105,7 @@ Requests permissions from the user by displaying a dialog box. This API uses a p
| Promise&lt;[PermissionRequestResult](js-apis-permissionrequestresult.md)&gt; | Promise used to return the result.| | Promise&lt;[PermissionRequestResult](js-apis-permissionrequestresult.md)&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
var permissions=['com.example.permission'] var permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions).then((data) => { this.context.requestPermissionsFromUser(permissions).then((data) => {
...@@ -1133,7 +1133,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call ...@@ -1133,7 +1133,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.| | callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example** **Example**
```js ```js
this.context.setMissionLabel("test",(result) => { this.context.setMissionLabel("test",(result) => {
console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); console.log('requestPermissionsFromUserresult:' + JSON.stringify(result));
...@@ -1162,10 +1162,10 @@ Sets a label for this ability in the mission. This API uses a promise to return ...@@ -1162,10 +1162,10 @@ Sets a label for this ability in the mission. This API uses a promise to return
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
this.context.setMissionLabel("test").then((data) => { this.context.setMissionLabel("test").then(() => {
console.log('success:' + JSON.stringify(data)); console.log('success');
}).catch((error) => { }).catch((error) => {
console.log('failed:' + JSON.stringify(error)); console.log('failed:' + JSON.stringify(error));
}); });
...@@ -1188,7 +1188,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call ...@@ -1188,7 +1188,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.| | callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example** **Example**
```js ```js
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image'
var imagePixelMap; var imagePixelMap;
...@@ -1235,7 +1235,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return ...@@ -1235,7 +1235,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return
| Promise&lt;void&gt; | Promise used to return the result.| | Promise&lt;void&gt; | Promise used to return the result.|
**Example** **Example**
```js ```js
import image from '@ohos.multimedia.image' import image from '@ohos.multimedia.image'
var imagePixelMap; var imagePixelMap;
...@@ -1254,8 +1254,8 @@ Sets an icon for this ability in the mission. This API uses a promise to return ...@@ -1254,8 +1254,8 @@ Sets an icon for this ability in the mission. This API uses a promise to return
console.log('--------- createPixelMap fail, err: ---------', err) console.log('--------- createPixelMap fail, err: ---------', err)
}); });
this.context.setMissionIcon(imagePixelMap) this.context.setMissionIcon(imagePixelMap)
.then((data) => { .then(() => {
console.log('-------------- setMissionIcon success, data: -------------', data); console.log('-------------- setMissionIcon success -------------');
}) })
.catch((err) => { .catch((err) => {
console.log('-------------- setMissionIcon fail, err: -------------', err); console.log('-------------- setMissionIcon fail, err: -------------', err);
......
...@@ -32,7 +32,7 @@ Enumerates the action constants of the **Want** object. ...@@ -32,7 +32,7 @@ Enumerates the action constants of the **Want** object.
| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | | ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. |
| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | | ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. |
| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. | | ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. |
| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for openning a contact or picture. | | ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for opening a contact or picture. |
| ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | Action of launching the UI for photographing. | | ACTION_IMAGE_CAPTURE<sup>8+</sup> | ohos.want.action.imageCapture | Action of launching the UI for photographing. |
| ACTION_VIDEO_CAPTURE<sup>8+</sup> | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | | ACTION_VIDEO_CAPTURE<sup>8+</sup> | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. |
| ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. | | ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. |
......
...@@ -49,6 +49,7 @@ import Want from '@ohos.application.Want'; ...@@ -49,6 +49,7 @@ import Want from '@ohos.application.Want';
- Passing a file descriptor (FD) - Passing a file descriptor (FD)
``` js ``` js
import fileio from '@ohos.fileio';
var fd; var fd;
try { try {
fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); fd = fileio.openSync("/data/storage/el2/base/haps/pic.png");
...@@ -59,9 +60,9 @@ import Want from '@ohos.application.Want'; ...@@ -59,9 +60,9 @@ import Want from '@ohos.application.Want';
"deviceId": "", // An empty deviceId indicates the local device. "deviceId": "", // An empty deviceId indicates the local device.
"bundleName": "com.extreme.test", "bundleName": "com.extreme.test",
"abilityName": "MainAbility", "abilityName": "MainAbility",
"moduleName": "entry" // moduleName is optional. "moduleName": "entry", // moduleName is optional.
"parameters": { "parameters": {
"keyFd":{"type":"FD", "value":fd} "keyFd":{"type":"FD", "value":fd}
} }
}; };
this.context.startAbility(want, (error) => { this.context.startAbility(want, (error) => {
......
...@@ -25,56 +25,25 @@ import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; ...@@ -25,56 +25,25 @@ import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility';
## WindowExtensionAbility.onConnect ## WindowExtensionAbility.onConnect
onConnect(want: Want): rpc.RemoteObject onConnect(want: Want): void
Called when this Window Extension ability is connected to an ability for the first time. Called when this Window Extension ability is connected to an ability for the first time.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. | | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.|
**Return value**
| Type | Description |
| ----------------------------------------------- | -------------------- |
| [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Proxy of this Window Extension ability.|
**Example** **Example**
```ts ```ts
import rpc from '@ohos.rpc';
class StubTest extends rpc.RemoteObject {
constructor(des) {
super(des);
}
onRemoteRequest(code, data, reply, option) {
return true;
}
queryLocalInterface(descriptor) {
return null;
}
getInterfaceDescriptor() {
return "";
}
sendRequest(code, data, reply, options) {
return null;
}
getCallingPid() {
return 1;
}
getCallingUid() {
return 1;
}
attachLocalInterface(localInterface, descriptor){}
}
export default class MyWindowExtensionAbility extends WindowExtensionAbility { export default class MyWindowExtensionAbility extends WindowExtensionAbility {
onConnect(want): rpc.RemoteObject { onConnect(want) {
console.info('WindowExtAbility onConnect ' + want.abilityName); console.info('WindowExtAbility onConnect ' + want.abilityName);
return new StubTest("test");
} }
} }
...@@ -88,9 +57,11 @@ Called when this Window Extension ability is disconnected from all connected abi ...@@ -88,9 +57,11 @@ Called when this Window Extension ability is disconnected from all connected abi
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name. | | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.|
**Example** **Example**
...@@ -105,7 +76,6 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility { ...@@ -105,7 +76,6 @@ export default class MyWindowExtensionAbility extends WindowExtensionAbility {
} }
``` ```
## WindowExtensionAbility.onWindowReady ## WindowExtensionAbility.onWindowReady
onWindowReady(window: Window): void onWindowReady(window: Window): void
...@@ -114,6 +84,8 @@ Called when a window is ready. ...@@ -114,6 +84,8 @@ Called when a window is ready.
**System capability**: SystemCapability.WindowManager.WindowManager.Core **System capability**: SystemCapability.WindowManager.WindowManager.Core
**Parameters**
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| window | [Window](js-apis-window.md) | Yes| Current **Window** instance.| | window | [Window](js-apis-window.md) | Yes| Current **Window** instance.|
......
...@@ -26,7 +26,7 @@ Callback of the common event of a static subscriber. ...@@ -26,7 +26,7 @@ Callback of the common event of a static subscriber.
| Name| Type| Mandatory| Description| | Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| event | CommonEventData | Yes| Common event of a static subscriber.| | event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.|
**Example** **Example**
......
...@@ -4911,7 +4911,7 @@ audioCapturer.getBufferSize().then((data) => { ...@@ -4911,7 +4911,7 @@ audioCapturer.getBufferSize().then((data) => {
console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`);
bufferSize = data; bufferSize = data;
}).catch((err) => { }).catch((err) => {
console.error(`AudioFrameworkRecLog: getBufferSize: EROOR: ${err}`); console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`);
}); });
audioCapturer.read(bufferSize, true, async(err, buffer) => { audioCapturer.read(bufferSize, true, async(err, buffer) => {
if (!err) { if (!err) {
......
...@@ -2810,10 +2810,11 @@ This is a system API. ...@@ -2810,10 +2810,11 @@ This is a system API.
| Name | Value | Description | | Name | Value | Description |
| -------------------- | ---- | ------------ | | -------------------- | ---- | ------------ |
| DEVICE_EARPIECE | 0 | Headset device. | | DEVICE_EARPIECE | 0 | Earpiece. |
| DEVICE_SPEAKER | 1 | Speaker device.| | DEVICE_SPEAKER | 1 | Speaker.|
| DEVICE_WIRED_HEADSET | 2 | Wired headset device.| | DEVICE_WIRED_HEADSET | 2 | Wired headset.|
| DEVICE_BLUETOOTH_SCO | 3 | Bluetooth SCO device. | | DEVICE_BLUETOOTH_SCO | 3 | Bluetooth SCO device. |
| DEVICE_MIC | 4 | Microphone. |
## CallRestrictionType<sup>8+</sup> ## CallRestrictionType<sup>8+</sup>
......
...@@ -631,7 +631,7 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the resu ...@@ -631,7 +631,7 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the resu
**Example** **Example**
```js ```js
cameraManager.createPreviewOutput(profile, survaceId).then((previewoutput) => { cameraManager.createPreviewOutput(profile, surfaceId).then((previewoutput) => {
console.log('Promise returned with previewOutput created.'); console.log('Promise returned with previewOutput created.');
}) })
``` ```
...@@ -2262,7 +2262,7 @@ cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(er ...@@ -2262,7 +2262,7 @@ cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(er
console.log(`Failed to check exposure mode supported ${err.message}`); console.log(`Failed to check exposure mode supported ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of isExposureModeSupported'); console.log('Callback returned with the successful execution of isExposureModeSupported');
}) })
``` ```
...@@ -2365,7 +2365,7 @@ cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { ...@@ -2365,7 +2365,7 @@ cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => {
console.log(`Failed to set the exposure mode ${err.message}`); console.log(`Failed to set the exposure mode ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setExposureMode'); console.log('Callback returned with the successful execution of setExposureMode');
}) })
``` ```
...@@ -2464,7 +2464,7 @@ cameraInput.setMeteringPoint(Point1,(err) => { ...@@ -2464,7 +2464,7 @@ cameraInput.setMeteringPoint(Point1,(err) => {
console.log(`Failed to set the exposure point ${err.message}`); console.log(`Failed to set the exposure point ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setMeteringPoint'); console.log('Callback returned with the successful execution of setMeteringPoint');
}) })
``` ```
...@@ -2571,7 +2571,7 @@ cameraInput.setExposureBias(-4,(err) => { ...@@ -2571,7 +2571,7 @@ cameraInput.setExposureBias(-4,(err) => {
console.log(`Failed to set the exposure bias ${err.message}`); console.log(`Failed to set the exposure bias ${err.message}`);
return ; return ;
} }
console.log('Callback returned with the successful excution of setExposureBias'); console.log('Callback returned with the successful execution of setExposureBias');
}) })
``` ```
...@@ -3545,7 +3545,7 @@ previewOutput.stop((err) => { ...@@ -3545,7 +3545,7 @@ previewOutput.stop((err) => {
console.error(`Failed to stop the previewOutput. ${err.message}`); console.error(`Failed to stop the previewOutput. ${err.message}`);
return; return;
} }
console.log('Callback returned with previewOutput stoped.'); console.log('Callback returned with previewOutput stopped.');
}) })
``` ```
...@@ -3567,7 +3567,7 @@ Stops outputting preview streams. This API uses a promise to return the result. ...@@ -3567,7 +3567,7 @@ Stops outputting preview streams. This API uses a promise to return the result.
```js ```js
previewOutput.stop().then(() => { previewOutput.stop().then(() => {
console.log('Callback returned with previewOutput stoped.'); console.log('Callback returned with previewOutput stopped.');
}) })
``` ```
...@@ -4476,7 +4476,7 @@ metadataOutput.stop((err) => { ...@@ -4476,7 +4476,7 @@ metadataOutput.stop((err) => {
console.error(`Failed to stop the metadataOutput. ${err.message}`); console.error(`Failed to stop the metadataOutput. ${err.message}`);
return; return;
} }
console.log('Callback returned with metadataOutput stoped.'); console.log('Callback returned with metadataOutput stopped.');
}) })
``` ```
...@@ -4498,7 +4498,7 @@ Stops outputting metadata. This API uses a promise to return the result. ...@@ -4498,7 +4498,7 @@ Stops outputting metadata. This API uses a promise to return the result.
```js ```js
metadataOutput.stop().then(() => { metadataOutput.stop().then(() => {
console.log('Callback returned with metadataOutput stoped.'); console.log('Callback returned with metadataOutput stopped.');
}) })
``` ```
......
...@@ -119,6 +119,25 @@ Subscribes to device connection events. This API uses an asynchronous callback t ...@@ -119,6 +119,25 @@ Subscribes to device connection events. This API uses an asynchronous callback t
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect9) instead. > This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondeviceconnect9) instead.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceConnect**.|
| callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | Yes| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.|
**Example**
```js
continuationManager.on("deviceConnect", (data) => {
console.info('onDeviceConnect deviceId: ' + JSON.stringify(data.id));
console.info('onDeviceConnect deviceType: ' + JSON.stringify(data.type));
console.info('onDeviceConnect deviceName: ' + JSON.stringify(data.name));
});
```
## continuationManager.on("deviceDisconnect")<sup>(deprecated)</sup> ## continuationManager.on("deviceDisconnect")<sup>(deprecated)</sup>
on(type: "deviceDisconnect", callback: Callback\<string>): void; on(type: "deviceDisconnect", callback: Callback\<string>): void;
...@@ -127,6 +146,23 @@ Subscribes to device disconnection events. This API uses an asynchronous callbac ...@@ -127,6 +146,23 @@ Subscribes to device disconnection events. This API uses an asynchronous callbac
> This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect9) instead. > This API is deprecated since API version 9. You are advised to use [on](#continuationmanagerondevicedisconnect9) instead.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.|
| callback | Callback\<string> | Yes| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.|
**Example**
```js
continuationManager.on("deviceDisconnect", (data) => {
console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data));
});
```
## continuationManager.off("deviceConnect")<sup>(deprecated)</sup> ## continuationManager.off("deviceConnect")<sup>(deprecated)</sup>
off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void; off(type: "deviceConnect", callback?: Callback\<ContinuationResult>): void;
...@@ -135,6 +171,25 @@ Unsubscribes from device connection events. This API uses an asynchronous callba ...@@ -135,6 +171,25 @@ Unsubscribes from device connection events. This API uses an asynchronous callba
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect9) instead. > This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdeviceconnect9) instead.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceConnect**.|
| callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | No| Callback invoked when a device is selected from the device list provided by the device selection module. This callback returns the device ID, type, and name.|
**Example**
```js
continuationManager.off("deviceConnect", (data) => {
console.info('onDeviceConnect deviceId: ' + JSON.stringify(data.id));
console.info('onDeviceConnect deviceType: ' + JSON.stringify(data.type));
console.info('onDeviceConnect deviceName: ' + JSON.stringify(data.name));
});
```
## continuationManager.off("deviceDisconnect")<sup>(deprecated)</sup> ## continuationManager.off("deviceDisconnect")<sup>(deprecated)</sup>
off(type: "deviceDisconnect", callback?: Callback\<string>): void; off(type: "deviceDisconnect", callback?: Callback\<string>): void;
...@@ -143,6 +198,23 @@ Unsubscribes from device disconnection events. This API uses an asynchronous cal ...@@ -143,6 +198,23 @@ Unsubscribes from device disconnection events. This API uses an asynchronous cal
> This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect9) instead. > This API is deprecated since API version 9. You are advised to use [off](#continuationmanageroffdevicedisconnect9) instead.
**System capability**: SystemCapability.Ability.DistributedAbilityManager
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| type | string | Yes| Event type. The value is fixed at **deviceDisconnect**.|
| callback | Callback\<string> | No| Callback invoked when a device is disconnected in the device selection module. This callback returns the device ID.|
**Example**
```js
continuationManager.off("deviceDisconnect", (data) => {
console.info('onDeviceDisconnect deviceId: ' + JSON.stringify(data));
});
```
## continuationManager.on("deviceConnect")<sup>9+</sup> ## continuationManager.on("deviceConnect")<sup>9+</sup>
on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void; on(type: "deviceConnect", token: number, callback: Callback\<Array\<ContinuationResult>>): void;
......
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册