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). If automatic state saving is enabled, **onSaveState** is called to save the state of this UIAbility. 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## Caller 589 590Implements sending of parcelable data to the target UIAbility when the CallerAbility invokes the target UIAbility (CalleeAbility). 591 592### Caller.call 593 594call(method: string, data: rpc.Parcelable): Promise<void> 595 596Sends parcelable data to the target UIAbility. This API uses a promise to return the result. 597 598**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 599 600**Parameters** 601 602| Name| Type| Mandatory| Description| 603| -------- | -------- | -------- | -------- | 604| 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.| 605| data | [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| 606 607**Return value** 608 609| Type| Description| 610| -------- | -------- | 611| Promise<void> | Promise that returns no value.| 612 613**Error codes** 614 615For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 616 617| ID| Error Message| 618| ------- | -------------------------------- | 619| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 620| 16200001 | Caller released. The caller has been released. | 621| 16200002 | The callee does not exist. | 622| 16000050 | Internal error. | 623 624**Example** 625 626```ts 627import { UIAbility, Caller } from '@kit.AbilityKit'; 628import { window } from '@kit.ArkUI'; 629import { rpc } from '@kit.IPCKit'; 630import { BusinessError } from '@kit.BasicServicesKit'; 631 632class MyMessageAble implements rpc.Parcelable { // Custom parcelable data structure. 633 name: string 634 str: string 635 num: number = 1 636 constructor(name: string, str: string) { 637 this.name = name; 638 this.str = str; 639 } 640 marshalling(messageSequence: rpc.MessageSequence) { 641 messageSequence.writeInt(this.num); 642 messageSequence.writeString(this.str); 643 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 644 return true; 645 } 646 unmarshalling(messageSequence: rpc.MessageSequence) { 647 this.num = messageSequence.readInt(); 648 this.str = messageSequence.readString(); 649 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 650 return true; 651 } 652}; 653let method = 'call_Function'; // Notification message string negotiated by the two UIAbilities. 654let caller: Caller; 655 656export default class MainUIAbility extends UIAbility { 657 onWindowStageCreate(windowStage: window.WindowStage) { 658 this.context.startAbilityByCall({ 659 bundleName: 'com.example.myservice', 660 abilityName: 'MainUIAbility', 661 deviceId: '' 662 }).then((obj) => { 663 caller = obj; 664 let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable. 665 caller.call(method, msg) 666 .then(() => { 667 console.log('Caller call() called'); 668 }) 669 .catch((callErr: BusinessError) => { 670 console.error(`Caller.call catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`); 671 }); 672 }).catch((err: BusinessError) => { 673 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 674 }); 675 } 676} 677``` 678 679 680### Caller.callWithResult 681 682callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> 683 684Sends 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. 685 686**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 687 688**Parameters** 689 690| Name| Type| Mandatory| Description| 691| -------- | -------- | -------- | -------- | 692| 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.| 693| data | [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| 694 695**Return value** 696 697| Type| Description| 698| -------- | -------- | 699| Promise<[rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9)> | Promise used to return the parcelable data from the target UIAbility.| 700 701**Error codes** 702 703For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 704 705| ID| Error Message| 706| ------- | -------------------------------- | 707| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 708| 16200001 | Caller released. The caller has been released. | 709| 16200002 | The callee does not exist. | 710| 16000050 | Internal error. | 711 712**Example** 713 714```ts 715import { UIAbility, Caller } from '@kit.AbilityKit'; 716import { window } from '@kit.ArkUI'; 717import { rpc } from '@kit.IPCKit'; 718import { BusinessError } from '@kit.BasicServicesKit'; 719 720class MyMessageAble implements rpc.Parcelable { 721 name: string 722 str: string 723 num: number = 1 724 constructor(name: string, str: string) { 725 this.name = name; 726 this.str = str; 727 } 728 marshalling(messageSequence: rpc.MessageSequence) { 729 messageSequence.writeInt(this.num); 730 messageSequence.writeString(this.str); 731 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 732 return true; 733 } 734 unmarshalling(messageSequence: rpc.MessageSequence) { 735 this.num = messageSequence.readInt(); 736 this.str = messageSequence.readString(); 737 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 738 return true; 739 } 740}; 741let method = 'call_Function'; 742let caller: Caller; 743 744export default class MainUIAbility extends UIAbility { 745 onWindowStageCreate(windowStage: window.WindowStage) { 746 this.context.startAbilityByCall({ 747 bundleName: 'com.example.myservice', 748 abilityName: 'MainUIAbility', 749 deviceId: '' 750 }).then((obj) => { 751 caller = obj; 752 let msg = new MyMessageAble('msg', 'world'); 753 caller.callWithResult(method, msg) 754 .then((data) => { 755 console.log('Caller callWithResult() called'); 756 let retmsg = new MyMessageAble('msg', 'world'); 757 data.readParcelable(retmsg); 758 }) 759 .catch((callErr: BusinessError) => { 760 console.error(`Caller.callWithResult catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`); 761 }); 762 }).catch((err: BusinessError) => { 763 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 764 }); 765 } 766} 767``` 768 769 770### Caller.release 771 772release(): void 773 774Releases the caller interface of the target UIAbility. 775 776**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 777 778**Error codes** 779 780For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 781 782| ID| Error Message| 783| ------- | -------------------------------- | 784| 16200001 | Caller released. The caller has been released. | 785| 16200002 | The callee does not exist. | 786 787**Example** 788 789```ts 790import { UIAbility, Caller } from '@kit.AbilityKit'; 791import { window } from '@kit.ArkUI'; 792import { BusinessError } from '@kit.BasicServicesKit'; 793 794let caller: Caller; 795 796export default class MainUIAbility extends UIAbility { 797 onWindowStageCreate(windowStage: window.WindowStage) { 798 this.context.startAbilityByCall({ 799 bundleName: 'com.example.myservice', 800 abilityName: 'MainUIAbility', 801 deviceId: '' 802 }).then((obj) => { 803 caller = obj; 804 try { 805 caller.release(); 806 } catch (releaseErr) { 807 console.error(`Caller.release catch error, error.code: ${releaseErr.code}, error.message: ${releaseErr.message}`); 808 } 809 }).catch((err: BusinessError) => { 810 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 811 }); 812 } 813} 814``` 815 816### Caller.onRelease 817 818 onRelease(callback: OnReleaseCallback): void 819 820Called when the stub on the target UIAbility is disconnected. This API uses an asynchronous callback to return the result. 821 822**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 823 824**Parameters** 825 826| Name| Type| Mandatory| Description| 827| -------- | -------- | -------- | -------- | 828| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 829 830**Error codes** 831 832For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 833 834| ID| Error Message| 835| ------- | -------------------------------- | 836| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 837| 16200001 | Caller released. The caller has been released. | 838 839**Example** 840 841```ts 842import { UIAbility, Caller } from '@kit.AbilityKit'; 843import { window } from '@kit.ArkUI'; 844import { BusinessError } from '@kit.BasicServicesKit'; 845 846let caller: Caller; 847 848export default class MainUIAbility extends UIAbility { 849 onWindowStageCreate(windowStage: window.WindowStage) { 850 this.context.startAbilityByCall({ 851 bundleName: 'com.example.myservice', 852 abilityName: 'MainUIAbility', 853 deviceId: '' 854 }).then((obj) => { 855 caller = obj; 856 try { 857 caller.onRelease((str) => { 858 console.log(`Caller OnRelease CallBack is called ${str}`); 859 }); 860 } catch (error) { 861 console.error(`Caller.onRelease catch error, error.code: $error.code}, error.message: ${error.message}`); 862 } 863 }).catch((err: BusinessError) => { 864 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 865 }); 866 } 867} 868``` 869 870### Caller.onRemoteStateChange<sup>10+</sup> 871 872onRemoteStateChange(callback: OnRemoteStateChangeCallback): void 873 874Called when the remote UIAbility state changes in the collaboration scenario. This API uses an asynchronous callback to return the result. 875 876**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 877 878**Parameters** 879 880| Name| Type| Mandatory| Description| 881| -------- | -------- | -------- | -------- | 882| callback | [OnRemoteStateChangeCallback](#onremotestatechangecallback10) | Yes| Callback used to return the result.| 883 884**Error codes** 885 886For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 887 888| ID| Error Message| 889| ------- | -------------------------------- | 890| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 891| 16200001 | Caller released. The caller has been released. | 892 893**Example** 894 895```ts 896import { UIAbility, Caller } from '@kit.AbilityKit'; 897import { window } from '@kit.ArkUI'; 898import { BusinessError } from '@kit.BasicServicesKit'; 899 900let caller: Caller; 901let dstDeviceId: string; 902 903export default class MainAbility extends UIAbility { 904 onWindowStageCreate(windowStage: window.WindowStage) { 905 this.context.startAbilityByCall({ 906 bundleName: 'com.example.myservice', 907 abilityName: 'MainUIAbility', 908 deviceId: dstDeviceId 909 }).then((obj) => { 910 caller = obj; 911 try { 912 caller.onRemoteStateChange((str) => { 913 console.log('Remote state changed ' + str); 914 }); 915 } catch (error) { 916 console.error(`Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}`); 917 } 918 }).catch((err: BusinessError) => { 919 console.error(`Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}`); 920 }) 921 } 922} 923``` 924 925### Caller.on('release') 926 927on(type: 'release', callback: OnReleaseCallback): void 928 929Called when the stub on the target UIAbility is disconnected. This API uses an asynchronous callback to return the result. 930 931**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 932 933**Parameters** 934 935| Name| Type| Mandatory| Description| 936| -------- | -------- | -------- | -------- | 937| type | string | Yes| Event type. The value is fixed at **'release'**.| 938| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 939 940**Error codes** 941 942For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 943 944| ID| Error Message| 945| ------- | -------------------------------- | 946| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 947| 16200001 | Caller released. The caller has been released. | 948 949**Example** 950 951```ts 952import { UIAbility, Caller } from '@kit.AbilityKit'; 953import { window } from '@kit.ArkUI'; 954import { BusinessError } from '@kit.BasicServicesKit'; 955 956let caller: Caller; 957 958export default class MainUIAbility extends UIAbility { 959 onWindowStageCreate(windowStage: window.WindowStage) { 960 this.context.startAbilityByCall({ 961 bundleName: 'com.example.myservice', 962 abilityName: 'MainUIAbility', 963 deviceId: '' 964 }).then((obj) => { 965 caller = obj; 966 try { 967 caller.on('release', (str) => { 968 console.log(`Caller OnRelease CallBack is called ${str}`); 969 }); 970 } catch (error) { 971 console.error(`Caller.on catch error, error.code: ${error.code}, error.message: ${error.message}`); 972 } 973 }).catch((err: BusinessError) => { 974 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 975 }); 976 } 977} 978``` 979 980### Caller.off('release') 981 982off(type: 'release', callback: OnReleaseCallback): void 983 984Deregisters 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. 985 986**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 987 988**Parameters** 989 990| Name| Type| Mandatory| Description| 991| -------- | -------- | -------- | -------- | 992| type | string | Yes| Event type. The value is fixed at **'release'**.| 993| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 994 995**Error codes** 996 997For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 998 999| ID| Error Message| 1000| ------- | -------------------------------- | 1001| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1002 1003**Example** 1004 1005```ts 1006import { UIAbility, Caller, OnReleaseCallback } from '@kit.AbilityKit'; 1007import { window } from '@kit.ArkUI'; 1008import { BusinessError } from '@kit.BasicServicesKit'; 1009 1010let caller: Caller; 1011 1012export default class MainUIAbility extends UIAbility { 1013 onWindowStageCreate(windowStage: window.WindowStage) { 1014 this.context.startAbilityByCall({ 1015 bundleName: 'com.example.myservice', 1016 abilityName: 'MainUIAbility', 1017 deviceId: '' 1018 }).then((obj) => { 1019 caller = obj; 1020 try { 1021 let onReleaseCallBack: OnReleaseCallback = (str) => { 1022 console.log(`Caller OnRelease CallBack is called ${str}`); 1023 }; 1024 caller.on('release', onReleaseCallBack); 1025 caller.off('release', onReleaseCallBack); 1026 } catch (error) { 1027 console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1028 } 1029 }).catch((err: BusinessError) => { 1030 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1031 }); 1032 } 1033} 1034``` 1035 1036### Caller.off('release') 1037 1038off(type: 'release'): void 1039 1040Deregisters a callback that is invoked when the stub on the target UIAbility is disconnected. This capability is reserved. 1041 1042**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1043 1044**Parameters** 1045 1046| Name| Type| Mandatory| Description| 1047| -------- | -------- | -------- | -------- | 1048| type | string | Yes| Event type. The value is fixed at **'release'**.| 1049 1050**Error codes** 1051 1052For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1053 1054| ID| Error Message| 1055| ------- | -------------------------------- | 1056| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1057 1058**Example** 1059 1060```ts 1061import { UIAbility, Caller, OnReleaseCallback } from '@kit.AbilityKit'; 1062import { window } from '@kit.ArkUI'; 1063import { BusinessError } from '@kit.BasicServicesKit'; 1064 1065let caller: Caller; 1066 1067export default class MainUIAbility extends UIAbility { 1068 onWindowStageCreate(windowStage: window.WindowStage) { 1069 this.context.startAbilityByCall({ 1070 bundleName: 'com.example.myservice', 1071 abilityName: 'MainUIAbility', 1072 deviceId: '' 1073 }).then((obj) => { 1074 caller = obj; 1075 try { 1076 let onReleaseCallBack: OnReleaseCallback = (str) => { 1077 console.log(`Caller OnRelease CallBack is called ${str}`); 1078 }; 1079 caller.on('release', onReleaseCallBack); 1080 caller.off('release'); 1081 } catch (error) { 1082 console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1083 } 1084 }).catch((err: BusinessError) => { 1085 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1086 }); 1087 } 1088} 1089``` 1090 1091## Callee 1092 1093Implements callbacks for caller notification registration and deregistration. 1094 1095### Callee.on 1096 1097on(method: string, callback: CalleeCallback): void 1098 1099Registers a caller notification callback, which is invoked when the target UIAbility registers a function. 1100 1101**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1102 1103**Parameters** 1104 1105| Name| Type| Mandatory| Description| 1106| -------- | -------- | -------- | -------- | 1107| method | string | Yes| Notification message string negotiated between the two UIAbilities.| 1108| 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.| 1109 1110**Error codes** 1111 1112For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1113 1114| ID| Error Message| 1115| ------- | -------------------------------- | 1116| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1117| 16200004 | The method has been registered. | 1118| 16000050 | Internal error. | 1119 1120**Example** 1121 1122```ts 1123import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1124import { rpc } from '@kit.IPCKit'; 1125 1126class MyMessageAble implements rpc.Parcelable { 1127 name: string 1128 str: string 1129 num: number = 1 1130 constructor(name: string, str: string) { 1131 this.name = name; 1132 this.str = str; 1133 } 1134 marshalling(messageSequence: rpc.MessageSequence) { 1135 messageSequence.writeInt(this.num); 1136 messageSequence.writeString(this.str); 1137 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 1138 return true; 1139 } 1140 unmarshalling(messageSequence: rpc.MessageSequence) { 1141 this.num = messageSequence.readInt(); 1142 this.str = messageSequence.readString(); 1143 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 1144 return true; 1145 } 1146}; 1147let method = 'call_Function'; 1148 1149function funcCallBack(pdata: rpc.MessageSequence) { 1150 console.log(`Callee funcCallBack is called ${pdata}`); 1151 let msg = new MyMessageAble('test', ''); 1152 pdata.readParcelable(msg); 1153 return new MyMessageAble('test1', 'Callee test'); 1154} 1155export default class MainUIAbility extends UIAbility { 1156 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1157 console.log('Callee onCreate is called'); 1158 try { 1159 this.callee.on(method, funcCallBack); 1160 } catch (error) { 1161 console.error(`Callee.on catch error, error.code: ${error.code}, error.message: ${error.message}`); 1162 } 1163 } 1164} 1165``` 1166 1167### Callee.off 1168 1169off(method: string): void 1170 1171Deregisters a caller notification callback, which is invoked when the target UIAbility registers a function. 1172 1173**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1174 1175**Parameters** 1176 1177| Name| Type| Mandatory| Description| 1178| -------- | -------- | -------- | -------- | 1179| method | string | Yes| Registered notification message string.| 1180 1181**Error codes** 1182 1183For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1184 1185| ID| Error Message| 1186| ------- | -------------------------------- | 1187| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1188| 16200005 | The method has not been registered. | 1189| 16000050 | Internal error. | 1190 1191**Example** 1192 1193```ts 1194import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1195 1196let method = 'call_Function'; 1197 1198export default class MainUIAbility extends UIAbility { 1199 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1200 console.log('Callee onCreate is called'); 1201 try { 1202 this.callee.off(method); 1203 } catch (error) { 1204 console.error(`Callee.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1205 } 1206 } 1207} 1208``` 1209 1210## OnReleaseCallback 1211 1212### (msg: string) 1213 1214(msg: string): void 1215 1216Defines the callback that is invoked when the stub on the target UIAbility is disconnected. 1217 1218**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1219 1220**Parameters** 1221 1222| Name| Type| Mandatory| Description| 1223| --- | ----- | --- | -------- | 1224| msg | string | Yes| Message used for disconnection.| 1225 1226## OnRemoteStateChangeCallback<sup>10+</sup> 1227 1228### (msg: string) 1229 1230(msg: string): void 1231 1232Defines the callback that is invoked when the remote UIAbility state changes in the collaboration scenario. 1233 1234**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1235 1236**Parameters** 1237 1238| Name| Type| Mandatory| Description| 1239| --- | ----- | --- | -------- | 1240| msg | string | Yes| Message used for disconnection.| 1241 1242## CalleeCallback 1243 1244### (indata: rpc.MessageSequence) 1245 1246(indata: rpc.MessageSequence): rpc.Parcelable 1247 1248Defines the callback of the registration message notification of the UIAbility. 1249 1250**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1251 1252**Parameters** 1253 1254| Name| Type| Mandatory| Description| 1255| --- | ----- | --- | -------- | 1256| indata | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes| Data to be transferred.| 1257 1258**Return value** 1259 1260| Type | Description | 1261| ------------ | ------------------------------------- | 1262| [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Returned data object.| 1263