1# Intra-Device Interaction Between UIAbility Components 2 3 4UIAbility 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). 5 6 7This 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). 8 9 10- [Starting UIAbility in the Same Application](#starting-uiability-in-the-same-application) 11 12- [Starting UIAbility in the Same Application and Obtaining the Return Result](#starting-uiability-in-the-same-application-and-obtaining-the-return-result) 13 14- [Starting UIAbility of Another Application](#starting-uiability-of-another-application) 15 16- [Starting UIAbility of Another Application and Obtaining the Return Result](#starting-uiability-of-another-application-and-obtaining-the-return-result) 17 18- [Starting UIAbility with Window Mode Specified (for System Applications Only)](#starting-uiability-with-window-mode-specified-for-system-applications-only) 19 20- [Starting a Specified Page of UIAbility](#starting-a-specified-page-of-uiability) 21 22- [Using Call to Implement UIAbility Interaction (for System Applications Only)](#using-call-to-implement-uiability-interaction-for-system-applications-only) 23 24 25## Starting UIAbility in the Same Application 26 27This 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. 28 29Assume 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. 30 311. 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). 32 33 ```ts 34 let context = ...; // UIAbilityContext 35 let want = { 36 deviceId: '', // An empty deviceId indicates the local device. 37 bundleName: 'com.example.myapplication', 38 abilityName: 'FuncAbility', 39 moduleName: 'func', // moduleName is optional. 40 parameters: {// Custom information. 41 info: 'From the Index page of EntryAbility', 42 }, 43 } 44 // context is the UIAbilityContext of the initiator UIAbility. 45 context.startAbility(want).then(() => { 46 console.info('Succeeded in starting ability.'); 47 }).catch((err) => { 48 console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); 49 }) 50 ``` 51 522. In FuncAbility, use [onCreate()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityoncreate) or [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#uiabilityonnewwant) to receive the parameters passed in by EntryAbility. 53 54 ```ts 55 import UIAbility from '@ohos.app.ability.UIAbility'; 56 57 export default class FuncAbility extends UIAbility { 58 onCreate(want, launchParam) { 59 // Receive the parameters passed by the initiator UIAbility. 60 let funcAbilityWant = want; 61 let info = funcAbilityWant?.parameters?.info; 62 ... 63 } 64 } 65 ``` 66 67 > **NOTE** 68 > 69 > In FuncAbility started, you can obtain the PID and bundle name of the UIAbility through **parameters** in the passed **want** parameter. 70 713. To stop the **UIAbility** instance after the FuncAbility service is complete, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) in FuncAbility. 72 73 ```ts 74 let context = ...; // UIAbilityContext 75 76 // context is the UIAbilityContext of the UIAbility instance to stop. 77 context.terminateSelf((err) => { 78 if (err.code) { 79 console.error(`Failed to terminate Self. Code is ${err.code}, message is ${err.message}`); 80 return; 81 } 82 }); 83 ``` 84 85 > **NOTE** 86 > 87 > 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. 88 894. To stop all UIAbility instances of the application, call **killProcessBySelf()** of [ApplicationContext](../reference/apis/js-apis-inner-application-applicationContext.md) to stop all processes of the application. 90 91 92## Starting UIAbility in the Same Application and Obtaining the Return Result 93 94When 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. 95 961. 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). 97 98 ```ts 99 let context = ...; // UIAbilityContext 100 let want = { 101 deviceId: '', // An empty deviceId indicates the local device. 102 bundleName: 'com.example.myapplication', 103 abilityName: 'FuncAbility', 104 moduleName: 'func', // moduleName is optional. 105 parameters: {// Custom information. 106 info: 'From the Index page of EntryAbility', 107 }, 108 } 109 // context is the UIAbilityContext of the initiator UIAbility. 110 context.startAbilityForResult(want).then((data) => { 111 ... 112 }).catch((err) => { 113 console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); 114 }) 115 ``` 116 1172. 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. 118 119 ```ts 120 let context = ...; // UIAbilityContext 121 const RESULT_CODE: number = 1001; 122 let abilityResult = { 123 resultCode: RESULT_CODE, 124 want: { 125 bundleName: 'com.example.myapplication', 126 abilityName: 'FuncAbility', 127 moduleName: 'func', 128 parameters: { 129 info: 'From the Index page of FuncAbility', 130 }, 131 }, 132 } 133 // context is the AbilityContext of the target UIAbility. 134 context.terminateSelfWithResult(abilityResult, (err) => { 135 if (err.code) { 136 console.error(`Failed to terminate self with result. Code is ${err.code}, message is ${err.message}`); 137 return; 138 } 139 }); 140 ``` 141 1423. 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. 143 144 ```ts 145 let context = ...; // UIAbilityContext 146 const RESULT_CODE: number = 1001; 147 148 ... 149 150 // context is the UIAbilityContext of the initiator UIAbility. 151 context.startAbilityForResult(want).then((data) => { 152 if (data?.resultCode === RESULT_CODE) { 153 // Parse the information returned by the target UIAbility. 154 let info = data.want?.parameters?.info; 155 ... 156 } 157 }).catch((err) => { 158 console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); 159 }) 160 ``` 161 162 163## Starting UIAbility of Another Application 164 165Generally, 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 initiator UIAbility. 166 167There are two ways to start **UIAbility**: [explicit and implicit](want-overview.md). 168 169- 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. 170 171- 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. 172 173This section describes how to start the UIAbility of another application through implicit Want. 174 1751. 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**. 176 177 ```json 178 { 179 "module": { 180 "abilities": [ 181 { 182 ... 183 "skills": [ 184 { 185 "entities": [ 186 ... 187 "entity.system.default" 188 ], 189 "actions": [ 190 ... 191 "ohos.want.action.viewData" 192 ] 193 } 194 ] 195 } 196 ] 197 } 198 } 199 ``` 200 2012. Include **entities** and **actions** of the initiator UIAbility'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). 202 203 ```ts 204 let context = ...; // UIAbilityContext 205 let want = { 206 deviceId: '', // An empty deviceId indicates the local device. 207 // Uncomment the line below if you want to implicitly query data only in the specific bundle. 208 // bundleName: 'com.example.myapplication', 209 action: 'ohos.want.action.viewData', 210 // entities can be omitted. 211 entities: ['entity.system.default'], 212 } 213 214 // context is the UIAbilityContext of the initiator UIAbility. 215 context.startAbility(want).then(() => { 216 console.info('Succeeded in starting ability.'); 217 }).catch((err) => { 218 console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); 219 }) 220 ``` 221 222 The following figure shows the effect. When you click **Open PDF**, a dialog box is displayed for you to select. 223  224 2253. To stop the **UIAbility** instance after the document application is used, call [terminateSelf()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself). 226 227 ```ts 228 let context = ...; // UIAbilityContext 229 230 // context is the UIAbilityContext of the UIAbility instance to stop. 231 context.terminateSelf((err) => { 232 if (err.code) { 233 console.error(`Failed to terminate self. Code is ${err.code}, message is ${err.message}`); 234 return; 235 } 236 }); 237 ``` 238 239 240## Starting UIAbility of Another Application and Obtaining the Return Result 241 242If 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. 243 2441. 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**. 245 246 ```json 247 { 248 "module": { 249 "abilities": [ 250 { 251 ... 252 "skills": [ 253 { 254 "entities": [ 255 ... 256 "entity.system.default" 257 ], 258 "actions": [ 259 ... 260 "ohos.want.action.editData" 261 ] 262 } 263 ] 264 } 265 ] 266 } 267 } 268 ``` 269 2702. 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 initiator UIAbility'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 initiator UIAbility 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. 271 272 ```ts 273 let context = ...; // UIAbilityContext 274 let want = { 275 deviceId: '', // An empty deviceId indicates the local device. 276 // Uncomment the line below if you want to implicitly query data only in the specific bundle. 277 // bundleName: 'com.example.myapplication', 278 action: 'ohos.want.action.editData', 279 // entities can be omitted. 280 entities: ['entity.system.default'] 281 } 282 283 // context is the UIAbilityContext of the initiator UIAbility. 284 context.startAbilityForResult(want).then((data) => { 285 ... 286 }).catch((err) => { 287 console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); 288 }) 289 ``` 290 2913. 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. 292 293 ```ts 294 let context = ...; // UIAbilityContext 295 const RESULT_CODE: number = 1001; 296 let abilityResult = { 297 resultCode: RESULT_CODE, 298 want: { 299 bundleName: 'com.example.myapplication', 300 abilityName: 'EntryAbility', 301 moduleName: 'entry', 302 parameters: { 303 payResult: 'OKay', 304 }, 305 }, 306 } 307 // context is the AbilityContext of the target UIAbility. 308 context.terminateSelfWithResult(abilityResult, (err) => { 309 if (err.code) { 310 console.error(`Failed to terminate self with result. Code is ${err.code}, message is ${err.message}`); 311 return; 312 } 313 }); 314 ``` 315 3164. 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). 317 318 ```ts 319 let context = ...; // UIAbilityContext 320 const RESULT_CODE: number = 1001; 321 322 let want = { 323 // Want parameter information. 324 }; 325 326 // context is the UIAbilityContext of the initiator UIAbility. 327 context.startAbilityForResult(want).then((data) => { 328 if (data?.resultCode === RESULT_CODE) { 329 // Parse the information returned by the target UIAbility. 330 let payResult = data.want?.parameters?.payResult; 331 ... 332 } 333 }).catch((err) => { 334 console.error(`Failed to start ability for result. Code is ${err.code}, message is ${err.message}`); 335 }) 336 ``` 337 338## Starting UIAbility with Window Mode Specified (for System Applications Only) 339 340By 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. 341 342In 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. 343 344In 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. 345 346In 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. 347 348The 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). 349 350> **NOTE** 351> 352> 1. If the **windowMode** field is not specified, the UIAbility is started in the default window mode. 353> 2. To ensure that the application can be displayed in the required window mode, check the **supportWindowMode** field in the [abilities](../quick-start/module-configuration-file.md#abilities) tag in the [module.json5 file](../quick-start/module-configuration-file.md) of the UIAbility and make sure the specified window mode is supported. 354 355The following uses the floating window mode as an example to describe how to start the FuncAbility from the EntryAbility page. 356 3571. Add the [StartOptions](../reference/apis/js-apis-app-ability-startOptions.md) parameter in [startAbility()](../reference/apis/js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability). 3582. 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. 359 360For details about how to obtain the context, see [Obtaining the Context of UIAbility](uiability-usage.md#obtaining-the-context-of-uiability). 361 362```ts 363import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 364 365let context = ...; // UIAbilityContext 366let want = { 367 deviceId: '', // An empty deviceId indicates the local device. 368 bundleName: 'com.example.myapplication', 369 abilityName: 'FuncAbility', 370 moduleName: 'func', // moduleName is optional. 371 parameters: {// Custom information. 372 info: 'From the Index page of EntryAbility', 373 }, 374} 375let options = { 376 windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FLOATING 377}; 378// context is the UIAbilityContext of the initiator UIAbility. 379context.startAbility(want, options).then(() => { 380 console.info('Succeeded in starting ability.'); 381}).catch((err) => { 382 console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); 383}) 384``` 385 386The display effect is shown below. 387 388 389 390## Starting a Specified Page of UIAbility 391 392A 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. 393 394 395### Specifying a Startup Page 396 397When the initiator 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). 398 399 400```ts 401let context = ...; // UIAbilityContext 402let want = { 403 deviceId: '', // An empty deviceId indicates the local device. 404 bundleName: 'com.example.myapplication', 405 abilityName: 'FuncAbility', 406 moduleName: 'func', // moduleName is optional. 407 parameters: {// Custom parameter used to pass the page information. 408 router: 'funcA', 409 }, 410} 411// context is the UIAbilityContext of the initiator UIAbility. 412context.startAbility(want).then(() => { 413 console.info('Succeeded in starting ability.'); 414}).catch((err) => { 415 console.error(`Failed to start ability. Code is ${err.code}, message is ${err.message}`); 416}) 417``` 418 419 420### Starting a Page When the Target UIAbility Is Started for the First Time 421 422When 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. 423 424 425```ts 426import UIAbility from '@ohos.app.ability.UIAbility' 427import Window from '@ohos.window' 428 429export default class FuncAbility extends UIAbility { 430 funcAbilityWant; 431 432 onCreate(want, launchParam) { 433 // Receive the parameters passed by the initiator UIAbility. 434 this.funcAbilityWant = want; 435 } 436 437 onWindowStageCreate(windowStage: Window.WindowStage) { 438 // Main window is created. Set a main page for this UIAbility. 439 let url = 'pages/Index'; 440 if (this.funcAbilityWant?.parameters?.router) { 441 if (this.funcAbilityWant.parameters.router === 'funA') { 442 url = 'pages/Second'; 443 } 444 } 445 windowStage.loadContent(url, (err, data) => { 446 ... 447 }); 448 } 449} 450``` 451 452 453### Starting a Page When the Target UIAbility Is Not Started for the First Time 454 455You 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. 456 457 458 459In 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. 460 4611. 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**. 462 463 ```ts 464 import UIAbility from '@ohos.app.ability.UIAbility' 465 466 export default class FuncAbility extends UIAbility { 467 onNewWant(want, launchParam) { 468 // Receive the parameters passed by the initiator UIAbility. 469 globalThis.funcAbilityWant = want; 470 ... 471 } 472 } 473 ``` 474 4752. 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. 476 477 ```ts 478 import router from '@ohos.router'; 479 480 @Entry 481 @Component 482 struct Index { 483 onPageShow() { 484 let funcAbilityWant = globalThis.funcAbilityWant; 485 let url2 = funcAbilityWant?.parameters?.router; 486 if (url2 && url2 === 'funcA') { 487 router.replaceUrl({ 488 url: 'pages/Second', 489 }) 490 } 491 } 492 493 // Page display. 494 build() { 495 ... 496 } 497 } 498 ``` 499 500> **NOTE** 501> 502> When the [launch type of the target UIAbility](uiability-launch-type.md) is set to **multiton**, a new instance is created each time the target UIAbility is started. In this case, the [onNewWant()](../reference/apis/js-apis-app-ability-uiAbility.md#abilityonnewwant) callback will not be invoked. 503 504 505## Using Call to Implement UIAbility Interaction (for System Applications Only) 506 507Call 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 call to implement data sharing between two UIAbility instances (CallerAbility and CalleeAbility) through IPC. 508 509The core API used for the call is **startAbilityByCall()**, which differs from **startAbility()** in the following ways: 510 511- **startAbilityByCall()** supports UIAbility launch in the foreground and background, whereas **startAbility()** supports UIAbility launch in the foreground only. 512 513- The CallerAbility can use the caller object returned by **startAbilityByCall()** to communicate with the CalleeAbility, but **startAbility()** does not provide the communication capability. 514 515Call is usually used in the following scenarios: 516 517- Communicating with the CalleeAbility 518 519- Starting the CalleeAbility in the background 520 521 522**Table 1** Terms used in the call 523 524| **Term**| Description| 525| -------- | -------- | 526| CallerAbility| UIAbility that triggers the call.| 527| CalleeAbility | UIAbility invoked by the call.| 528| Caller | Object returned by **startAbilityByCall** and used by the CallerAbility to communicate with the CalleeAbility.| 529| Callee | Object held by the CalleeAbility to communicate with the CallerAbility.| 530 531The following figure shows the call process. 532 533Figure 1 Call process 534 535 536 537- The CallerAbility uses **startAbilityByCall** to obtain a caller object and uses **call()** of the caller object to send data to the CalleeAbility. 538 539- The CalleeAbility, which holds a **Callee** object, uses **on()** of the **Callee** object to register a callback. This callback is invoked when the CalleeAbility receives data from the CallerAbility. 540 541> **NOTE** 542> 1. Currently, only system applications can use the call. 543> 544> 2. The launch type of the CalleeAbility must be **singleton**. 545> 546> 3. Both local (intra-device) and cross-device calls are supported. The following describes how to initiate a local call. For details about how to initiate a cross-device call, see [Using Cross-Device Call](hop-multi-device-collaboration.md#using-cross-device-call). 547 548 549### Available APIs 550 551The following table describes the main APIs used for the call. For details, see [AbilityContext](../reference/apis/js-apis-app-ability-uiAbility.md#caller). 552 553**Table 2** Call APIs 554 555| API| Description| 556| -------- | -------- | 557| 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).| 558| on(method: string, callback: CalleeCallBack): void | Callback invoked when the CalleeAbility registers a method.| 559| off(method: string): void | Callback invoked when the CalleeAbility deregisters a method.| 560| call(method: string, data: rpc.Parcelable): Promise<void> | Sends agreed parcelable data to the CalleeAbility.| 561| callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> | Sends agreed parcelable data to the CalleeAbility and obtains the agreed parcelable data returned by the CalleeAbility.| 562| release(): void | Releases the caller object.| 563| on(type: "release", callback: OnReleaseCallback): void | Callback invoked when the caller object is released.| 564 565The implementation of using the call for UIAbility interaction involves two parts. 566 567- [Creating a CalleeAbility](#creating-a-calleeability) 568 569- [Accessing the CalleeAbility](#accessing-the-calleeability) 570 571 572### Creating a CalleeAbility 573 574For the CalleeAbility, 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. 575 5761. Configure the launch type of the UIAbility. 577 578 For example, set the launch type of the CalleeAbility to **singleton**. For details, see [UIAbility Component Launch Type](uiability-launch-type.md). 579 5802. Import the **UIAbility** module. 581 582 ```ts 583 import UIAbility from '@ohos.app.ability.UIAbility'; 584 ``` 585 5863. Define the agreed parcelable data. 587 588 The data formats sent and received by the CallerAbility and CalleeAbility must be consistent. In the following example, the data formats are number and string. 589 590 591 ```ts 592 export default class MyParcelable { 593 num: number = 0; 594 str: string = ''; 595 596 constructor(num, string) { 597 this.num = num; 598 this.str = string; 599 } 600 601 marshalling(messageSequence) { 602 messageSequence.writeInt(this.num); 603 messageSequence.writeString(this.str); 604 return true; 605 } 606 607 unmarshalling(messageSequence) { 608 this.num = messageSequence.readInt(); 609 this.str = messageSequence.readString(); 610 return true; 611 } 612 } 613 ``` 614 6154. Implement **Callee.on** and **Callee.off**. 616 617 The time to register a listener for the CalleeAbility 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 UIAbility and deregistered in **onDestroy**. After receiving parcelable data, the application processes the data and returns the data result. You need to implement processing based on service requirements. The sample code is as follows: 618 619 620 ```ts 621 const TAG: string = '[CalleeAbility]'; 622 const MSG_SEND_METHOD: string = 'CallSendMsg'; 623 624 function sendMsgCallback(data) { 625 console.info('CalleeSortFunc called'); 626 627 // Obtain the parcelable data sent by the CallerAbility. 628 let receivedData = new MyParcelable(0, ''); 629 data.readParcelable(receivedData); 630 console.info(`receiveData[${receivedData.num}, ${receivedData.str}]`); 631 632 // Process the data. 633 // Return the parcelable data result to the CallerAbility. 634 return new MyParcelable(receivedData.num + 1, `send ${receivedData.str} succeed`); 635 } 636 637 export default class CalleeAbility extends UIAbility { 638 onCreate(want, launchParam) { 639 try { 640 this.callee.on(MSG_SEND_METHOD, sendMsgCallback); 641 } catch (err) { 642 console.error(`Failed to register. Code is ${err.code}, message is ${err.message}`); 643 } 644 } 645 646 onDestroy() { 647 try { 648 this.callee.off(MSG_SEND_METHOD); 649 } catch (err) { 650 console.error(`Failed to unregister. Code is ${err.code}, message is ${err.message}`); 651 } 652 } 653 } 654 ``` 655 656 657### Accessing the CalleeAbility 658 6591. Import the **UIAbility** module. 660 661 ```ts 662 import UIAbility from '@ohos.app.ability.UIAbility'; 663 ``` 664 6652. Obtain the caller interface. 666 667 The **UIAbilityContext** attribute implements **startAbilityByCall** to obtain the caller object for communication. The following example uses **this.context** to obtain the **UIAbilityContext**, uses **startAbilityByCall** to start the CalleeAbility, obtain the caller object, and register the **onRelease** listener of the CallerAbility. You need to implement processing based on service requirements. 668 669 670 ```ts 671 // Register the onRelease() listener of the CallerAbility. 672 private regOnRelease(caller) { 673 try { 674 caller.on('release', (msg) => { 675 console.info(`caller onRelease is called ${msg}`); 676 }) 677 console.info('Succeeded in registering on release.'); 678 } catch (err) { 679 console.err(`Failed to caller register on release. Code is ${err.code}, message is ${err.message}`); 680 } 681 } 682 683 async onButtonGetCaller() { 684 try { 685 this.caller = await context.startAbilityByCall({ 686 bundleName: 'com.samples.CallApplication', 687 abilityName: 'CalleeAbility' 688 }); 689 if (this.caller === undefined) { 690 console.info('get caller failed') 691 return; 692 } 693 console.info('get caller success') 694 this.regOnRelease(this.caller) 695 } (err) { 696 console.err(`Failed to get caller. Code is ${err.code}, message is ${err.message}`); 697 } 698 } 699 ``` 700