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:
- Creating a callee
- Accessing the callee
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).
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.
> The startup mode of the callee must be **singleton**.
> Currently, only system applications and Service Extension abilities can use the **Call** APIs to access the callee.
> **NOTE**<br/>
> The launch type of the callee ability must be `singleton`.
> Currently, only system applications can use the ability call.
## Available APIs
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|
|:------|:------|
|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.|
|on(method: string, callback: CalleeCallBack): void|Callback invoked when the callee registers a method.|
|off(method: string): void|Callback invoked when the callee deregisters a method.|
|call(method: string, data: rpc.Sequenceable): Promise\<void>|Sends agreed sequenceable data to the callee.|
|callWithResult(method: string, data: rpc.Sequenceable): Promise\<rpc.MessageParcel>|Sends agreed sequenceable data to the callee and returns the agreed sequenceable data.|
|release(): void|Releases the caller interface.|
|onRelease(callback: OnReleaseCallBack): void|Registers a callback that is invoked when the caller is disconnected.|
|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 ability registers 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 ability.|
|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` object.|
|onRelease(callback: OnReleaseCallBack): void|Callback invoked when the `Caller` object is released.|
> 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.
### Creating a Callee
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.
1. Configure the ability startup mode.
The procedure for developing the ability call is as follows:
1. Create a callee ability.
2. Access the callee ability.
> **NOTE**
>
> 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|
|:------|:------|
|"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:
```json
...
...
@@ -51,13 +71,13 @@ An example of the ability configuration is as follows:
"visible":true
}]
```
2. Import the **Ability** module.
```
**2. Import the Ability module.**
```ts
importAbilityfrom'@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
exportdefaultclassMySequenceable{
num:number=0
...
...
@@ -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
constTAG:string='[CalleeAbility]'
constMSG_SEND_METHOD:string='CallSendMsg'
functionsendMsgCallback(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.
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
// Register the onRelease listener of the caller ability.
privateregOnRelease(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}`)
}
}
asynconButtonGetCaller(){
try{
this.caller=awaitcontext.startAbilityByCall({
...
...
@@ -136,73 +168,74 @@ async onButtonGetCaller() {
abilityName:'CalleeAbility'
})
if(this.caller===undefined){
Logger.error(TAG,'get caller failed')
console.log('get caller failed')
return
}
Logger.log(TAG,'get caller success')
console.log('get caller success')
this.regOnRelease(this.caller)
}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
letTAG='[MainAbility] '
varcaller=undefined
letcontext=this.context
context.startAbilityByCall({
deviceId:getRemoteDeviceId(),
bundleName:'com.samples.CallApplication',
abilityName:'CalleeAbility'
}).then((data)=>{
if(data!=null){
caller=data
console.log(TAG+'get remote caller success')
// Register the onRelease listener of the caller.
caller.onRelease((msg)=>{
console.log(TAG+'remote caller onRelease is called '+msg)
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:
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:
console.log("Succeed to request permission from user with data: "+JSON.stringify(data))
}).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
constMSG_SEND_METHOD:string='CallSendMsg'
asynconButtonCall(){
...
...
@@ -210,12 +243,12 @@ async onButtonCall() {
letmsg=newMySequenceable(1,'origin_Msg')
awaitthis.caller.call(MSG_SEND_METHOD,msg)
}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:
@@ -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.
> **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.
## Usage
...
...
@@ -78,7 +78,7 @@ Starts an ability with start options specified. This API uses an asynchronous ca
| callback | AsyncCallback<void> | Yes| Callback used to return the result.|
**Example**
```js
varwant={
"deviceId":"",
...
...
@@ -127,7 +127,7 @@ Starts an ability. This API uses a promise to return the result.
windowMode:0,
};
this.context.startAbility(want,options)
.then((data)=>{
.then(()=>{
console.log('Operation successful.')
}).catch((error)=>{
console.log('Operation failed.');
...
...
@@ -407,8 +407,8 @@ Starts a new Service Extension ability. This API uses a promise to return the re
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters**
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, including the ability name, module name, bundle name, and device ID. If the device ID is left blank or the default value is used, the local ability will be started.|
| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.|
**Return value**
...
...
@@ -744,16 +746,38 @@ Starts an ability in the background and obtains the caller interface for communi
```js
letcaller=undefined;
this.context.startAbilityByCall({
// Start an ability in the background by not passing parameters.
varwantBackground={
bundleName:"com.example.myservice",
moduleName:"entry",
abilityName:"MainAbility",
deviceId:""
}).then((obj)=>{
caller=obj;
console.log('Caller GetCaller Get '+caller);
}).catch((e)=>{
console.log('Caller GetCaller error '+e);
});
};
this.context.startAbilityByCall(wantBackground)
.then((obj)=>{
caller=obj;
console.log('GetCaller Success');
}).catch((error)=>{
console.log(`GetCaller failed with ${error}`);
});
// Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true.