1# @ohos.app.ability.UIAbility (UIAbility) 2 3UIAbility is an application component that has the UI. The UIAbility module, inherited from [Ability](js-apis-app-ability-ability.md), provides lifecycle callbacks such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration: 4 5- [Caller](#caller): an object returned by [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall). The CallerAbility (caller) uses this object to communicate with the CalleeAbility (callee). 6- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller). 7 8For details about the inheritance relationship of each ability, see [Inheritance Relationship](./js-apis-app-ability-ability.md#ability-inheritance-relationship). 9 10> **NOTE** 11> 12> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. 13> 14> The APIs of this module can be used only in the stage model. 15 16## Modules to Import 17 18```ts 19import { UIAbility } from '@kit.AbilityKit'; 20``` 21 22## Properties 23 24**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 25 26| Name| Type| Read-only| Optional| Description| 27| -------- | -------- | -------- | -------- | -------- | 28| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | No| No| Context of the UIAbility.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 29| launchWant | [Want](js-apis-app-ability-want.md) | No| No| Parameters for starting the UIAbility.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 30| lastRequestWant | [Want](js-apis-app-ability-want.md) | No| No| Parameters carried in the last request.<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 31| callee | [Callee](#callee) | No| No| Object that invokes the stub service.| 32 33## UIAbility.onCreate 34 35onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void 36 37Called to initialize the service logic when a UIAbility instance in the completely closed state is created. In other words, a UIAbility instance enters this lifecycle callback from a [cold start](../../application-models/uiability-intra-device-interaction.md#cold-starting-uiability). This API returns the result synchronously and does not support asynchronous callback. 38 39**Atomic service API**: This API can be used in atomic services since API version 11. 40 41**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 42 43**Parameters** 44 45| Name| Type| Mandatory| Description| 46| -------- | -------- | -------- | -------- | 47| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, including the ability name and bundle name.| 48| launchParam | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#launchparam) | Yes| Parameters for starting the UIAbility, and the reason for the last abnormal exit.| 49 50**Example** 51 52```ts 53import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 54 55class MyUIAbility extends UIAbility { 56 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 57 console.log(`onCreate, want: ${want.abilityName}`); 58 } 59} 60``` 61 62 63## UIAbility.onWindowStageCreate 64 65onWindowStageCreate(windowStage: window.WindowStage): void 66 67Called when a **WindowStage** is created for this UIAbility. 68 69**Atomic service API**: This API can be used in atomic services since API version 11. 70 71**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 72 73**Parameters** 74 75| Name| Type| Mandatory| Description| 76| -------- | -------- | -------- | -------- | 77| windowStage | [window.WindowStage](../apis-arkui/js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| 78 79**Example** 80 81```ts 82import { UIAbility } from '@kit.AbilityKit'; 83import { window } from '@kit.ArkUI'; 84 85class MyUIAbility extends UIAbility { 86 onWindowStageCreate(windowStage: window.WindowStage) { 87 console.log('onWindowStageCreate'); 88 } 89} 90``` 91 92 93## UIAbility.onWindowStageWillDestroy<sup>12+</sup> 94 95onWindowStageWillDestroy(windowStage: window.WindowStage): void 96 97Called when the **WindowStage** is about to be destroyed. 98 99**Atomic service API**: This API can be used in atomic services since API version 12. 100 101**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 102 103**Parameters** 104 105| Name| Type| Mandatory| Description| 106| -------- | -------- | -------- | -------- | 107| windowStage | [window.WindowStage](../apis-arkui/js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| 108 109**Example** 110 111```ts 112import { UIAbility } from '@kit.AbilityKit'; 113import { window } from '@kit.ArkUI'; 114 115class MyUIAbility extends UIAbility { 116 onWindowStageWillDestroy(windowStage: window.WindowStage) { 117 console.log('onWindowStageWillDestroy'); 118 } 119} 120``` 121 122 123## UIAbility.onWindowStageDestroy 124 125onWindowStageDestroy(): void 126 127Called when the **WindowStage** is destroyed for this UIAbility. 128 129**Atomic service API**: This API can be used in atomic services since API version 11. 130 131**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 132 133**Example** 134 135```ts 136import { UIAbility } from '@kit.AbilityKit'; 137 138class MyUIAbility extends UIAbility { 139 onWindowStageDestroy() { 140 console.log('onWindowStageDestroy'); 141 } 142} 143``` 144 145 146## UIAbility.onWindowStageRestore 147 148onWindowStageRestore(windowStage: window.WindowStage): void 149 150Called when the **WindowStage** is restored during the migration of this UIAbility, which is a multi-instance ability. 151 152**Atomic service API**: This API can be used in atomic services since API version 11. 153 154**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 155 156**Parameters** 157 158| Name| Type| Mandatory| Description| 159| -------- | -------- | -------- | -------- | 160| windowStage | [window.WindowStage](../apis-arkui/js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| 161 162**Example** 163 164```ts 165import { UIAbility } from '@kit.AbilityKit'; 166import { window } from '@kit.ArkUI'; 167 168class MyUIAbility extends UIAbility { 169 onWindowStageRestore(windowStage: window.WindowStage) { 170 console.log('onWindowStageRestore'); 171 } 172} 173``` 174 175 176## UIAbility.onDestroy 177 178onDestroy(): void | Promise<void> 179 180Called to clear resources when this UIAbility is destroyed. This API returns the result synchronously or uses a promise to return the result. 181 182**Atomic service API**: This API can be used in atomic services since API version 11. 183 184**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 185 186**Return value** 187 188| Type| Description| 189| -------- | -------- | 190| void \| Promise<void> | No return value or a Promise object that returns no result.| 191 192**Example** 193 194```ts 195import { UIAbility } from '@kit.AbilityKit'; 196 197class MyUIAbility extends UIAbility { 198 onDestroy() { 199 console.log('onDestroy'); 200 } 201} 202``` 203 204After the **onDestroy()** lifecycle callback is executed, the application may exit. Consequently, the asynchronous function (for example, asynchronously writing data to the database) in **onDestroy()** may fail to be executed. You can use the asynchronous lifecycle to ensure that the subsequent lifecycle continues only after the asynchronous function in **onDestroy()** finishes the execution. 205 206```ts 207import { UIAbility } from '@kit.AbilityKit'; 208 209class MyUIAbility extends UIAbility { 210 async onDestroy() { 211 console.log('onDestroy'); 212 // Call the asynchronous function. 213 } 214} 215``` 216 217## UIAbility.onForeground 218 219onForeground(): void 220 221Called when this UIAbility is switched from the background to the foreground. This API returns the result synchronously and does not support asynchronous callback. 222 223**Atomic service API**: This API can be used in atomic services since API version 11. 224 225**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 226 227**Example** 228 229```ts 230import { UIAbility } from '@kit.AbilityKit'; 231 232class MyUIAbility extends UIAbility { 233 onForeground() { 234 console.log('onForeground'); 235 } 236} 237``` 238 239 240## UIAbility.onBackground 241 242onBackground(): void 243 244Called when this UIAbility is switched from the foreground to the background. This API returns the result synchronously and does not support asynchronous callback. 245 246**Atomic service API**: This API can be used in atomic services since API version 11. 247 248**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 249 250**Example** 251 252```ts 253import { UIAbility } from '@kit.AbilityKit'; 254 255class MyUIAbility extends UIAbility { 256 onBackground() { 257 console.log('onBackground'); 258 } 259} 260``` 261 262 263## UIAbility.onContinue 264 265onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult | Promise<AbilityConstant.OnContinueResult> 266 267Called to save data during the UIAbility migration preparation process. 268 269> **NOTE** 270> 271> Since API version 12, **UIAbility.onContinue** supports the return value in the form of Promise\<[AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#oncontinueresult)\>. 272 273**Atomic service API**: This API can be used in atomic services since API version 11. 274 275**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 276 277**Parameters** 278 279| Name| Type| Mandatory| Description| 280| -------- | -------- | -------- | -------- | 281| wantParam | Record<string, Object> | Yes| **want** parameter.| 282 283**Return value** 284 285| Type| Description| 286| -------- | -------- | 287| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#oncontinueresult) \| Promise<[AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#oncontinueresult)> | Continuation result or Promise used to return the continuation result.| 288 289**Example** 290 291 ```ts 292 import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 293 294 class MyUIAbility extends UIAbility { 295 onContinue(wantParams: Record<string, Object>) { 296 console.log('onContinue'); 297 wantParams['myData'] = 'my1234567'; 298 return AbilityConstant.OnContinueResult.AGREE; 299 } 300 } 301 ``` 302 303An asynchronous API can be used to save data during ability continuation. 304 305 ```ts 306 import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 307 308 class MyUIAbility extends UIAbility { 309 async setWant(wantParams: Record<string, Object>) { 310 console.log('setWant start'); 311 for (let time = 0; time < 1000; ++time) { 312 wantParams[time] = time; 313 } 314 console.log('setWant end'); 315 } 316 317 async onContinue(wantParams: Record<string, Object>) { 318 console.log('onContinue'); 319 return this.setWant(wantParams).then(()=>{ 320 return AbilityConstant.OnContinueResult.AGREE; 321 }); 322 } 323 } 324 ``` 325 326 327## UIAbility.onNewWant 328 329onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void 330 331Called when a UIAbility instance that has undergone the following states is started again: started in the foreground, running in the foreground, and switched to the background. In other words, a UIAbility instance enters this lifecycle callback from a [hot start](../../application-models/uiability-intra-device-interaction.md#hot-starting-uiability). 332 333**Atomic service API**: This API can be used in atomic services since API version 11. 334 335**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 336 337**Parameters** 338 339| Name| Type| Mandatory| Description| 340| -------- | -------- | -------- | -------- | 341| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.| 342| launchParam | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#launchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.| 343 344**Example** 345 346```ts 347import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 348 349class MyUIAbility extends UIAbility { 350 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) { 351 console.log(`onNewWant, want: ${want.abilityName}`); 352 console.log(`onNewWant, launchParam: ${JSON.stringify(launchParam)}`); 353 } 354} 355``` 356 357## UIAbility.onDump 358 359onDump(params: Array\<string>): Array\<string> 360 361Called to dump the client information. This API can be used to dump non-sensitive information. 362 363**Atomic service API**: This API can be used in atomic services since API version 11. 364 365**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 366 367**Parameters** 368 369| Name| Type| Mandatory| Description| 370| -------- | -------- | -------- | -------- | 371| params | Array\<string> | Yes| Parameters in the form of a command.| 372 373**Return value** 374 375| Type| Description| 376| -------- | -------- | 377| Array\<string> | Dumped information array.| 378 379**Example** 380 381```ts 382import { UIAbility } from '@kit.AbilityKit'; 383 384class MyUIAbility extends UIAbility { 385 onDump(params: Array<string>) { 386 console.log(`dump, params: ${JSON.stringify(params)}`); 387 return ['params']; 388 } 389} 390``` 391 392 393## UIAbility.onSaveState 394 395onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>): AbilityConstant.OnSaveResult 396 397Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). When an application is faulty, the framework calls **onSaveState** to save the status of the UIAbility if auto-save is enabled. 398 399**Atomic service API**: This API can be used in atomic services since API version 11. 400 401**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 402 403**Parameters** 404 405| Name| Type| Mandatory| Description| 406| -------- | -------- | -------- | -------- | 407| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#statetype) | Yes| Reason for triggering the callback to save the UIAbility state.| 408| wantParam | Record<string, Object> | Yes| **want** parameter.| 409 410**Return value** 411 412| Type| Description| 413| -------- | -------- | 414| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#onsaveresult) | Whether the UIAbility state is saved.| 415 416**Example** 417 418```ts 419import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 420 421class MyUIAbility extends UIAbility { 422 onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>) { 423 console.log('onSaveState'); 424 wantParam['myData'] = 'my1234567'; 425 return AbilityConstant.OnSaveResult.RECOVERY_AGREE; 426 } 427} 428``` 429 430## UIAbility.onShare<sup>10+</sup> 431 432onShare(wantParam: Record<string, Object>): void 433 434Called by this UIAbility to set data to share in the cross-device sharing scenario. 435 436**Atomic service API**: This API can be used in atomic services since API version 11. 437 438**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 439 440**Parameters** 441 442| Name| Type| Mandatory| Description| 443| -------- | -------- | -------- | -------- | 444| wantParam | Record<string, Object> | Yes| Data to share.| 445 446**Example** 447 448```ts 449import { UIAbility } from '@kit.AbilityKit'; 450 451class MyUIAbility extends UIAbility { 452 onShare(wantParams: Record<string, Object>) { 453 console.log('onShare'); 454 wantParams['ohos.extra.param.key.shareUrl'] = 'example.com'; 455 } 456} 457``` 458 459## UIAbility.onPrepareToTerminate<sup>10+</sup> 460 461onPrepareToTerminate(): boolean 462 463Called when this UIAbility is about to terminate. It allows for additional actions to be performed before the UIAbility is officially terminated. For example, you can prompt the user to confirm whether they want to terminate the UIAbility. If the user confirms, you can call [terminateSelf](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) to terminate it. 464 465Currently, this API takes effect only on 2-in-1 devices. 466 467> **NOTE** 468> 469> Since API version 15, this callback is not executed when [UIAbility.onPrepareToTerminateAsync](#uiabilityonpreparetoterminateasync15) is implemented. When [AbilityStage.onPrepareTerminationAsync](js-apis-app-ability-abilityStage.md#abilitystageonprepareterminationasync15) or [AbilityStage.onPrepareTermination](js-apis-app-ability-abilityStage.md#abilitystageonpreparetermination15) is implemented, this callback is not executed if the user right-clicks the dock bar or system tray to close the UIAbility. 470 471**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE 472 473**Atomic service API**: This API can be used in atomic services since API version 11. 474 475**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 476 477**Return value** 478 479| Type| Description| 480| -- | -- | 481| boolean | Whether to terminate the UIAbility. The value **true** means that the termination process is canceled. The value **false** means to continue terminating the UIAbility.| 482 483**Example** 484 485```ts 486import { UIAbility, Want } from '@kit.AbilityKit'; 487import { BusinessError } from '@kit.BasicServicesKit'; 488 489export default class EntryAbility extends UIAbility { 490 onPrepareToTerminate() { 491 // Define a pre-termination operation, 492 // for example, starting another UIAbility and performing asynchronous termination based on the startup result. 493 let want: Want = { 494 bundleName: "com.example.myapplication", 495 moduleName: "entry", 496 abilityName: "SecondAbility" 497 } 498 this.context.startAbilityForResult(want) 499 .then((result)=>{ 500 // Obtain the startup result and terminate the current UIAbility when resultCode in the return value is 0. 501 console.log('startAbilityForResult success, resultCode is ' + result.resultCode); 502 if (result.resultCode === 0) { 503 this.context.terminateSelf(); 504 } 505 }).catch((err: BusinessError)=>{ 506 // Exception handling. 507 console.error('startAbilityForResult failed, err:' + JSON.stringify(err)); 508 this.context.terminateSelf(); 509 }) 510 511 return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled. 512 } 513} 514``` 515 516## UIAbility.onPrepareToTerminateAsync<sup>15+</sup> 517 518onPrepareToTerminateAsync(): Promise\<boolean> 519 520Called when this UIAbility is about to terminate. It allows for additional actions to be performed before the UIAbility is officially terminated. This API uses a promise to return the result. For example, you can prompt the user to confirm whether they want to terminate the UIAbility. If the user confirms, you can call [terminateSelf](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself) to terminate it. 521 522Currently, this API takes effect only on 2-in-1 devices. 523 524> **NOTE** 525> 526> - When [AbilityStage.onPrepareTerminationAsync](js-apis-app-ability-abilityStage.md#abilitystageonprepareterminationasync15) or [AbilityStage.onPrepareTermination](js-apis-app-ability-abilityStage.md#abilitystageonpreparetermination15) is implemented, this callback is not executed if the user right-clicks the dock bar or system tray to close the UIAbility. 527> 528> - If an asynchronous callback crashes, it will be handled as a timeout. If the UIAbility does not respond within 10 seconds, it will be terminated forcibly. 529 530**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE 531 532**Atomic service API**: This API can be used in atomic services since API version 15. 533 534**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 535 536**Return value** 537 538| Type| Description| 539| -- | -- | 540| Promise\<boolean> | Promise used to return the result. The value **true** means that the termination process is canceled. The value **false** means to continue terminating the UIAbility.| 541 542**Example** 543 544```ts 545import { UIAbility } from '@kit.AbilityKit'; 546 547export default class EntryAbility extends UIAbility { 548 async onPrepareToTerminateAsync(): Promise<boolean> { 549 await new Promise<boolean>((res, rej) => { 550 setTimeout (res, 2000); // Execute the operation 2 seconds later. 551 }); 552 return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled. 553 } 554} 555``` 556 557## UIAbility.onBackPressed<sup>10+</sup> 558 559onBackPressed(): boolean 560 561Called when an operation of going back to the previous page is triggered on this UIAbility. The return value determines whether to destroy the UIAbility instance. 562 563- When the target SDK version is earlier than 12, the default return value is **false**, indicating that the UIAbility will be destroyed. 564- When the target SDK version is 12 or later, the default return value is **true**, indicating that the UIAbility will be moved to the background and will not be destroyed. 565 566**Atomic service API**: This API can be used in atomic services since API version 11. 567 568**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 569 570**Return value** 571 572| Type| Description| 573| -- | -- | 574| boolean | The value **true** means that the UIAbility instance will be moved to the background and will not be destroyed, and **false** means that the UIAbility instance will be destroyed.| 575 576**Example** 577 578```ts 579import { UIAbility } from '@kit.AbilityKit'; 580 581export default class EntryAbility extends UIAbility { 582 onBackPressed() { 583 return true; 584 } 585} 586``` 587 588## UIAbility.onCollaborate<sup>18+</sup> 589 590onCollaborate(wantParam: Record<string, Object>): AbilityConstant.CollaborateResult 591 592Callback invoked to return the collaboration result in multi-device collaboration scenarios. 593 594 **NOTE** 595- This callback does not support ability launch in specified mode. 596- When you use methods such as **startAbility()** to start an application, you must include **FLAG_ABILITY_ON_COLLABORATE** in [Flags](js-apis-ability-wantConstant.md#flags) in the Want object. 597- During a cold start, this callback must be invoked before [onForeground](#uiabilityonforeground) or after [onBackground](#uiabilityonbackground). During a hot start, this callback must be invoked before [onNewWant](#uiabilityonnewwant). 598 599 600**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 601 602**Parameters** 603 604| Name | Type | Mandatory| Description | 605| --------- | --------------------------------- | ---- | ------------------------------------------------------------ | 606| wantParam | Record<string, Object> | Yes | Want parameter, which supports only the key **"ohos.extra.param.key.supportCollaborateIndex"**. The key can be used to obtain the data passed by the caller and perform corresponding processing.| 607 608**Return value** 609 610| Name | Value | Description | 611| -------- | ---- | ---------- | 612| [AbilityConstant.CollaborateResult](js-apis-app-ability-abilityConstant.md#collaborateresult18) | Collaborator result, that is, whether the target application accepts the collaboration request.| 613 614**Example** 615 616```ts 617import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 618 619class MyAbility extends UIAbility { 620 onCollaborate(wantParam: Record<string, Object>) { 621 return AbilityConstant.CollaborateResult.ACCEPT; 622 } 623} 624``` 625 626## Caller 627 628Implements sending of parcelable data to the target UIAbility when the CallerAbility invokes the target UIAbility (CalleeAbility). 629 630### Caller.call 631 632call(method: string, data: rpc.Parcelable): Promise<void> 633 634Sends parcelable data to the target UIAbility. This API uses a promise to return the result. 635 636**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 637 638**Parameters** 639 640| Name| Type| Mandatory| Description| 641| -------- | -------- | -------- | -------- | 642| method | string | Yes| Notification message string negotiated between the two UIAbilities. The message is used to instruct the callee to register a function to receive the parcelable data.| 643| data | [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| 644 645**Return value** 646 647| Type| Description| 648| -------- | -------- | 649| Promise<void> | Promise that returns no value.| 650 651**Error codes** 652 653For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 654 655| ID| Error Message| 656| ------- | -------------------------------- | 657| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 658| 16200001 | Caller released. The caller has been released. | 659| 16200002 | The callee does not exist. | 660| 16000050 | Internal error. | 661 662**Example** 663 664```ts 665import { UIAbility, Caller } from '@kit.AbilityKit'; 666import { window } from '@kit.ArkUI'; 667import { rpc } from '@kit.IPCKit'; 668import { BusinessError } from '@kit.BasicServicesKit'; 669 670class MyMessageAble implements rpc.Parcelable { // Custom parcelable data structure. 671 name: string 672 str: string 673 num: number = 1 674 constructor(name: string, str: string) { 675 this.name = name; 676 this.str = str; 677 } 678 marshalling(messageSequence: rpc.MessageSequence) { 679 messageSequence.writeInt(this.num); 680 messageSequence.writeString(this.str); 681 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 682 return true; 683 } 684 unmarshalling(messageSequence: rpc.MessageSequence) { 685 this.num = messageSequence.readInt(); 686 this.str = messageSequence.readString(); 687 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 688 return true; 689 } 690}; 691let method = 'call_Function'; // Notification message string negotiated by the two UIAbilities. 692let caller: Caller; 693 694export default class MainUIAbility extends UIAbility { 695 onWindowStageCreate(windowStage: window.WindowStage) { 696 this.context.startAbilityByCall({ 697 bundleName: 'com.example.myservice', 698 abilityName: 'MainUIAbility', 699 deviceId: '' 700 }).then((obj) => { 701 caller = obj; 702 let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable. 703 caller.call(method, msg) 704 .then(() => { 705 console.log('Caller call() called'); 706 }) 707 .catch((callErr: BusinessError) => { 708 console.error(`Caller.call catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`); 709 }); 710 }).catch((err: BusinessError) => { 711 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 712 }); 713 } 714} 715``` 716 717 718### Caller.callWithResult 719 720callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> 721 722Sends parcelable data to the target UIAbility and obtains the parcelable data returned by the target UIAbility. This API uses a promise to return the result. 723 724**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 725 726**Parameters** 727 728| Name| Type| Mandatory| Description| 729| -------- | -------- | -------- | -------- | 730| method | string | Yes| Notification message string negotiated between the two UIAbilities. The message is used to instruct the callee to register a function to receive the parcelable data.| 731| data | [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| 732 733**Return value** 734 735| Type| Description| 736| -------- | -------- | 737| Promise<[rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9)> | Promise used to return the parcelable data from the target UIAbility.| 738 739**Error codes** 740 741For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 742 743| ID| Error Message| 744| ------- | -------------------------------- | 745| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 746| 16200001 | Caller released. The caller has been released. | 747| 16200002 | The callee does not exist. | 748| 16000050 | Internal error. | 749 750**Example** 751 752```ts 753import { UIAbility, Caller } from '@kit.AbilityKit'; 754import { window } from '@kit.ArkUI'; 755import { rpc } from '@kit.IPCKit'; 756import { BusinessError } from '@kit.BasicServicesKit'; 757 758class MyMessageAble implements rpc.Parcelable { 759 name: string 760 str: string 761 num: number = 1 762 constructor(name: string, str: string) { 763 this.name = name; 764 this.str = str; 765 } 766 marshalling(messageSequence: rpc.MessageSequence) { 767 messageSequence.writeInt(this.num); 768 messageSequence.writeString(this.str); 769 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 770 return true; 771 } 772 unmarshalling(messageSequence: rpc.MessageSequence) { 773 this.num = messageSequence.readInt(); 774 this.str = messageSequence.readString(); 775 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 776 return true; 777 } 778}; 779let method = 'call_Function'; 780let caller: Caller; 781 782export default class MainUIAbility extends UIAbility { 783 onWindowStageCreate(windowStage: window.WindowStage) { 784 this.context.startAbilityByCall({ 785 bundleName: 'com.example.myservice', 786 abilityName: 'MainUIAbility', 787 deviceId: '' 788 }).then((obj) => { 789 caller = obj; 790 let msg = new MyMessageAble('msg', 'world'); 791 caller.callWithResult(method, msg) 792 .then((data) => { 793 console.log('Caller callWithResult() called'); 794 let retmsg = new MyMessageAble('msg', 'world'); 795 data.readParcelable(retmsg); 796 }) 797 .catch((callErr: BusinessError) => { 798 console.error(`Caller.callWithResult catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`); 799 }); 800 }).catch((err: BusinessError) => { 801 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 802 }); 803 } 804} 805``` 806 807 808### Caller.release 809 810release(): void 811 812Releases the caller interface of the target UIAbility. 813 814**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 815 816**Error codes** 817 818For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 819 820| ID| Error Message| 821| ------- | -------------------------------- | 822| 16200001 | Caller released. The caller has been released. | 823| 16200002 | The callee does not exist. | 824 825**Example** 826 827```ts 828import { UIAbility, Caller } from '@kit.AbilityKit'; 829import { window } from '@kit.ArkUI'; 830import { BusinessError } from '@kit.BasicServicesKit'; 831 832let caller: Caller; 833 834export default class MainUIAbility extends UIAbility { 835 onWindowStageCreate(windowStage: window.WindowStage) { 836 this.context.startAbilityByCall({ 837 bundleName: 'com.example.myservice', 838 abilityName: 'MainUIAbility', 839 deviceId: '' 840 }).then((obj) => { 841 caller = obj; 842 try { 843 caller.release(); 844 } catch (releaseErr) { 845 console.error(`Caller.release catch error, error.code: ${releaseErr.code}, error.message: ${releaseErr.message}`); 846 } 847 }).catch((err: BusinessError) => { 848 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 849 }); 850 } 851} 852``` 853 854### Caller.onRelease 855 856 onRelease(callback: OnReleaseCallback): void 857 858Called when the stub on the target UIAbility is disconnected. This API uses an asynchronous callback to return the result. 859 860**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 861 862**Parameters** 863 864| Name| Type| Mandatory| Description| 865| -------- | -------- | -------- | -------- | 866| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 867 868**Error codes** 869 870For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 871 872| ID| Error Message| 873| ------- | -------------------------------- | 874| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 875| 16200001 | Caller released. The caller has been released. | 876 877**Example** 878 879```ts 880import { UIAbility, Caller } from '@kit.AbilityKit'; 881import { window } from '@kit.ArkUI'; 882import { BusinessError } from '@kit.BasicServicesKit'; 883 884let caller: Caller; 885 886export default class MainUIAbility extends UIAbility { 887 onWindowStageCreate(windowStage: window.WindowStage) { 888 this.context.startAbilityByCall({ 889 bundleName: 'com.example.myservice', 890 abilityName: 'MainUIAbility', 891 deviceId: '' 892 }).then((obj) => { 893 caller = obj; 894 try { 895 caller.onRelease((str) => { 896 console.log(`Caller OnRelease CallBack is called ${str}`); 897 }); 898 } catch (error) { 899 console.error(`Caller.onRelease catch error, error.code: $error.code}, error.message: ${error.message}`); 900 } 901 }).catch((err: BusinessError) => { 902 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 903 }); 904 } 905} 906``` 907 908### Caller.onRemoteStateChange<sup>10+</sup> 909 910onRemoteStateChange(callback: OnRemoteStateChangeCallback): void 911 912Called when the remote UIAbility state changes in the collaboration scenario. This API uses an asynchronous callback to return the result. 913 914**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 915 916**Parameters** 917 918| Name| Type| Mandatory| Description| 919| -------- | -------- | -------- | -------- | 920| callback | [OnRemoteStateChangeCallback](#onremotestatechangecallback10) | Yes| Callback used to return the result.| 921 922**Error codes** 923 924For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 925 926| ID| Error Message| 927| ------- | -------------------------------- | 928| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 929| 16200001 | Caller released. The caller has been released. | 930 931**Example** 932 933```ts 934import { UIAbility, Caller } from '@kit.AbilityKit'; 935import { window } from '@kit.ArkUI'; 936import { BusinessError } from '@kit.BasicServicesKit'; 937 938let caller: Caller; 939let dstDeviceId: string; 940 941export default class MainAbility extends UIAbility { 942 onWindowStageCreate(windowStage: window.WindowStage) { 943 this.context.startAbilityByCall({ 944 bundleName: 'com.example.myservice', 945 abilityName: 'MainUIAbility', 946 deviceId: dstDeviceId 947 }).then((obj) => { 948 caller = obj; 949 try { 950 caller.onRemoteStateChange((str) => { 951 console.log('Remote state changed ' + str); 952 }); 953 } catch (error) { 954 console.error(`Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}`); 955 } 956 }).catch((err: BusinessError) => { 957 console.error(`Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}`); 958 }) 959 } 960} 961``` 962 963### Caller.on('release') 964 965on(type: 'release', callback: OnReleaseCallback): void 966 967Called when the stub on the target UIAbility is disconnected. This API uses an asynchronous callback to return the result. 968 969**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 970 971**Parameters** 972 973| Name| Type| Mandatory| Description| 974| -------- | -------- | -------- | -------- | 975| type | string | Yes| Event type. The value is fixed at **'release'**.| 976| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 977 978**Error codes** 979 980For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 981 982| ID| Error Message| 983| ------- | -------------------------------- | 984| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 985| 16200001 | Caller released. The caller has been released. | 986 987**Example** 988 989```ts 990import { UIAbility, Caller } from '@kit.AbilityKit'; 991import { window } from '@kit.ArkUI'; 992import { BusinessError } from '@kit.BasicServicesKit'; 993 994let caller: Caller; 995 996export default class MainUIAbility extends UIAbility { 997 onWindowStageCreate(windowStage: window.WindowStage) { 998 this.context.startAbilityByCall({ 999 bundleName: 'com.example.myservice', 1000 abilityName: 'MainUIAbility', 1001 deviceId: '' 1002 }).then((obj) => { 1003 caller = obj; 1004 try { 1005 caller.on('release', (str) => { 1006 console.log(`Caller OnRelease CallBack is called ${str}`); 1007 }); 1008 } catch (error) { 1009 console.error(`Caller.on catch error, error.code: ${error.code}, error.message: ${error.message}`); 1010 } 1011 }).catch((err: BusinessError) => { 1012 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1013 }); 1014 } 1015} 1016``` 1017 1018### Caller.off('release') 1019 1020off(type: 'release', callback: OnReleaseCallback): void 1021 1022Unregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved. This API uses an asynchronous callback to return the result. 1023 1024**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1025 1026**Parameters** 1027 1028| Name| Type| Mandatory| Description| 1029| -------- | -------- | -------- | -------- | 1030| type | string | Yes| Event type. The value is fixed at **'release'**.| 1031| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 1032 1033**Error codes** 1034 1035For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1036 1037| ID| Error Message| 1038| ------- | -------------------------------- | 1039| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1040 1041**Example** 1042 1043```ts 1044import { UIAbility, Caller, OnReleaseCallback } from '@kit.AbilityKit'; 1045import { window } from '@kit.ArkUI'; 1046import { BusinessError } from '@kit.BasicServicesKit'; 1047 1048let caller: Caller; 1049 1050export default class MainUIAbility extends UIAbility { 1051 onWindowStageCreate(windowStage: window.WindowStage) { 1052 this.context.startAbilityByCall({ 1053 bundleName: 'com.example.myservice', 1054 abilityName: 'MainUIAbility', 1055 deviceId: '' 1056 }).then((obj) => { 1057 caller = obj; 1058 try { 1059 let onReleaseCallBack: OnReleaseCallback = (str) => { 1060 console.log(`Caller OnRelease CallBack is called ${str}`); 1061 }; 1062 caller.on('release', onReleaseCallBack); 1063 caller.off('release', onReleaseCallBack); 1064 } catch (error) { 1065 console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1066 } 1067 }).catch((err: BusinessError) => { 1068 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1069 }); 1070 } 1071} 1072``` 1073 1074### Caller.off('release') 1075 1076off(type: 'release'): void 1077 1078Unregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved. 1079 1080**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1081 1082**Parameters** 1083 1084| Name| Type| Mandatory| Description| 1085| -------- | -------- | -------- | -------- | 1086| type | string | Yes| Event type. The value is fixed at **'release'**.| 1087 1088**Error codes** 1089 1090For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1091 1092| ID| Error Message| 1093| ------- | -------------------------------- | 1094| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1095 1096**Example** 1097 1098```ts 1099import { UIAbility, Caller, OnReleaseCallback } from '@kit.AbilityKit'; 1100import { window } from '@kit.ArkUI'; 1101import { BusinessError } from '@kit.BasicServicesKit'; 1102 1103let caller: Caller; 1104 1105export default class MainUIAbility extends UIAbility { 1106 onWindowStageCreate(windowStage: window.WindowStage) { 1107 this.context.startAbilityByCall({ 1108 bundleName: 'com.example.myservice', 1109 abilityName: 'MainUIAbility', 1110 deviceId: '' 1111 }).then((obj) => { 1112 caller = obj; 1113 try { 1114 let onReleaseCallBack: OnReleaseCallback = (str) => { 1115 console.log(`Caller OnRelease CallBack is called ${str}`); 1116 }; 1117 caller.on('release', onReleaseCallBack); 1118 caller.off('release'); 1119 } catch (error) { 1120 console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1121 } 1122 }).catch((err: BusinessError) => { 1123 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1124 }); 1125 } 1126} 1127``` 1128 1129## Callee 1130 1131Implements callbacks for caller notification registration and deregistration. 1132 1133### Callee.on 1134 1135on(method: string, callback: CalleeCallback): void 1136 1137Registers a caller notification callback, which is invoked when the target UIAbility registers a function. 1138 1139**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1140 1141**Parameters** 1142 1143| Name| Type| Mandatory| Description| 1144| -------- | -------- | -------- | -------- | 1145| method | string | Yes| Notification message string negotiated between the two UIAbilities.| 1146| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) type. The callback must return at least one empty [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) object. Otherwise, the function execution fails.| 1147 1148**Error codes** 1149 1150For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1151 1152| ID| Error Message| 1153| ------- | -------------------------------- | 1154| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1155| 16200004 | The method has been registered. | 1156| 16000050 | Internal error. | 1157 1158**Example** 1159 1160```ts 1161import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1162import { rpc } from '@kit.IPCKit'; 1163 1164class MyMessageAble implements rpc.Parcelable { 1165 name: string 1166 str: string 1167 num: number = 1 1168 constructor(name: string, str: string) { 1169 this.name = name; 1170 this.str = str; 1171 } 1172 marshalling(messageSequence: rpc.MessageSequence) { 1173 messageSequence.writeInt(this.num); 1174 messageSequence.writeString(this.str); 1175 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 1176 return true; 1177 } 1178 unmarshalling(messageSequence: rpc.MessageSequence) { 1179 this.num = messageSequence.readInt(); 1180 this.str = messageSequence.readString(); 1181 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 1182 return true; 1183 } 1184}; 1185let method = 'call_Function'; 1186 1187function funcCallBack(pdata: rpc.MessageSequence) { 1188 console.log(`Callee funcCallBack is called ${pdata}`); 1189 let msg = new MyMessageAble('test', ''); 1190 pdata.readParcelable(msg); 1191 return new MyMessageAble('test1', 'Callee test'); 1192} 1193export default class MainUIAbility extends UIAbility { 1194 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1195 console.log('Callee onCreate is called'); 1196 try { 1197 this.callee.on(method, funcCallBack); 1198 } catch (error) { 1199 console.error(`Callee.on catch error, error.code: ${error.code}, error.message: ${error.message}`); 1200 } 1201 } 1202} 1203``` 1204 1205### Callee.off 1206 1207off(method: string): void 1208 1209Unregisters a caller notification callback, which is invoked when the target UIAbility registers a function. 1210 1211**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1212 1213**Parameters** 1214 1215| Name| Type| Mandatory| Description| 1216| -------- | -------- | -------- | -------- | 1217| method | string | Yes| Registered notification message string.| 1218 1219**Error codes** 1220 1221For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1222 1223| ID| Error Message| 1224| ------- | -------------------------------- | 1225| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1226| 16200005 | The method has not been registered. | 1227| 16000050 | Internal error. | 1228 1229**Example** 1230 1231```ts 1232import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1233 1234let method = 'call_Function'; 1235 1236export default class MainUIAbility extends UIAbility { 1237 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1238 console.log('Callee onCreate is called'); 1239 try { 1240 this.callee.off(method); 1241 } catch (error) { 1242 console.error(`Callee.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1243 } 1244 } 1245} 1246``` 1247 1248## OnReleaseCallback 1249 1250### (msg: string) 1251 1252(msg: string): void 1253 1254Defines the callback that is invoked when the stub on the target UIAbility is disconnected. 1255 1256**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1257 1258**Parameters** 1259 1260| Name| Type| Mandatory| Description| 1261| --- | ----- | --- | -------- | 1262| msg | string | Yes| Message used for disconnection.| 1263 1264## OnRemoteStateChangeCallback<sup>10+</sup> 1265 1266### (msg: string) 1267 1268(msg: string): void 1269 1270Defines the callback that is invoked when the remote UIAbility state changes in the collaboration scenario. 1271 1272**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1273 1274**Parameters** 1275 1276| Name| Type| Mandatory| Description| 1277| --- | ----- | --- | -------- | 1278| msg | string | Yes| Message used for disconnection.| 1279 1280## CalleeCallback 1281 1282### (indata: rpc.MessageSequence) 1283 1284(indata: rpc.MessageSequence): rpc.Parcelable 1285 1286Defines the callback of the registration message notification of the UIAbility. 1287 1288**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1289 1290**Parameters** 1291 1292| Name| Type| Mandatory| Description| 1293| --- | ----- | --- | -------- | 1294| indata | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes| Data to be transferred.| 1295 1296**Return value** 1297 1298| Type | Description | 1299| ------------ | ------------------------------------- | 1300| [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Returned data object.| 1301