未验证 提交 c4332a44 编写于 作者: O openharmony_ci 提交者: Gitee

!9560 翻译完成:7961 Call调用开发文档整改以及新增Call前台的说明

Merge pull request !9560 from wusongqing/TR7961
# 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']
context.requestPermissionsFromUser(permissions).then((data) => {
console.log("Succeed to request permission from user with data: "+ JSON.stringify(data)) console.log("Succeed to request permission from user with data: "+ JSON.stringify(data))
}).catch((error) => { }).catch((error) => {
console.log("Failed to request permission from user with error: "+ JSON.stringify(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() {
try {
this.caller.release() this.caller.release()
this.caller = undefined this.caller = undefined
Logger.log(TAG, 'caller release succeed') console.log('caller release succeed')
} catch (error) { } catch (error) {
Logger.error(TAG, `caller release failed with ${error}`) console.log(`caller release failed with ${error}`)
}
} }
``` ```
...@@ -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));
}); });
...@@ -851,8 +851,8 @@ Disconnects a connection. This API uses a promise to return the result. ...@@ -851,8 +851,8 @@ Disconnects a connection. This API uses a promise to return the result.
```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
...@@ -909,7 +909,7 @@ Starts an ability in the foreground or background and obtains the caller interfa ...@@ -909,7 +909,7 @@ Starts an ability in the foreground or background and obtains the caller interfa
```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);
...@@ -1164,8 +1164,8 @@ Sets a label for this ability in the mission. This API uses a promise to return ...@@ -1164,8 +1164,8 @@ Sets a label for this ability in the mission. This API uses a promise to return
**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));
}); });
...@@ -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);
......
...@@ -724,15 +724,17 @@ Disconnects this ability from the Service ability. This API uses a promise to re ...@@ -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;; 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 capability**: SystemCapability.Ability.AbilityRuntime.Core
**System API**: This is a system API and cannot be called by third-party applications.
**Parameters** **Parameters**
| Name| Type| Mandatory| Description| | 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** **Return value**
...@@ -744,16 +746,38 @@ Starts an ability in the background and obtains the caller interface for communi ...@@ -744,16 +746,38 @@ Starts an ability in the background and obtains the caller interface for communi
```js ```js
let caller = undefined; let caller = undefined;
this.context.startAbilityByCall({
// Start an ability in the background by not passing parameters.
var wantBackground = {
bundleName: "com.example.myservice", bundleName: "com.example.myservice",
moduleName: "entry", moduleName: "entry",
abilityName: "MainAbility", abilityName: "MainAbility",
deviceId: "" deviceId: ""
}).then((obj) => { };
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; caller = obj;
console.log('Caller GetCaller Get ' + caller); console.log('GetCaller success');
}).catch((e) => { }).catch((error) => {
console.log('Caller GetCaller error ' + e); console.log(`GetCaller failed with ${error}`);
}); });
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册