uiability-intra-device-interaction.md 33.1 KB
Newer Older
G
Gloria 已提交
1
# Intra-Device Interaction Between UIAbility Components
G
Gloria 已提交
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17


UIAbility is the minimum unit that can be scheduled by the system. Jumping between functional modules in a device involves starting of specific UIAbility components, which belong to the same or a different application (for example, starting UIAbility of a third-party payment application).


This topic describes the UIAbility interaction modes in the following scenarios. For details about cross-device application component interaction, see [Inter-Device Application Component Interaction (Continuation)](inter-device-interaction-hop-overview.md).


- [Starting UIAbility in the Same Application](#starting-uiability-in-the-same-application)

- [Starting UIAbility in the Same Application and Obtaining the Return Result](#starting-uiability-in-the-same-application-and-obtaining-the-return-result)

- [Starting UIAbility of Another Application](#starting-uiability-of-another-application)

- [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result)

18 19
- [Starting UIAbility with Window Mode Specified (System Applications Only)](#starting-uiability-with-window-mode-specified-system-applications-only)

G
Gloria 已提交
20 21
- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability)

22
- [Using Ability Call to Implement UIAbility Interaction (System Applications Only)](#using-ability-call-to-implement-uiability-interaction-system-applications-only)
G
Gloria 已提交
23 24 25 26 27 28 29 30


## Starting UIAbility in the Same Application

This scenario is possible when an application contains multiple UIAbility components. For example, in a payment application, you may need to start the payment UIAbility from the entry UIAbility.

Assume that your application has two UIAbility components: EntryAbility and FuncAbility, either in the same module or different modules. You are required to start FuncAbility from EntryAbility.

G
Gloria 已提交
31
1. In EntryAbility, call [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to start UIAbility. The [want](../reference/apis/js-apis-app-ability-want.md) parameter is the entry parameter for starting the UIAbility instance. In the **want** parameter, **bundleName** indicates the bundle name of the application to start; **abilityName** indicates the name of the UIAbility to start; **moduleName** is required only when the target UIAbility belongs to a different module; **parameters** is used to carry custom information. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
G
Gloria 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
   
   ```ts
   let wantInfo = {
       deviceId: '', // An empty deviceId indicates the local device.
       bundleName: 'com.example.myapplication',
       abilityName: 'FuncAbility',
       moduleName: 'module1', // moduleName is optional.
       parameters: {// Custom information.
           info: 'From the Index page of EntryAbility',
       },
   }
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbility(wantInfo).then(() => {
       // ...
   }).catch((err) => {
       // ...
   })
   ```

2. Use the FuncAbility lifecycle callback to receive the parameters passed from EntryAbility.
   
   ```ts
   import UIAbility from '@ohos.app.ability.UIAbility';
G
Gloria 已提交
55
   import window from '@ohos.window';
G
Gloria 已提交
56 57 58 59 60 61 62 63 64 65 66
   
   export default class FuncAbility extends UIAbility {
       onCreate(want, launchParam) {
   	// Receive the parameters passed by the caller UIAbility.
           let funcAbilityWant = want;
           let info = funcAbilityWant?.parameters?.info;
           // ...
       }
   }
   ```

G
Gloria 已提交
67
3. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility.
G
Gloria 已提交
68 69
   
   ```ts
G
Gloria 已提交
70
   // context is the ability-level context of the UIAbility instance to stop.
G
Gloria 已提交
71 72 73 74
   this.context.terminateSelf((err) => {
       // ...
   });
   ```
G
Gloria 已提交
75 76 77 78 79 80
   
   > **NOTE**
   >
   > When [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) is called to stop the **UIAbility** instance, the snapshot of the instance is retained by default. That is, the mission corresponding to the instance is still displayed in Recents. If you do not want to retain the snapshot, set **removeMissionAfterTerminate** under the [abilities](../quick-start/module-configuration-file.md#abilities) tag to **true** in the [module.json5 file](../quick-start/module-configuration-file.md) of the corresponding UIAbility.
   
4. To stop all UIAbility instances of the application, call [killProcessBySelf()](../reference/apis/js-apis-inner-application-applicationContext.md#applicationcontextkillallprocesses9) of [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) to stop all processes of the application.
G
Gloria 已提交
81 82 83 84 85 86


## Starting UIAbility in the Same Application and Obtaining the Return Result

When starting FuncAbility from EntryAbility, you want the result to be returned after the FuncAbility service is finished. For example, your application uses two independent UIAbility components to carry the entry and sign-in functionalities. After the sign-in operation is finished in the sign-in UIAbility, the sign-in result needs to be returned to the entry UIAbility.

G
Gloria 已提交
87
1. In EntryAbility, call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start FuncAbility. Use **data** in the asynchronous callback to receive information returned after FuncAbility stops itself. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
G
Gloria 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
   
   ```ts
   let wantInfo = {
       deviceId: '', // An empty deviceId indicates the local device.
       bundleName: 'com.example.myapplication',
       abilityName: 'FuncAbility',
       moduleName: 'module1', // moduleName is optional.
       parameters: {// Custom information.
           info: 'From the Index page of EntryAbility',
       },
   }
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbilityForResult(wantInfo).then((data) => {
       // ...
   }).catch((err) => {
       // ...
   })
   ```

G
Gloria 已提交
107
2. Call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop FuncAbility. Use the input parameter **abilityResult** to carry the information that FuncAbility needs to return to EntryAbility.
G
Gloria 已提交
108 109 110 111 112 113 114 115 116 117 118 119 120 121
   
   ```ts
   const RESULT_CODE: number = 1001;
   let abilityResult = {
       resultCode: RESULT_CODE,
       want: {
           bundleName: 'com.example.myapplication',
           abilityName: 'FuncAbility',
           moduleName: 'module1',
           parameters: {
               info: 'From the Index page of FuncAbility',
           },
       },
   }
G
Gloria 已提交
122
   // context is the ability-level context of the callee UIAbility.
G
Gloria 已提交
123 124 125 126 127
   this.context.terminateSelfWithResult(abilityResult, (err) => {
       // ...
   });
   ```

G
Gloria 已提交
128
3. After FuncAbility stops itself, EntryAbility uses [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to receive the information returned by FuncAbility. The value of **RESULT_CODE** must be the same as the preceding value.
G
Gloria 已提交
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155
   
   ```ts
   const RESULT_CODE: number = 1001;
   
   // ...
   
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbilityForResult(want).then((data) => {
       if (data?.resultCode === RESULT_CODE) {
           // Parse the information returned by the callee UIAbility.
           let info = data.want?.parameters?.info;
           // ...
       }
   }).catch((err) => {
       // ...
   })
   ```


## Starting UIAbility of Another Application

Generally, the user only needs to do a common operation (for example, selecting a document application to view the document content) to start the UIAbility of another application. The [implicit Want launch mode](want-overview.md#types-of-want) is recommended. The system identifies a matched UIAbility and starts it based on the **want** parameter of the caller.

There are two ways to start **UIAbility**: [explicit and implicit](want-overview.md).

- Explicit Want launch: This mode is used to start a determined UIAbility component of an application. You need to set **bundleName** and **abilityName** of the target application in the **want** parameter.

G
Gloria 已提交
156
- Implicit Want launch: The user selects a UIAbility to start based on the matching conditions. That is, the UIAbility to start is not determined (the **abilityName** parameter is not specified). When [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) is called, the want parameter specifies a series of parameters such as **entities** and **actions**. **entities** provides category information of the target UIAbility, such as the browser or video player. **actions** specifies the common operations to perform, such as viewing, sharing, and application details. Then the system analyzes the **want** parameter to find the right UIAbility to start. You usually do not know whether the target application is installed and what **bundleName** and **abilityName** of the target application are. Therefore, implicit Want launch is usually used to start the UIAbility of another application.
G
Gloria 已提交
157 158 159

This section describes how to start the UIAbility of another application through implicit Want.

G
Gloria 已提交
160
1. Install multiple document applications on your device. In the [module.json5 file](../quick-start/module-configuration-file.md) of each UIAbility component, configure **entities** and **actions** under **skills**.
G
Gloria 已提交
161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
   
   ```json
   {
     "module": {
       "abilities": [
         {
           // ...
           "skills": [
             {
               "entities": [
                 // ...
                 "entity.system.default"
               ],
               "actions": [
                 // ...
                 "ohos.want.action.viewData"
               ]
             }
           ]
         }
       ]
     }
   }
   ```

2. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).
   
   ```ts
   let wantInfo = {
       deviceId: '', // An empty deviceId indicates the local device.
       // Uncomment the line below if you want to implicitly query data only in the specific bundle.
       // bundleName: 'com.example.myapplication',
       action: 'ohos.want.action.viewData',
       // entities can be omitted.
       entities: ['entity.system.default'],
   }
   
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbility(wantInfo).then(() => {
       // ...
   }).catch((err) => {
       // ...
   })
   ```

   The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select.
207
   ![](figures/uiability-intra-device-interaction.png)
G
Gloria 已提交
208
   
G
Gloria 已提交
209
3. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself).
G
Gloria 已提交
210 211
   
   ```ts
G
Gloria 已提交
212
   // context is the ability-level context of the UIAbility instance to stop.
G
Gloria 已提交
213 214 215 216 217 218 219 220
   this.context.terminateSelf((err) => {
       // ...
   });
   ```


## Starting UIAbility of Another Application and Obtaining the Return Result

G
Gloria 已提交
221
If you want to obtain the return result when using implicit Want to start the UIAbility of another application, use [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult). An example scenario is that the main application needs to start a third-party payment application and obtain the payment result.
G
Gloria 已提交
222

G
Gloria 已提交
223
1. In the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility corresponding to the payment application, set **entities** and **actions** under **skills**.
G
Gloria 已提交
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
   
   ```json
   {
     "module": {
       "abilities": [
         {
           // ...
           "skills": [
             {
               "entities": [
                 // ...
                 "entity.system.default"
               ],
               "actions": [
                 // ...
                 "ohos.want.action.editData"
               ]
             }
           ]
         }
       ]
     }
   }
   ```

G
Gloria 已提交
249
2. Call [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to start the UIAbility of the payment application. Include **entities** and **actions** of the caller's **want** parameter into **entities** and **actions** under **skills** of the target UIAbility. Use **data** in the asynchronous callback to receive the information returned to the caller after the payment UIAbility stops itself. After the system matches the UIAbility that meets the **entities** and **actions** information, a dialog box is displayed, showing the list of matched UIAbility instances for users to select.
G
Gloria 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
   
   ```ts
   let wantInfo = {
       deviceId: '', // An empty deviceId indicates the local device.
       // Uncomment the line below if you want to implicitly query data only in the specific bundle.
       // bundleName: 'com.example.myapplication',
       action: 'ohos.want.action.editData',
       // entities can be omitted.
       entities: ['entity.system.default'],
   }
   
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbilityForResult(wantInfo).then((data) => {
       // ...
   }).catch((err) => {
       // ...
   })
   ```

G
Gloria 已提交
269
3. After the payment is finished, call [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) to stop the payment UIAbility and return the **abilityResult** parameter.
G
Gloria 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283
   
   ```ts
   const RESULT_CODE: number = 1001;
   let abilityResult = {
       resultCode: RESULT_CODE,
       want: {
           bundleName: 'com.example.myapplication',
           abilityName: 'EntryAbility',
           moduleName: 'entry',
           parameters: {
               payResult: 'OKay',
           },
       },
   }
G
Gloria 已提交
284
   // context is the ability-level context of the callee UIAbility.
G
Gloria 已提交
285 286 287 288 289
   this.context.terminateSelfWithResult(abilityResult, (err) => {
       // ...
   });
   ```

G
Gloria 已提交
290
4. Receive the information returned by the payment application in the callback of the [startAbilityForResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult) method. The value of **RESULT_CODE** must be the same as that returned by [terminateSelfWithResult()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateselfwithresult).
G
Gloria 已提交
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
   
   ```ts
   const RESULT_CODE: number = 1001;
   
   let want = {
     // Want parameter information.
   };
   
   // context is the ability-level context of the initiator UIAbility.
   this.context.startAbilityForResult(want).then((data) => {
       if (data?.resultCode === RESULT_CODE) {
           // Parse the information returned by the callee UIAbility.
           let payResult = data.want?.parameters?.payResult;
           // ...
       }
   }).catch((err) => {
       // ...
   })
   ```

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
## Starting UIAbility with Window Mode Specified (System Applications Only)

By specifying the window mode when starting the UIAbility of an application, the application can be displayed in different window modes, which can be full-screen, floating window, or split-screen.

In full-screen mode, an application occupies the entire screen after being started. Users cannot view other windows or applications. This mode is suitable for an application that requires users to focus on a specific task or UI.

In floating window mode, an application is displayed on the screen as a floating window after being started. Users can easily switch to other windows or applications. The mode is suitable for an application that requires users to process multiple tasks at the same time.

In split-screen mode, two applications occupy the entire screen, with one on the left or in the upper part of the screen and the other on the right or in the lower part. This mode helps users improve multi-task processing efficiency.

The window mode is specified by the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter of [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability).

> **NOTE**
>
> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode.
> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities tag](../quick-start/module-configuration-file.md#abilities) in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported.

The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page.

1. Add the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability).
2. Set the **windowMode** field in the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter to **WINDOW_MODE_FLOATING**, indicating that the UIAbility will be displayed in a floating window.

For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).

```ts
import AbilityConstant from '@ohos.app.ability.AbilityConstant';

let wantInfo = {
  deviceId: '', // An empty deviceId indicates the local device.
  bundleName: 'com.example.myapplication',
  abilityName: 'FuncAbility',
  moduleName: 'module1', // moduleName is optional.
  parameters: {// Custom information.
    info: 'From the Index page of EntryAbility',
  },
}
let options = {
  windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING
}
// context is the ability-level context of the initiator UIAbility.
this.context.startAbility(wantInfo, options).then(() => {
  // ...
}).catch((err) => {
  // ...
})
```

The display effect is shown below.  
![](figures/start-uiability-floating-window.png)
G
Gloria 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474

## Starting a Specified Page of UIAbility

A UIAbility component can have multiple pages. When it is started in different scenarios, different pages can be displayed. For example, when a user jumps from a page of a UIAbility component to another UIAbility, you want to start a specified page of the target UIAbility. This section describes how to specify a startup page and start the specified page when the target UIAbility is started for the first time or when the target UIAbility is not started for the first time.


### Specifying a Startup Page

When the caller UIAbility starts another UIAbility, it usually needs to redirect to a specified page. For example, FuncAbility contains two pages: Index (corresponding to the home page) and Second (corresponding to function A page). You can configure the specified page URL in the **want** parameter by adding a custom parameter to **parameters** in **want**. For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability).


```ts
let wantInfo = {
    deviceId: '', // An empty deviceId indicates the local device.
    bundleName: 'com.example.myapplication',
    abilityName: 'FuncAbility',
    moduleName: 'module1', // moduleName is optional.
    parameters: {// Custom parameter used to pass the page information.
        router: 'funcA',
    },
}
// context is the ability-level context of the initiator UIAbility.
this.context.startAbility(wantInfo).then(() => {
    // ...
}).catch((err) => {
    // ...
})
```


### Starting a Page When the Target UIAbility Is Started for the First Time

When the target UIAbility is started for the first time, in the **onWindowStageCreate()** callback of the target UIAbility, parse the **want** parameter passed by EntryAbility to obtain the URL of the page to be loaded, and pass the URL to the **windowStage.loadContent()** method.


```ts
import UIAbility from '@ohos.app.ability.UIAbility'
import Window from '@ohos.window'

export default class FuncAbility extends UIAbility {
    funcAbilityWant;

    onCreate(want, launchParam) {
        // Receive the parameters passed by the caller UIAbility.
        this.funcAbilityWant = want;
    }

    onWindowStageCreate(windowStage: Window.WindowStage) {
        // Main window is created. Set a main page for this ability.
        let url = 'pages/Index';
        if (this.funcAbilityWant?.parameters?.router) {
            if (this.funcAbilityWant.parameters.router === 'funA') {
                url = 'pages/Second';
            }
        }
        windowStage.loadContent(url, (err, data) => {
            // ...
        });
    }
}
```


### Starting a Page When the Target UIAbility Is Not Started for the First Time

You start application A, and its home page is displayed. Then you return to the home screen and start application B. Now you need to start application A again from application B and have a specified page of application A displayed. An example scenario is as follows: When you open the home page of the SMS application and return to the home screen, the SMS application is in the opened state and its home page is displayed. Then you open the home page of the Contacts application, access user A's details page, and touch the SMS icon to send an SMS message to user A. The SMS application is started again and the sending page is displayed.

![uiability_not_first_started](figures/uiability_not_first_started.png)

In summary, when a UIAbility instance of application A has been created and the main page of the UIAbility instance is displayed, you need to start the UIAbility of application A from application B and have a different page displayed.

1. In the target UIAbility, the **Index** page is loaded by default. The UIAbility instance has been created, and the **onNewWant()** callback rather than **onCreate()** and **onWindowStageCreate()** will be invoked. In the **onNewWant()** callback, parse the **want** parameter and bind it to the global variable **globalThis**.
   
   ```ts
   import UIAbility from '@ohos.app.ability.UIAbility'
   
   export default class FuncAbility extends UIAbility {
       onNewWant(want, launchParam) {
           // Receive the parameters passed by the caller UIAbility.
           globalThis.funcAbilityWant = want;
           // ...
       }
   }
   ```

2. In FuncAbility, use the router module to implement redirection to the specified page on the **Index** page. Because the **Index** page of FuncAbility is active, the variable will not be declared again and the **aboutToAppear()** callback will not be triggered. Therefore, the page routing functionality can be implemented in the **onPageShow()** callback of the **Index** page.
   
   ```ts
   import router from '@ohos.router';
   
   @Entry
   @Component
   struct Index {
     onPageShow() {
       let funcAbilityWant = globalThis.funcAbilityWant;
       let url2 = funcAbilityWant?.parameters?.router;
       if (url2 && url2 === 'funcA') {
         router.replaceUrl({
           url: 'pages/Second',
         })
       }
     }
   
     // Page display.
     build() {
       // ...
     }
   }
   ```

> **NOTE**
>
> 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.


475
## Using Ability Call to Implement UIAbility Interaction (System Applications Only)
G
Gloria 已提交
476

477
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.
G
Gloria 已提交
478 479 480 481 482 483 484 485 486 487 488 489 490

The core API used for the ability call is **startAbilityByCall**, which differs from **startAbility** in the following ways:

- **startAbilityByCall** supports ability launch in the foreground and background, whereas **startAbility** supports ability launch 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

491
  **Table 1** Terms used in the ability call
G
Gloria 已提交
492 493 494 495 496 497 498 499 500 501

| **Term**| Description|
| -------- | -------- |
| CallerAbility | UIAbility that triggers the ability call.|
| CalleeAbility | UIAbility 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.|

The following figure shows the ability call process.

502
  Figure 1 Ability call process
G
Gloria 已提交
503

504
  ![call](figures/call.png)  
G
Gloria 已提交
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521

- 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.

> **NOTE**
> 1. Currently, only system applications can use the ability call.
> 
> 2. The launch type of the callee ability must be **singleton**.
> 
> 3. Both local (intra-device) and cross-device ability calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device ability call, see [Using Cross-Device Ability Call](hop-multi-device-collaboration.md#using-cross-device-ability-call).


### Available APIs

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).

522
 **Table 2** Ability call APIs
G
Gloria 已提交
523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546

| API| Description|
| -------- | -------- |
| startAbilityByCall(want: Want): Promise<Caller> | 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<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.|
| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.|

The implementation of using the ability call for UIAbility interaction involves two parts.

- [Creating a Callee Ability](#creating-a-callee-ability)

- [Accessing the Callee Ability](#accessing-the-callee-ability)


### 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.
   
G
Gloria 已提交
547
   Set **launchType** of the callee ability to **singleton** in the **module.json5** file.
548
   
G
Gloria 已提交
549 550 551
   | JSON Field| Description|
   | -------- | -------- |
   | "launchType" | Ability launch type. Set this parameter to **singleton**.|
552
   
G
Gloria 已提交
553
   An example of the ability configuration is as follows:
554 555 556 557 558 559 560 561 562 563 564 565 566 567
   
   
   ```json
   "abilities":[{
     "name": ".CalleeAbility",
     "srcEntrance": "./ets/CalleeAbility/CalleeAbility.ts",
     "launchType": "singleton",
     "description": "$string:CalleeAbility_desc",
     "icon": "$media:icon",
     "label": "$string:CalleeAbility_label",
     "visible": true
   }]
   ```
   
G
Gloria 已提交
568 569 570 571 572 573 574 575 576
2. Import the **UIAbility** module.

   ```ts
   import Ability from '@ohos.app.ability.UIAbility';
   ```

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.
577 578
   
   
G
Gloria 已提交
579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651
   ```ts
   export default class MySequenceable {
       num: number = 0
       str: string = ""
   
       constructor(num, string) {
           this.num = num
           this.str = string
       }
   
       marshalling(messageParcel) {
           messageParcel.writeInt(this.num)
           messageParcel.writeString(this.str)
           return true
       }
   
       unmarshalling(messageParcel) {
           this.num = messageParcel.readInt()
           this.str = messageParcel.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 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';
   
   function sendMsgCallback(data) {
       console.info('CalleeSortFunc called');
   
       // Obtain the sequenceable data sent by the caller ability.
       let receivedData = new MySequenceable(0, '');
       data.readSequenceable(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`);
   }
   
   export default class CalleeAbility extends Ability {
       onCreate(want, launchParam) {
           try {
               this.callee.on(MSG_SEND_METHOD, sendMsgCallback);
           } catch (error) {
               console.info(`${MSG_SEND_METHOD} register failed with error ${JSON.stringify(error)}`);
           }
       }
   
       onDestroy() {
           try {
               this.callee.off(MSG_SEND_METHOD);
           } catch (error) {
               console.error(TAG, `${MSG_SEND_METHOD} unregister failed with error ${JSON.stringify(error)}`);
           }
       }
   }
   ```

### Accessing the Callee Ability

1. Import the **UIAbility** module.
   
   ```ts
   import Ability from '@ohos.app.ability.UIAbility';
   ```

2. Obtain the caller interface.

652 653
   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.
   
G
Gloria 已提交
654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683
   ```ts
   // Register the onRelease() listener of the caller ability.
   private regOnRelease(caller) {
       try {
           caller.on("release", (msg) => {
               console.info(`caller onRelease is called ${msg}`);
           })
           console.info('caller register OnRelease succeed');
       } catch (error) {
           console.info(`caller register OnRelease failed with ${error}`);
       }
   }
   
   async onButtonGetCaller() {
       try {
           this.caller = await context.startAbilityByCall({
               bundleName: 'com.samples.CallApplication',
               abilityName: 'CalleeAbility'
           })
           if (this.caller === undefined) {
               console.info('get caller failed')
               return
           }
           console.info('get caller success')
           this.regOnRelease(this.caller)
       } catch (error) {
           console.info(`get caller failed with ${error}`)
       }
   }
   ```