提交 113bed4c 编写于 作者: G Gloria

Update docs against 7961+8744+8710+8654+9252

Signed-off-by: wusongqing<wusongqing@huawei.com>
上级 e5d98006
# Ability Call Development
## 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:
- 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.
![stage-call](figures/stage-call.png)
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> 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.|
## How to Develop
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**<br/>
> 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
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
export default class MySequenceable {
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
const TAG: string = '[CalleeAbility]'
const MSG_SEND_METHOD: string = 'CallSendMsg'
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, '')
data.readSequenceable(receivedData)
Logger.log(TAG, `receiveData[${receivedData.num}, ${receivedData.str}]`)
console.log(`receiveData[${receivedData.num}, ${receivedData.str}]`)
// 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`)
}
......@@ -106,7 +126,7 @@ export default class CalleeAbility extends Ability {
try {
this.callee.on(MSG_SEND_METHOD, sendMsgCallback)
} 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 {
}
```
### Accessing the Callee
1. Import the **Ability** module.
```
### Accessing the Callee Ability
**1. Import the Ability module.**
```ts
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
// 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() {
try {
this.caller = await context.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
let TAG = '[MainAbility] '
var caller = undefined
let context = 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.log(TAG + 'remote caller register OnRelease succeed')
}
}).catch((error) => {
console.error(TAG + 'get remote caller failed with ' + error)
})
async onButtonGetRemoteCaller() {
var caller = undefined
var context = this.context
context.startAbilityByCall({
deviceId: getRemoteDeviceId(),
bundleName: 'com.samples.CallApplication',
abilityName: 'CalleeAbility'
}).then((data) => {
if (data != null) {
caller = data
console.log('get remote caller success')
// Register the onRelease listener of the caller ability.
caller.onRelease((msg) => {
console.log(`remote caller onRelease is called ${msg}`)
})
console.log('remote caller register OnRelease succeed')
}
}).catch((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
import deviceManager from '@ohos.distributedHardware.deviceManager';
var dmClass;
function getRemoteDeviceId() {
if (typeof dmClass === 'object' && dmClass != null) {
var list = dmClass.getTrustedDeviceListSync();
var list = dmClass.getTrustedDeviceListSync()
if (typeof (list) == 'undefined' || typeof (list.length) == 'undefined') {
console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null");
return;
console.log("MainAbility onButtonClick getRemoteDeviceId err: list is null")
return
}
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId);
return list[0].deviceId;
console.log("MainAbility onButtonClick getRemoteDeviceId success:" + list[0].deviceId)
return list[0].deviceId
} 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
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
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))
})
requestPermission() {
let context = this.context
let permissions: Array<string> = ['ohos.permission.DISTRIBUTED_DATASYNC']
context.requestPermissionsFromUser(permissions).then((data) => {
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
const MSG_SEND_METHOD: string = 'CallSendMsg'
async onButtonCall() {
......@@ -210,12 +243,12 @@ async onButtonCall() {
let msg = new MySequenceable(1, 'origin_Msg')
await this.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:
```ts
const MSG_SEND_METHOD: string = 'CallSendMsg'
originMsg: string = ''
......@@ -224,26 +257,28 @@ async onButtonCallWithResult(originMsg, backMsg) {
try {
let msg = new MySequenceable(1, originMsg)
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, '')
data.readSequenceable(result)
backMsg(result.str)
Logger.log(TAG, `caller result is [${result.num}, ${result.str}]`)
console.log(`caller result is [${result.num}, ${result.str}]`)
} 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
try {
this.caller.release()
this.caller = undefined
Logger.log(TAG, 'caller release succeed')
} catch (error) {
Logger.error(TAG, `caller release failed with ${error}`)
releaseCall() {
try {
this.caller.release()
this.caller = undefined
console.log('caller release succeed')
} catch (error) {
console.log(`caller release failed with ${error}`)
}
}
```
......@@ -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&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```js
var want = {
"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
"abilityName": "MainAbility"
};
this.context.startServiceExtensionAbility(want)
.then((data) => {
console.log('---------- startServiceExtensionAbility success, data: -----------', data);
.then(() => {
console.log('---------- startServiceExtensionAbility success -----------');
})
.catch((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
};
var accountId = 100;
this.context.startServiceExtensionAbilityWithAccount(want,accountId)
.then((data) => {
console.log('---------- startServiceExtensionAbilityWithAccount success, data: -----------', data);
.then(() => {
console.log('---------- startServiceExtensionAbilityWithAccount success -----------');
})
.catch((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
"abilityName": "MainAbility"
};
this.context.stopServiceExtensionAbility(want)
.then((data) => {
console.log('---------- stopServiceExtensionAbility success, data: -----------', data);
.then(() => {
console.log('---------- stopServiceExtensionAbility success -----------');
})
.catch((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
};
var accountId = 100;
this.context.stopServiceExtensionAbilityWithAccount(want,accountId)
.then((data) => {
console.log('---------- stopServiceExtensionAbilityWithAccount success, data: -----------', data);
.then(() => {
console.log('---------- stopServiceExtensionAbilityWithAccount success -----------');
})
.catch((err) => {
console.log('---------- stopServiceExtensionAbilityWithAccount fail, err: -----------', err);
......@@ -658,8 +658,8 @@ Terminates this ability. This API uses a promise to return the result.
**Example**
```js
this.context.terminateSelf().then((data) => {
console.log('success:' + JSON.stringify(data));
this.context.terminateSelf().then(() => {
console.log('success');
}).catch((error) => {
console.log('failed:' + JSON.stringify(error));
});
......@@ -848,11 +848,11 @@ Disconnects a connection. This API uses a promise to return the result.
| Promise\<void> | Promise used to return the result.|
**Example**
```js
var connectionNumber = 0;
this.context.disconnectAbility(connectionNumber).then((data) => {
console.log('disconnectAbility success, data: ', data);
this.context.disconnectAbility(connectionNumber).then(() => {
console.log('disconnectAbility success');
}).catch((err) => {
console.log('disconnectAbility fail, err: ', err);
});
......@@ -888,7 +888,7 @@ Disconnects a connection. This API uses an asynchronous callback to return the r
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
......@@ -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.|
**Example**
```js
let caller = undefined;
// Start an ability in the background without passing parameters.
// Start an ability in the background by not passing parameters.
var wantBackground = {
bundleName: "com.example.myservice",
moduleName: "entry",
......@@ -1050,8 +1050,8 @@ Starts an ability with the account ID specified. This API uses a promise to retu
windowMode: 0,
};
this.context.startAbilityWithAccount(want, accountId, options)
.then((data) => {
console.log('---------- startAbilityWithAccount success, data: -----------', data);
.then(() => {
console.log('---------- startAbilityWithAccount success -----------');
})
.catch((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
| callback | AsyncCallback&lt;[PermissionRequestResult](js-apis-permissionrequestresult.md)&gt; | Yes| Callback used to return the result.|
**Example**
```js
var permissions=['com.example.permission']
this.context.requestPermissionsFromUser(permissions,(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
| Promise&lt;[PermissionRequestResult](js-apis-permissionrequestresult.md)&gt; | Promise used to return the result.|
**Example**
```js
var permissions=['com.example.permission']
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
| callback | AsyncCallback&lt;void&gt; | Yes| Callback used to return the result.|
**Example**
```js
this.context.setMissionLabel("test",(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
| Promise&lt;void&gt; | Promise used to return the result.|
**Example**
```js
this.context.setMissionLabel("test").then((data) => {
console.log('success:' + JSON.stringify(data));
this.context.setMissionLabel("test").then(() => {
console.log('success');
}).catch((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
| callback | AsyncCallback\<void> | Yes| Callback used to return the result.|
**Example**
```js
import image from '@ohos.multimedia.image'
var imagePixelMap;
......@@ -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.|
**Example**
```js
import image from '@ohos.multimedia.image'
var imagePixelMap;
......@@ -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)
});
this.context.setMissionIcon(imagePixelMap)
.then((data) => {
console.log('-------------- setMissionIcon success, data: -------------', data);
.then(() => {
console.log('-------------- setMissionIcon success -------------');
})
.catch((err) => {
console.log('-------------- setMissionIcon fail, err: -------------', err);
......
......@@ -724,15 +724,17 @@ Disconnects this ability from the Service ability. This API uses a promise to re
startAbilityByCall(want: Want): Promise&lt;Caller&gt;;
Starts an ability in the background and obtains the caller interface for communication.
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 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
let caller = undefined;
this.context.startAbilityByCall({
// Start an ability in the background by not passing parameters.
var wantBackground = {
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.
var wantForeground = {
bundleName: "com.example.myservice",
moduleName: "entry",
abilityName: "MainAbility",
deviceId: "",
parameters: {
"ohos.aafwk.param.callAbilityToForeground": true
}
};
this.context.startAbilityByCall(wantForeground)
.then((obj) => {
caller = obj;
console.log('GetCaller success');
}).catch((error) => {
console.log(`GetCaller failed with ${error}`);
});
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册