提交 b84380ce 编写于 作者: G Gloria

Update docs against 16094

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 930e2a61
# Multi-device Collaboration (System Applications Only)
# Multi-device Collaboration (for System Applications Only)
## When to Use
......@@ -47,19 +47,19 @@ On device A, touch the **Start** button provided by the initiator application to
### How to Develop
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md#stage-model).
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
```ts
requestPermission() {
let context = this.context;
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
})
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error))
})
}
```
......@@ -129,19 +129,19 @@ On device A, touch the **Start** button provided by the initiator application to
### How to Develop
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Applying for Permissions](../security/accesstoken-guidelines.md#stage-model).
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
```ts
requestPermission() {
let context = this.context;
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
})
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error))
})
}
```
......@@ -218,19 +218,31 @@ A system application can connect to a service on another device by calling [conn
### How to Develop
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
1. Configure the data synchronization permission in the **module.json5** file. The sample code is as follows:
```json
{
"module": {
"requestPermissions":[
{
"name" : "ohos.permission.DISTRIBUTED_DATASYNC",
}
]
}
}
```
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
```ts
requestPermission() {
let context = this.context;
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
})
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error))
})
}
```
......@@ -279,10 +291,10 @@ A system application can connect to a service on another device by calling [conn
});
},
onDisconnect(elementName) {
console.info('onDisconnect callback');
console.info('onDisconnect callback')
},
onFailed(code) {
console.info('onFailed callback');
console.info('onFailed callback')
}
}
// The ID returned after the connection is set up must be saved. The ID will be passed for service disconnection.
......@@ -305,7 +317,7 @@ A system application can connect to a service on another device by calling [conn
## Using Cross-Device Ability Call
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction).
The basic principle of cross-device ability call is the same as that of intra-device ability call. For details, see [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](uiability-intra-device-interaction.md#using-ability-call-to-implement-uiability-interaction-for-system-applications-only).
The following describes how to implement multi-device collaboration through cross-device ability call.
......@@ -319,45 +331,56 @@ The following describes how to implement multi-device collaboration through cros
| startAbilityByCall(want: Want): Promise&lt;Caller&gt;; | Starts a UIAbility in the foreground or background and obtains the caller object for communicating with the UIAbility.|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.|
| call(method: string, data: rpc.Sequenceable): Promise&lt;void&gt; | Sends agreed sequenceable data to the callee ability.|
| callWithResult(method: string, data: rpc.Sequenceable): Promise&lt;rpc.MessageParcel&gt; | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.|
| call(method: string, data: rpc.Parcelable): Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.|
| callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.|
| release(): void | Releases the caller object.|
| on(type:&nbsp;"release",&nbsp;callback:&nbsp;OnReleaseCallback):&nbsp;void | Callback invoked when the caller object is released.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
### How to Develop
1. Request the **ohos.permission.DISTRIBUTED_DATASYNC** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
1. Configure the data synchronization permission in the **module.json5** file. The sample code is as follows:
```json
{
"module": {
"requestPermissions":[
{
"name" : "ohos.permission.DISTRIBUTED_DATASYNC",
}
]
}
}
```
2. Request the data synchronization permission. The sample code for displaying a dialog box to request the permission is as follows:
```ts
requestPermission() {
let context = this.context;
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC'];
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data));
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error));
})
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
console.info("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => {
console.info("Failed to request permission from user with error: "+ JSON.stringify(error))
})
}
```
3. Create the 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.
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 launch type of the UIAbility.
Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
| JSON Field| Description|
| -------- | -------- |
| "launchType"| Ability launch type. Set this parameter to **singleton**.|
| "launchType"| Ability launch type. Set this parameter to **singleton**.|
An example of the UIAbility configuration is as follows:
```json
"abilities":[{
"name": ".CalleeAbility",
......@@ -371,17 +394,17 @@ The following describes how to implement multi-device collaboration through cros
```
2. Import the **UIAbility** module.
```ts
import Ability from '@ohos.app.ability.UIAbility';
import Ability from '@ohos.app.ability.UIAbility'
```
3. Define the agreed parcelable data.
3. Define the agreed sequenceable data.
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 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.
```ts
export default class MySequenceable {
export default class MyParcelable {
num: number = 0
str: string = ""
......@@ -390,24 +413,24 @@ The following describes how to implement multi-device collaboration through cros
this.str = string
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num)
messageParcel.writeString(this.str)
marshalling(messageSequence) {
messageSequence.writeInt(this.num)
messageSequence.writeString(this.str)
return true
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt()
this.str = messageParcel.readString()
unmarshalling(messageSequence) {
this.num = messageSequence.readInt()
this.str = messageSequence.readString()
return true
}
}
```
4. Implement **Callee.on** and **Callee.off**.
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.
4. Implement **Callee.on** and **Callee.off**.
In the following example, the **MSG_SEND_METHOD** listener is registered in **onCreate()** of the ability and deregistered in **onDestroy()**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements.
```ts
const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg'
......@@ -415,14 +438,14 @@ The following describes how to implement multi-device collaboration through cros
function sendMsgCallback(data) {
console.info('CalleeSortFunc called')
// Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '')
data.readSequenceable(receivedData)
// Obtain the parcelable data sent by the caller ability.
let receivedData = new MyParcelable(0, '')
data.readParcelable(receivedData)
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// Process the data.
// Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`)
// Return the parcelable data result to the caller ability.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`)
}
export default class CalleeAbility extends Ability {
......@@ -436,7 +459,7 @@ The following describes how to implement multi-device collaboration through cros
onDestroy() {
try {
this.callee.off(MSG_SEND_METHOD)
this.callee.off(MSG_SEND_METHOD)
} catch (error) {
console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`)
}
......@@ -448,14 +471,13 @@ The following describes how to implement multi-device collaboration through cros
1. Import the **UIAbility** module.
```ts
import Ability from '@ohos.app.ability.UIAbility';
import Ability from '@ohos.app.ability.UIAbility'
```
2. Obtain the caller object.
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.
```ts
async onButtonGetRemoteCaller() {
var caller = undefined
......@@ -469,7 +491,7 @@ The following describes how to implement multi-device collaboration through cros
if (data != null) {
caller = data
console.info('get remote caller success')
// Register the onRelease() listener of the caller ability.
// 注册caller的release监听
caller.onRelease((msg) => {
console.info(`remote caller onRelease is called ${msg}`)
})
......@@ -483,38 +505,39 @@ The following describes how to implement multi-device collaboration through cros
For details about how to implement **getRemoteDeviceId()**, see [Starting UIAbility and ServiceExtensionAbility Across Devices (No Data Returned)](#starting-uiability-and-serviceextensionability-across-devices-no-data-returned).
5. Sends agreed sequenceable data to the callee ability.
1. 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.
5. Sends agreed parcelable data to the callee ability.
1. The parcelable data can be sent to the callee ability with or without a return value. The method and parcelable data must be consistent with those of the callee ability. The following example describes how to send data to the callee ability.
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg';
const MSG_SEND_METHOD: string = 'CallSendMsg'
async onButtonCall() {
try {
let msg = new MySequenceable(1, 'origin_Msg');
await this.caller.call(MSG_SEND_METHOD, msg);
let msg = new MyParcelable(1, 'origin_Msg')
await this.caller.call(MSG_SEND_METHOD, msg)
} catch (error) {
console.info(`caller call failed with ${error}`);
console.info(`caller call failed with ${error}`)
}
}
```
2. 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**.
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg';
originMsg: string = '';
backMsg: string = '';
const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = ''
backMsg: string = ''
async onButtonCallWithResult(originMsg, backMsg) {
try {
let msg = new MySequenceable(1, originMsg);
const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg);
console.info('caller callWithResult succeed');
let msg = new MyParcelable(1, originMsg)
const data = await this.caller.callWithResult(MSG_SEND_METHOD, msg)
console.info('caller callWithResult succeed')
let result = new MySequenceable(0, '');
data.readSequenceable(result);
backMsg(result.str);
console.info(`caller result is [${result.num}, ${result.str}]`);
let result = new MyParcelable(0, '')
data.readParcelable(result)
backMsg(result.str)
console.info(`caller result is [${result.num}, ${result.str}]`)
} catch (error) {
console.info(`caller callWithResult failed with ${error}`);
console.info(`caller callWithResult failed with ${error}`)
}
}
```
......@@ -526,11 +549,11 @@ The following describes how to implement multi-device collaboration through cros
```ts
releaseCall() {
try {
this.caller.release();
this.caller.release()
this.caller = undefined
console.info('caller release succeed');
console.info('caller release succeed')
} catch (error) {
console.info(`caller release failed with ${error}`);
console.info(`caller release failed with ${error}`)
}
}
```
```
\ No newline at end of file
......@@ -17,7 +17,7 @@ This topic describes the UIAbility interaction modes in the following scenarios.
- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability)
- [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](#using-ability-call-to-implement-uiability-interaction-system-applications-only)
- [Using Ability Call to Implement UIAbility Interaction (for System Applications Only)](#using-ability-call-to-implement-uiability-interaction-for-system-applications-only)
## Starting UIAbility in the Same Application
......@@ -50,7 +50,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
```ts
import UIAbility from '@ohos.app.ability.UIAbility';
import window from '@ohos.window';
import Window from '@ohos.window';
export default class FuncAbility extends UIAbility {
onCreate(want, launchParam) {
......@@ -65,7 +65,7 @@ Assume that your application has two UIAbility components: EntryAbility and Func
3. To stop the **UIAbility** instance after the FuncAbility service is complete, call **terminateSelf()** in FuncAbility.
```ts
// context is the ability context of the UIAbility instance to stop.
// context is the ability-level context of the UIAbility instance to stop.
this.context.terminateSelf((err) => {
// ...
});
......@@ -111,7 +111,7 @@ When starting FuncAbility from EntryAbility, you want the result to be returned
},
},
}
// context is the ability context of the callee UIAbility.
// context is the ability-level context of the callee UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => {
// ...
});
......@@ -196,13 +196,13 @@ This section describes how to start the UIAbility of another application through
```
The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select.
![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png)
![uiability-intra-device-interaction](figures/uiability-intra-device-interaction.png)
3. To stop the **UIAbility** instance after the document application is used, call **terminateSelf()**.
```ts
// context is the ability context of the UIAbility instance to stop.
// context is the ability-level context of the UIAbility instance to stop.
this.context.terminateSelf((err) => {
// ...
});
......@@ -274,7 +274,7 @@ If you want to obtain the return result when using implicit Want to start the UI
},
},
}
// context is the ability context of the callee UIAbility.
// context is the ability-level context of the callee UIAbility.
this.context.terminateSelfWithResult(abilityResult, (err) => {
// ...
});
......@@ -416,7 +416,7 @@ In summary, when a UIAbility instance of application A has been created and the
> When the [launch type of the callee UIAbility](uiability-launch-type.md) is set to **standard**, a new instance is created each time the callee UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked.
## Using Ability Call to Implement UIAbility Interaction (System Applications Only)
## Using Ability Call to Implement UIAbility Interaction (for System Applications Only)
Ability call is an extension of the UIAbility capability. It enables the UIAbility to be invoked by and communicate with external systems. The UIAbility 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 UIAbility instances (caller ability and callee ability) through IPC.
......@@ -443,9 +443,9 @@ Ability call is usually used in the following scenarios:
The following figure shows the ability call process.
**Figure 1** Ability call process
Figure 1 Ability call process
![call](figures/call.png)
![call](figures/call.png)
- The caller ability uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the callee ability.
......@@ -463,15 +463,15 @@ The following figure shows the ability call process.
The following table describes the main APIs used for the ability call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller).
**Table 2** Ability call APIs
**Table 2** Ability call APIs
| API| Description|
| -------- | -------- |
| startAbilityByCall(want: Want): Promise&lt;Caller&gt; | Starts a UIAbility in the foreground (through the **want** configuration) or background (default) and obtains the caller object for communication with the UIAbility. For details, see [AbilityContext](../reference/apis/js-apis-inner-application-uiAbilityContext.md#abilitycontextstartabilitybycall) or [ServiceExtensionContext](../reference/apis/js-apis-inner-application-serviceExtensionContext.md#serviceextensioncontextstartabilitybycall).|
| on(method: string, callback: CalleeCallBack): void | Callback invoked when the callee ability registers a method.|
| off(method: string): void | Callback invoked when the callee ability deregisters a method.|
| call(method: string, data: rpc.Sequenceable): Promise&lt;void&gt; | Sends agreed sequenceable data to the callee ability.|
| callWithResult(method: string, data: rpc.Sequenceable): Promise&lt;rpc.MessageParcel&gt; | Sends agreed sequenceable data to the callee ability and obtains the agreed sequenceable data returned by the callee ability.|
| call(method:&nbsp;string,&nbsp;data:&nbsp;rpc.Parcelable):&nbsp;Promise&lt;void&gt; | Sends agreed parcelable data to the callee ability.|
| callWithResult(method:&nbsp;string,&nbsp;data:&nbsp;rpc.Parcelable):&nbsp;Promise&lt;rpc.MessageSequence&gt; | Sends agreed parcelable data to the callee ability and obtains the agreed parcelable data returned by the callee ability.|
| release(): void | Releases the caller object.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|
......@@ -487,16 +487,15 @@ The implementation of using the ability call for UIAbility interaction involves
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 **launchType** of the callee ability to **singleton** in the **module.json5** file.
| JSON Field| Description|
| -------- | -------- |
| "launchType" | Ability launch type. Set this parameter to **singleton**.|
An example of the ability configuration is as follows:
| JSON Field| Description|
| -------- | -------- |
| "launchType" | Ability launch type. Set this parameter to **singleton**.|
An example of the ability configuration is as follows:
```json
"abilities":[{
"name": ".CalleeAbility",
......@@ -510,18 +509,17 @@ An example of the ability configuration is as follows:
```
2. Import the **UIAbility** module.
```ts
import Ability from '@ohos.app.ability.UIAbility';
```
3. Define the agreed sequenceable data.
3. Define the agreed parcelable data.
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.
```ts
export default class MySequenceable {
export default class MyParcelable {
num: number = 0
str: string = ""
......@@ -530,25 +528,24 @@ An example of the ability configuration is as follows:
this.str = string
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num)
messageParcel.writeString(this.str)
marshalling(messageSequence) {
messageSequence.writeInt(this.num)
messageSequence.writeString(this.str)
return true
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt()
this.str = messageParcel.readString()
unmarshalling(messageSequence) {
this.num = messageSequence.readInt()
this.str = messageSequence.readString()
return true
}
}
```
4. Implement **Callee.on** and **Callee.off**.
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 parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code 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 sample code is as follows:
```ts
const TAG: string = '[CalleeAbility]';
const MSG_SEND_METHOD: string = 'CallSendMsg';
......@@ -556,14 +553,14 @@ An example of the ability configuration is as follows:
function sendMsgCallback(data) {
console.info('CalleeSortFunc called');
// Obtain the sequenceable data sent by the caller ability.
let receivedData = new MySequenceable(0, '');
data.readSequenceable(receivedData);
// Obtain the parcelable data sent by the caller ability.
let receivedData = new MyParcelable(0, '');
data.readParcelable(receivedData);
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`);
// Process the data.
// Return the sequenceable data result to the caller ability.
return new MySequenceable(receivedData.num + 1, `send ${receivedData.str} succeed`);
// Return the parcelable data result to the caller ability.
return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`);
}
export default class CalleeAbility extends Ability {
......@@ -595,10 +592,9 @@ An example of the ability configuration is as follows:
```
2. Obtain the caller interface.
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.
```ts
// Register the onRelease() listener of the caller ability.
private regOnRelease(caller) {
......
......@@ -3,6 +3,7 @@
The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information.
This module provides the following common ability-related functions:
- [Caller](#caller): implements sending of sequenceable data to the target ability when an ability (caller ability) invokes the target ability (callee ability).
- [Callee](#callee): implements callbacks for registration and deregistration of caller notifications.
......@@ -68,8 +69,8 @@ Called when a **WindowStage** is created for this ability.
| -------- | -------- | -------- | -------- |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.|
**Example**
**Example**
```ts
class myAbility extends Ability {
onWindowStageCreate(windowStage) {
......@@ -87,8 +88,8 @@ Called when the **WindowStage** is destroyed for this ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
**Example**
```ts
class myAbility extends Ability {
onWindowStageDestroy() {
......@@ -112,8 +113,8 @@ Called when the **WindowStage** is restored during the migration of this ability
| -------- | -------- | -------- | -------- |
| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.|
**Example**
**Example**
```ts
class myAbility extends Ability {
onWindowStageRestore(windowStage) {
......@@ -131,8 +132,8 @@ Called when this ability is destroyed to clear resources.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
**Example**
```ts
class myAbility extends Ability {
onDestroy() {
......@@ -150,8 +151,7 @@ Called when this ability is switched from the background to the foreground.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
**Example**
```ts
class myAbility extends Ability {
onForeground() {
......@@ -169,8 +169,8 @@ Called when this ability is switched from the foreground to the background.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**Example**
**Example**
```ts
class myAbility extends Ability {
onBackground() {
......@@ -200,8 +200,8 @@ Called to save data during the ability migration preparation process.
| -------- | -------- |
| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#abilityconstantoncontinueresult) | Continuation result.|
**Example**
**Example**
```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
class MyUIAbility extends UIAbility {
......@@ -229,8 +229,8 @@ Called when a new Want is passed in and this ability is started again.
| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.|
| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the ability startup and the last abnormal exit.|
**Example**
**Example**
```ts
class MyUIAbility extends UIAbility {
onNewWant(want, launchParams) {
......@@ -254,8 +254,8 @@ Dumps client information.
| -------- | -------- | -------- | -------- |
| params | Array\<string> | Yes| Parameters in the form of a command.|
**Example**
**Example**
```ts
class myAbility extends Ability {
onDump(params) {
......@@ -278,7 +278,7 @@ Called when the framework automatically saves the ability state in the case of a
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| reason | [AbilityConstant.StateType](js-apis-application-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the ability state.|
| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the ability state.|
| wantParam | {[key:&nbsp;string]:&nbsp;any} | Yes| **want** parameter.|
**Return value**
......@@ -305,13 +305,13 @@ class MyUIAbility extends UIAbility {
## Caller
Implements sending of sequenceable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility).
Implements sending of parcelable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility).
## Caller.call
call(method: string, data: rpc.Sequenceable): Promise&lt;void&gt;;
Sends sequenceable data to the target ability.
Sends parcelable data to the target ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
......@@ -319,8 +319,8 @@ Sends sequenceable data to the target ability.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.|
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the parcelable data.|
| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.|
**Return value**
......@@ -333,14 +333,13 @@ Sends sequenceable data to the target ability.
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
class MyMessageAble{ // ԶSequenceableݽṹ
class MyMessageAble{ // Custom parcelable data structure.
name:''
str:''
num: 1
......@@ -348,15 +347,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
this.name = name;
this.str = str;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
return true;
}
......@@ -371,8 +370,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
deviceId: ''
}).then((obj) => {
caller = obj;
let msg = new MyMessageAble('msg', 'world'); // See the definition of Sequenceable.
let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable.
caller.call(method, msg)
.then(() => {
console.log('Caller call() called');
......@@ -392,9 +390,9 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
## Caller.callWithResult
callWithResult(method: string, data: rpc.Sequenceable): Promise&lt;rpc.MessageParcel&gt;;
callWithResult(method: string, data: rpc.Parcelable): Promise&lt;rpc.MessageSequence&gt;;
Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability.
Sends parcelable data to the target ability and obtains the parcelable data returned by the target ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
......@@ -402,21 +400,20 @@ Sends sequenceable data to the target ability and obtains the sequenceable data
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.|
| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.|
| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the parcelable data.|
| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.|
**Return value**
| Type| Description|
| -------- | -------- |
| Promise&lt;[rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)&gt; | Promise used to return the sequenceable data from the target ability.|
| Promise&lt;[rpc.MessageSequence](js-apis-rpc.md#messagesequence9)&gt; | Promise used to return the parcelable data from the target ability.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -431,15 +428,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
this.name = name;
this.str = str;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
return true;
}
......@@ -459,7 +456,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
.then((data) => {
console.log('Caller callWithResult() called');
let retmsg = new MyMessageAble(0, '');
data.readSequenceable(retmsg);
data.readParcelable(retmsg);
})
.catch((callErr) => {
console.log('Caller.callWithResult catch error, error.code: ' + JSON.stringify(callErr.code) +
......@@ -480,7 +477,7 @@ release(): void;
Releases the caller interface of the target ability.
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
**System capability**: SystemCapability.UIAbility.UIAbilityRuntime.UIAbilityCore
**Error codes**
......@@ -491,8 +488,8 @@ Releases the caller interface of the target ability.
| 16200002 | Callee invalid. The callee does not exist. |
| 16000050 | Internal Error. |
**Example**
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
let caller;
......@@ -532,8 +529,8 @@ Registers a callback that is invoked when the stub on the target ability is disc
| -------- | -------- | -------- | -------- |
| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used to return the result.|
**Example**
**Example**
```ts
import Ability from '@ohos.application.Ability';
let caller;
......@@ -581,11 +578,10 @@ Registers a callback that is invoked when the stub on the target ability is disc
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
let caller;
......@@ -633,10 +629,10 @@ Deregisters a callback that is invoked when the stub on the target ability is di
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
**Example**
```ts
let caller;
export default class MainUIAbility extends UIAbility {
......@@ -684,10 +680,10 @@ Deregisters a callback that is invoked when the stub on the target ability is di
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For other IDs, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
**Example**
```ts
let caller;
export default class MainUIAbility extends UIAbility {
......@@ -733,14 +729,13 @@ Registers a caller notification callback, which is invoked when the target abili
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| method | string | Yes| Notification message string negotiated between the two abilities.|
| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.|
| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageSequence](js-apis-rpc.md#messagesequence9) type. The callback must return at least one empty [rpc.Parcelable](js-apis-rpc.md#parcelable9) object. Otherwise, the function execution fails.|
**Error codes**
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
......@@ -755,15 +750,15 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
this.name = name;
this.str = str;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']');
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']');
return true;
}
......@@ -772,7 +767,7 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
function funcCallBack(pdata) {
console.log('Callee funcCallBack is called ' + pdata);
let msg = new MyMessageAble('test', '');
pdata.readSequenceable(msg);
pdata.readParcelable(msg);
return new MyMessageAble('test1', 'Callee test');
}
export default class MainAbility extends Ability {
......@@ -807,12 +802,10 @@ Deregisters a caller notification callback, which is invoked when the target abi
| ID| Error Message|
| ------- | -------------------------------- |
| 401 | If the input parameter is not valid parameter. |
For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md).
**Example**
**Example**
```ts
import Ability from '@ohos.app.ability.UIAbility';
let method = 'call_Function';
......@@ -841,10 +834,10 @@ For details about the error codes, see [Ability Error Codes](../errorcodes/error
## CalleeCallback
(indata: rpc.MessageParcel): rpc.Sequenceable;
(indata: rpc.MessageSequence): rpc.Parcelable;
**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore
| Name| Readable| Writable| Type| Description|
| -------- | -------- | -------- | -------- | -------- |
| (indata: [rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)) | Yes| No| [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Prototype of the listener function registered by the callee.|
| (indata: [rpc.MessageSequence](js-apis-rpc.md#messagesequence9)) | Yes| No| [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Prototype of the listener function registered by the callee.|
......@@ -58,7 +58,7 @@ If an application needs to interact with a continuous task in the background (fo
],
"reqPermissions": [
{
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
"name": "ohos.permission.KEEP_BACKGROUND_RUNNING" // Continuous task permission
}
]
}
......@@ -345,7 +345,7 @@ For details about the stage model, see [Stage Model Development Overview](../app
}
}
class MySequenceable {
class MyParcelable {
num: number = 0;
str: String = "";
......@@ -354,31 +354,31 @@ For details about the stage model, see [Stage Model Development Overview](../app
this.str = string;
}
marshalling(messageParcel) {
messageParcel.writeInt(this.num);
messageParcel.writeString(this.str);
marshalling(messageSequence) {
messageSequence.writeInt(this.num);
messageSequence.writeString(this.str);
return true;
}
unmarshalling(messageParcel) {
this.num = messageParcel.readInt();
this.str = messageParcel.readString();
unmarshalling(messageSequence) {
this.num = messageSequence.readInt();
this.str = messageSequence.readString();
return true;
}
}
function sendMsgCallback(data) {
console.info('BgTaskAbility funcCallBack is called ' + data)
let receivedData = new MySequenceable(0, "")
data.readSequenceable(receivedData)
let receivedData = new MyParcelable(0, "")
data.readParcelable(receivedData)
console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// You can execute different methods based on the str value in the sequenceable data sent by the caller.
// You can execute different methods based on the str value in the parcelable data sent by the caller.
if (receivedData.str === 'start_bgtask') {
startContinuousTask()
} else if (receivedData.str === 'stop_bgtask') {
stopContinuousTask();
}
return new MySequenceable(10, "Callee test");
return new MyParcelable(10, "Callee test");
}
export default class BgTaskAbility extends Ability {
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册