1# @ohos.app.ability.UIAbility (Ability with UI) 2 3<!--Kit: Ability Kit--> 4<!--Subsystem: Ability--> 5<!--Owner: @littlejerry1; @Luobniz21--> 6<!--Designer: @ccllee1--> 7<!--Tester: @lixueqing513--> 8<!--Adviser: @huipeizi--> 9 10UIAbility is an application component that has the UI. It inherits from [Ability](js-apis-app-ability-ability.md) and provides [lifecycle](#uiability-lifecycle-states) callbacks such as component creation, destruction, and foreground/background switching. It also provides the [background communication capability](#background-communication-capability). 11 12> **NOTE** 13> 14> 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. 15> 16> The APIs of this module can be used only in the stage model. 17 18For details about the inheritance relationship of each ability, see [Inheritance Relationship](./js-apis-app-ability-ability.md#ability-inheritance-relationship). 19 20## UIAbility Lifecycle States 21 22**Figure 1** UIAbility lifecycle states 23 24 25 26- **Create**: A UIAbility instance has been created. The system triggers the [onCreate](#oncreate) callback in this state, where you can perform initialization operations. 27- **Foreground**: The UIAbility has been brought to the foreground. The system triggers the [onForeground](#onforeground) callback in this state, where you can request resources required by the application. 28- **Background**: The UIAbility has been moved to the background. The system triggers the [onBackground](#onbackground) callback in this state, where you can release some application resources. 29- **Destroy**: The UIAbility instance is about to be destroyed. The system triggers the [onDestroy](#ondestroy) callback in this state, where you can save data. 30 31## Background Communication Capability 32 33**Call** invocations can be used for background communication with the target UIAbility. The following figure shows the Call invocation. 34 35 36**Figure 2** Diagram of Call invocation 37 38 39 40- The Caller UIAbility uses [startAbilityByCall()](js-apis-inner-application-uiAbilityContext.md#startabilitybycall) to obtain a [Caller](#caller) object and then uses the [call](#call) API of the Caller object to send data to the Callee UIAbility. 41 42- The Callee UIAbility holds a [Callee](#callee) object and uses the [on](#on) API of the Callee object to register a callback function for receiving data sent by the Caller object. 43 44## Modules to Import 45 46```ts 47import { UIAbility } from '@kit.AbilityKit'; 48``` 49 50## UIAbility 51 52Application component that has the UI. It provides lifecycle callbacks such as component creation, destruction, and foreground/background switching, and supports component collaboration. 53 54### Properties 55 56**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 57 58| Name| Type| Read-only| Optional| Description| 59| -------- | -------- | -------- | -------- | -------- | 60| 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.| 61| launchWant | [Want](js-apis-app-ability-want.md) | No| No| Want in the request used to cold start the UIAbility. The value is the Want received in [onCreate](#oncreate).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 62| lastRequestWant | [Want](js-apis-app-ability-want.md) | No| No| Want in the most recent request to launch the UIAbility.<br>- On the first launch of a UIAbility, it is the Want parameter received in [onCreate](#oncreate).<br>- On subsequent launches, it is the most recent Want received in [onNewWant](#onnewwant).<br>**Atomic service API**: This API can be used in atomic services since API version 11.| 63| callee | [Callee](#callee) | No| No| Background communication object created by the system for the UIAbility, known as the Callee UIAbility (Callee), which is capable of receiving data sent from the Caller object.| 64 65 66### onCreate 67 68onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void 69 70Called when a UIAbility instance is created. You can execute initialization logic (such as defining variables and loading resources) in this callback. This callback is invoked during a [cold start](../../application-models/uiability-intra-device-interaction.md#cold-starting-uiability) of the UIAbility. 71 72This API returns the result synchronously and does not support asynchronous callback. 73 74**Atomic service API**: This API can be used in atomic services since API version 11. 75 76**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 77 78**Parameters** 79 80| Name| Type| Mandatory| Description| 81| -------- | -------- | -------- | -------- | 82| want | [Want](js-apis-app-ability-want.md) | Yes| Data passed by the caller when launching the UIAbility.| 83| launchParam | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#launchparam) | Yes| Parameters for application launch, including the reason for application launch and the reason for the last application exit.| 84 85**Example** 86 87 88```ts 89import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 90import { hilog } from '@kit.PerformanceAnalysisKit'; 91 92export default class MyUIAbility extends UIAbility { 93 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 94 // Execute an asynchronous task. 95 hilog.info(0x0000, 'testTag', `onCreate, want: ${want.abilityName}`); 96 hilog.info(0x0000, 'testTag', `the launchReason is + ${launchParam.launchReason} + , the lastExitReason is + ${launchParam.lastExitReason}`); 97 } 98} 99``` 100 101 102### onWindowStageCreate 103 104onWindowStageCreate(windowStage: window.WindowStage): void 105 106Called when a WindowStage instance is created. You can load a page through the WindowStage instance in this callback. 107 108**Atomic service API**: This API can be used in atomic services since API version 11. 109 110**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 111 112**Parameters** 113 114| Name| Type| Mandatory| Description| 115| -------- | -------- | -------- | -------- | 116| windowStage | [window.WindowStage](../apis-arkui/arkts-apis-window-WindowStage.md) | Yes| WindowStage instance.| 117 118**Example** 119 120```ts 121import { UIAbility } from '@kit.AbilityKit'; 122import { hilog } from '@kit.PerformanceAnalysisKit'; 123import { window } from '@kit.ArkUI'; 124 125export default class MyUIAbility extends UIAbility { 126 // The main window has been created. Set the main page for the UIAbility. 127 onWindowStageCreate(windowStage: window.WindowStage): void { 128 windowStage.loadContent('pages/Index', (err, data) => { 129 if (err.code) { 130 hilog.error(0x0000, 'testTag', `Failed to load the content. Cause: ${JSON.stringify(err)}`); 131 return; 132 } 133 hilog.info(0x0000, 'testTag', `Succeeded in loading the content. Data: ${JSON.stringify(data)}`); 134 }); 135 } 136} 137``` 138 139 140### onWindowStageWillDestroy<sup>12+</sup> 141 142onWindowStageWillDestroy(windowStage: window.WindowStage): void 143 144Called when the WindowStage instance is about to be destroyed. You can cancel the listening of WindowStage events in this lifecycle. 145 146**Atomic service API**: This API can be used in atomic services since API version 12. 147 148**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 149 150**Parameters** 151 152| Name| Type| Mandatory| Description| 153| -------- | -------- | -------- | -------- | 154| windowStage | [window.WindowStage](../apis-arkui/arkts-apis-window-WindowStage.md) | Yes| WindowStage instance.| 155 156**Example** 157 158```ts 159import { UIAbility } from '@kit.AbilityKit'; 160import { hilog } from '@kit.PerformanceAnalysisKit'; 161import { window } from '@kit.ArkUI'; 162 163export default class MyUIAbility extends UIAbility { 164 onWindowStageWillDestroy(windowStage: window.WindowStage) { 165 hilog.info(0x0000, 'testTag', `onWindowStageWillDestroy`); 166 } 167} 168``` 169 170 171### onWindowStageDestroy 172 173onWindowStageDestroy(): void 174 175Called when the WindowStage instance has been destroyed. It informs applications that the WindowStage instance is no longer available for use. 176 177The callback is invoked only when the UIAbility exits gracefully. It is not invoked in cases of abnormal exits (for example, due to low memory conditions). 178 179**Atomic service API**: This API can be used in atomic services since API version 11. 180 181**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 182 183**Example** 184 185```ts 186import { UIAbility } from '@kit.AbilityKit'; 187import { hilog } from '@kit.PerformanceAnalysisKit'; 188 189export default class MyUIAbility extends UIAbility { 190 onWindowStageDestroy() { 191 // The main window is destroyed. It is time to release UI resources. 192 hilog.info(0x0000, 'testTag', `onWindowStageDestroy`); 193 } 194} 195``` 196 197 198### onWindowStageRestore 199 200onWindowStageRestore(windowStage: window.WindowStage): void 201 202Called when the page stack is restored for the target UIAbility during cross-device migration. 203 204> **NOTE** 205> 206> When an application is launched as a result of a migration, the **onWindowStageRestore()** lifecycle callback function, rather than **onWindowStageCreate()**, is triggered following [onCreate()](#oncreate) or [onNewWant()](#onnewwant). This sequence occurs for both cold and hot starts. 207 208 209**Atomic service API**: This API can be used in atomic services since API version 11. 210 211**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 212 213**Parameters** 214 215| Name| Type| Mandatory| Description| 216| -------- | -------- | -------- | -------- | 217| windowStage | [window.WindowStage](../apis-arkui/arkts-apis-window-WindowStage.md) | Yes| WindowStage instance.| 218 219**Example** 220 221```ts 222import { UIAbility } from '@kit.AbilityKit'; 223import { hilog } from '@kit.PerformanceAnalysisKit'; 224import { window } from '@kit.ArkUI'; 225 226export default class MyUIAbility extends UIAbility { 227 onWindowStageRestore(windowStage: window.WindowStage) { 228 hilog.info(0x0000, 'testTag', `onWindowStageRestore`); 229 } 230} 231``` 232 233 234### onDestroy 235 236onDestroy(): void | Promise<void> 237 238Called when the UIAbility is destroyed (for example, when the UIAbility is terminated using the [terminateSelf](js-apis-inner-application-uiAbilityContext.md#terminateself) API). You can clear resources and save data during this lifecycle. This API returns the result synchronously or uses a promise to return the result. 239 240After 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. Using a Promise for asynchronous callback is recommended to prevent such issues. 241 242The callback is invoked only when the UIAbility exits gracefully. It is not invoked in cases of abnormal exits (for example, due to low memory conditions). 243 244**Atomic service API**: This API can be used in atomic services since API version 11. 245 246**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 247 248**Return value** 249 250| Type| Description| 251| -------- | -------- | 252| void \| Promise<void> | No return value or a Promise object that returns no result.| 253 254**Example** 255 256- A synchronous callback example is as follows: 257 258 ```ts 259 import { UIAbility } from '@kit.AbilityKit'; 260 import { hilog } from '@kit.PerformanceAnalysisKit'; 261 262 export default class MyUIAbility extends UIAbility { 263 onDestroy() { 264 hilog.info(0x0000, 'testTag', `onDestroy`); 265 // Call the synchronous function. 266 } 267 } 268 ``` 269 270- A promise asynchronous callback example is as follows: 271 272 ```ts 273 import { UIAbility } from '@kit.AbilityKit'; 274 import { hilog } from '@kit.PerformanceAnalysisKit'; 275 276 export default class MyUIAbility extends UIAbility { 277 async onDestroy() { 278 hilog.info(0x0000, 'testTag', `onDestroy`); 279 // Call the asynchronous function. 280 } 281 } 282 ``` 283 284 285### onWillForeground<sup>20+</sup> 286 287onWillForeground(): void 288 289Called just before the application transitions to the foreground. It is called before [onForeground](#onforeground). It can be used to capture the moment when the application starts to transition to the foreground. When paired with [onDidForeground](#ondidforeground20), it can also measure the duration from the application's initial foreground entry to its full transition into the foreground state. 290 291This API returns the result synchronously and does not support asynchronous callback. 292 293**Atomic service API**: This API can be used in atomic services since API version 20. 294 295**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 296 297**Example** 298 299```ts 300import { UIAbility } from '@kit.AbilityKit'; 301import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; 302import { BusinessError } from '@kit.BasicServicesKit'; 303 304export default class EntryAbility extends UIAbility { 305 // ... 306 307 onWillForeground(): void { 308 // Start to log the event that the application starts moving to the foreground. 309 let eventParams: Record<string, number> = { 'xxxx': 100 }; 310 let eventInfo: hiAppEvent.AppEventInfo = { 311 // Define the event domain. 312 domain: "lifecycle", 313 // Define the event name. 314 name: "onwillforeground", 315 // Define the event type. 316 eventType: hiAppEvent.EventType.BEHAVIOR, 317 // Define the event parameters. 318 params: eventParams, 319 }; 320 hiAppEvent.write(eventInfo).then(() => { 321 hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`); 322 }).catch((err: BusinessError) => { 323 hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`); 324 }); 325 } 326 // ... 327 328 onDidForeground(): void { 329 // Start to log the event that the application fully transitions to the foreground. 330 let eventParams: Record<string, number> = { 'xxxx': 100 }; 331 let eventInfo: hiAppEvent.AppEventInfo = { 332 // Define the event domain. 333 domain: "lifecycle", 334 // Define the event name. 335 name: "ondidforeground", 336 // Define the event type. 337 eventType: hiAppEvent.EventType.BEHAVIOR, 338 // Define the event parameters. 339 params: eventParams, 340 }; 341 hiAppEvent.write(eventInfo).then(() => { 342 hilog.info(0x0000, 'testTag', `HiAppEvent success to write event`); 343 }).catch((err: BusinessError) => { 344 hilog.error(0x0000, 'testTag', `HiAppEvent err.code: ${err.code}, err.message: ${err.message}`); 345 }); 346 } 347} 348``` 349 350 351### onForeground 352 353onForeground(): void 354 355Called when the application is initially launched into the foreground or transitions from the background to the foreground. You can request necessary system resources, for example, requesting location services when the application transitions to the foreground, within this callback. 356 357This API returns the result synchronously and does not support asynchronous callback. 358 359**Atomic service API**: This API can be used in atomic services since API version 11. 360 361**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 362 363**Example** 364 365 366```ts 367import { UIAbility } from '@kit.AbilityKit'; 368import { hilog } from '@kit.PerformanceAnalysisKit'; 369 370export default class MyUIAbility extends UIAbility { 371 onForeground() { 372 // Execute an asynchronous task. 373 hilog.info(0x0000, 'testTag', `onForeground`); 374 } 375} 376``` 377 378 379### onDidForeground<sup>20+</sup> 380 381onDidForeground(): void 382 383Called after the application has transitioned to the foreground. It is called after [onForeground](#onforeground). It can be used to capture the moment when the application fully transitions to the foreground. When paired with [onWillForeground](#onwillforeground20), it can also measure the duration from the application's initial foreground entry to its full transition into the foreground state. 384 385This API returns the result synchronously and does not support asynchronous callback. 386 387**Atomic service API**: This API can be used in atomic services since API version 20. 388 389**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 390 391**Example** 392 393For details, see [onWillForeground](#onwillforeground20). 394 395 396### onWillBackground<sup>20+</sup> 397 398onWillBackground(): void 399 400Called just when the application transitions to the background. It is called before [onBackground](#onbackground). It can be used to log various types of data, such as faults, statistics, security information, and user behavior that occur during application running. 401 402This API returns the result synchronously and does not support asynchronous callback. 403 404**Atomic service API**: This API can be used in atomic services since API version 20. 405 406**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 407 408**Example** 409 410```ts 411import { UIAbility } from '@kit.AbilityKit'; 412import { hiAppEvent, hilog } from '@kit.PerformanceAnalysisKit'; 413import { BusinessError } from '@kit.BasicServicesKit'; 414 415export default class MyUIAbility extends UIAbility { 416 onWillBackground(): void { 417 let eventParams: Record<string, number | string> = { 418 "int_data": 100, 419 "str_data": "strValue", 420 }; 421 // Record the application fault information. 422 hiAppEvent.write({ 423 domain: "test_domain", 424 name: "test_event", 425 eventType: hiAppEvent.EventType.FAULT, 426 params: eventParams, 427 }, (err: BusinessError) => { 428 if (err) { 429 hilog.error(0x0000, 'testTag', `hiAppEvent code: ${err.code}, message: ${err.message}`); 430 return; 431 } 432 hilog.info(0x0000, 'testTag', `hiAppEvent success to write event`); 433 }); 434 } 435} 436``` 437 438 439### onBackground 440 441onBackground(): void 442 443Called when the application transitions from the foreground to the background. You can release resources when the UI is no longer visible, for example, stopping location services, within this callback. 444 445This API returns the result synchronously and does not support asynchronous callback. 446 447**Atomic service API**: This API can be used in atomic services since API version 11. 448 449**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 450 451**Example** 452 453```ts 454import { UIAbility } from '@kit.AbilityKit'; 455import { hilog } from '@kit.PerformanceAnalysisKit'; 456 457export default class MyUIAbility extends UIAbility { 458 onBackground() { 459 // The UIAbility transitions to the background. 460 hilog.info(0x0000, 'testTag', `onBackground`); 461 } 462} 463``` 464 465 466### onDidBackground<sup>20+</sup> 467 468onDidBackground(): void 469 470Called after the application has transitioned to the background. It is called after [onBackground](#onbackground). It can be used to release resources after the application has entered the background, for example, stopping audio playback. 471 472This API returns the result synchronously and does not support asynchronous callback. 473 474**Atomic service API**: This API can be used in atomic services since API version 20. 475 476**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 477 478**Example** 479 480```ts 481import { UIAbility } from '@kit.AbilityKit'; 482import { BusinessError } from '@kit.BasicServicesKit'; 483import { hilog } from '@kit.PerformanceAnalysisKit'; 484import { audio } from '@kit.AudioKit'; 485 486export default class MyUIAbility extends UIAbility { 487 static audioRenderer: audio.AudioRenderer; 488 // ... 489 onForeground(): void { 490 let audioStreamInfo: audio.AudioStreamInfo = { 491 samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, // Sampling rate. 492 channels: audio.AudioChannel.CHANNEL_2, // Channel. 493 sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, // Sampling format. 494 encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW // Encoding format. 495 }; 496 497 let audioRendererInfo: audio.AudioRendererInfo = { 498 usage: audio.StreamUsage.STREAM_USAGE_MUSIC, // Audio stream usage type: music. Set this parameter based on the service scenario. 499 rendererFlags: 0 // AudioRenderer flag. 500 }; 501 502 let audioRendererOptions: audio.AudioRendererOptions = { 503 streamInfo: audioStreamInfo, 504 rendererInfo: audioRendererInfo 505 }; 506 507 // Request an AudioRenderer in the foreground to play Pulse Code Modulation (PCM) audio data. 508 audio.createAudioRenderer(audioRendererOptions).then((data) => { 509 MyUIAbility.audioRenderer = data; 510 hilog.info(0x0000, 'testTag', `AudioRenderer Created : Success : Stream Type: SUCCESS.`); 511 }).catch((err: BusinessError) => { 512 hilog.error(0x0000, 'testTag', `AudioRenderer Created : F : ${JSON.stringify(err)}.`); 513 }); 514 } 515 516 onDidBackground() { 517 // Release the AudioRenderer after transitioning to the background. 518 MyUIAbility.audioRenderer.release((err: BusinessError) => { 519 if (err) { 520 hilog.error(0x0000, 'testTag', `AudioRenderer release failed, error: ${JSON.stringify(err)}.`); 521 } else { 522 hilog.info(0x0000, 'testTag', `AudioRenderer released.`); 523 } 524 }); 525 } 526} 527``` 528 529### onContinue 530 531onContinue(wantParam: Record<string, Object>): AbilityConstant.OnContinueResult | Promise<AbilityConstant.OnContinueResult> 532 533Called to save data during the UIAbility migration preparation process. 534 535> **NOTE** 536> 537> Starting from API version 12, **UIAbility.onContinue** supports the return value in the form of Promise\<[AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#oncontinueresult)\>. 538 539**Atomic service API**: This API can be used in atomic services since API version 11. 540 541**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 542 543**Parameters** 544 545| Name| Type| Mandatory| Description| 546| -------- | -------- | -------- | -------- | 547| wantParam | Record<string, Object> | Yes| Data to be migrated.| 548 549**Return value** 550 551| Type| Description| 552| -------- | -------- | 553| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#oncontinueresult) \| Promise<[AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#oncontinueresult)> | Whether the migration is accepted. The options are as follows:<br>- **AGREE**: The migration is allowed.<br>- **REJECT**: The migration is rejected, for example, when an application is abnormal in **onContinue()**.<br>- **MISMATCH**: The application versions of the source and target devices do not match. The application on the source device can obtain the version of the target application from **onContinue**. If the ability continuation cannot be performed due to version mismatch, this result is returned.<br> This callback comes in pairs with **onWindowStageRestore**. In ability continuation scenarios, the source UIAbility triggers **onContinue** to save custom data, and the target UIAbility triggers **onWindowStageRestore** to restore the custom data.| 554 555**Example** 556 557- The following is an example of saving data using a synchronous API during application migration: 558 559 ```ts 560 import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 561 562 export default class MyUIAbility extends UIAbility { 563 onContinue(wantParams: Record<string, Object>) { 564 console.info('onContinue'); 565 wantParams['myData'] = 'my1234567'; 566 return AbilityConstant.OnContinueResult.AGREE; 567 } 568 } 569 ``` 570 571- The following is an example of saving data using an asynchronous API during application migration: 572 573 ```ts 574 import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 575 576 export default class MyUIAbility extends UIAbility { 577 async setWant(wantParams: Record<string, Object>) { 578 console.info('setWant start'); 579 for (let time = 0; time < 1000; ++time) { 580 wantParams[time] = time; 581 } 582 console.info('setWant end'); 583 } 584 585 async onContinue(wantParams: Record<string, Object>) { 586 console.info('onContinue'); 587 return this.setWant(wantParams).then(() => { 588 return AbilityConstant.OnContinueResult.AGREE; 589 }); 590 } 591 } 592 ``` 593 594 595### onNewWant 596 597onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void 598 599Called when a UIAbility instance, which has been in the foreground, is brought up again. If there are specific scenarios where you do not want this lifecycle callback to be triggered, you can use [setOnNewWantSkipScenarios](./js-apis-inner-application-uiAbilityContext.md#setonnewwantskipscenarios20) to set those [scenarios](./js-apis-app-ability-contextConstant.md#scenarios20). 600 601 602**Atomic service API**: This API can be used in atomic services since API version 11. 603 604**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 605 606**Parameters** 607 608| Name| Type| Mandatory| Description| 609| -------- | -------- | -------- | -------- | 610| want | [Want](js-apis-app-ability-want.md) | Yes| Data passed by the caller when re-launching the UIAbility.| 611| launchParam | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#launchparam) | Yes| Reason for re-launching the UIAbility.| 612 613**Example** 614 615```ts 616import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 617 618export default class MyUIAbility extends UIAbility { 619 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) { 620 console.info(`onNewWant, want: ${want.abilityName}`); 621 console.info(`onNewWant, launchParam: ${JSON.stringify(launchParam)}`); 622 } 623} 624``` 625 626### onDump 627 628onDump(params: Array\<string>): Array\<string> 629 630Called when UIAbility data is dumped by running the dump command during application debugging. You can return non-sensitive information to be dumped by the UIAbility in this callback. 631 632**Atomic service API**: This API can be used in atomic services since API version 11. 633 634**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 635 636**Parameters** 637 638| Name| Type| Mandatory| Description| 639| -------- | -------- | -------- | -------- | 640| params | Array\<string> | Yes| Parameters for the dump command.| 641 642**Return value** 643 644| Type| Description| 645| -------- | -------- | 646| Array\<string> | Information returned by the dump operation.| 647 648**Example** 649 650```ts 651import { UIAbility } from '@kit.AbilityKit'; 652 653export default class MyUIAbility extends UIAbility { 654 onDump(params: Array<string>) { 655 console.info(`dump, params: ${JSON.stringify(params)}`); 656 return ['params']; 657 } 658} 659``` 660 661 662### onSaveState 663 664onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>): AbilityConstant.OnSaveResult 665 666Called 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. 667 668When the application has enabled the fault recovery feature (with the **saveOccasion** parameter in [enableAppRecovery](js-apis-app-ability-appRecovery.md#apprecoveryenableapprecovery) set to **SAVE_WHEN_ERROR**), this callback is invoked to save the UIAbility data in the case of an application fault. 669 670> **NOTE** 671> 672> Starting from API version 20, this callback is not executed when [UIAbility.onSaveStateAsync](#onsavestateasync20) is implemented. 673 674**Atomic service API**: This API can be used in atomic services since API version 11. 675 676**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 677 678**Parameters** 679 680| Name| Type| Mandatory| Description| 681| -------- | -------- | -------- | -------- | 682| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#statetype) | Yes| Reason for triggering the application to save its state. Currently, only **APP_RECOVERY** (fault recovery scenario) is supported.| 683| wantParam | Record<string, Object> | Yes| Custom application state data, which is stored in **Want.parameters** in **onCreate** when the application restarts.| 684 685**Return value** 686 687| Type| Description| 688| -------- | -------- | 689| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#onsaveresult) | An object indicating the data-saving policy (for example, all denied, all allowed, or only allowed in fault recovery scenarios).| 690 691**Example** 692 693```ts 694import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 695 696export default class MyUIAbility extends UIAbility { 697 onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>) { 698 console.info('onSaveState'); 699 wantParam['myData'] = 'my1234567'; 700 return AbilityConstant.OnSaveResult.RECOVERY_AGREE; 701 } 702} 703``` 704 705### onSaveStateAsync<sup>20+</sup> 706 707onSaveStateAsync(stateType: AbilityConstant.StateType, wantParam: Record<string, Object>): Promise\<AbilityConstant.OnSaveResult> 708 709When the application has enabled the fault recovery feature (with the **saveOccasion** parameter in [enableAppRecovery](js-apis-app-ability-appRecovery.md#apprecoveryenableapprecovery) set to **SAVE_WHEN_ERROR**), this callback is invoked to save the UIAbility data in the case of an application fault. This API uses a promise to return the result. 710 711**Atomic service API**: This API can be used in atomic services since API version 20. 712 713**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 714 715**Parameters** 716 717| Name| Type| Mandatory| Description| 718| -------- | -------- | -------- | -------- | 719| stateType | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#statetype) | Yes| Reason for triggering the application to save its state. Currently, only **APP_RECOVERY** (fault recovery scenario) is supported.| 720| wantParam | Record<string, Object> | Yes| Custom application state data, which is stored in **Want.parameters** when the application restarts.| 721 722**Return value** 723 724| Type| Description| 725| -------- | -------- | 726| Promise\<[AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#onsaveresult)> | Promise used to return the result. An object indicating the data-saving policy (for example, all denied, all allowed, or only allowed in fault recovery scenarios).| 727 728**Example** 729 730```ts 731import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 732 733class MyUIAbility extends UIAbility { 734 async onSaveStateAsync(reason: AbilityConstant.StateType, wantParam: Record<string, Object>) : Promise<AbilityConstant.OnSaveResult> { 735 await new Promise<string>((res, rej) => { 736 setTimeout(res, 1000); // Execute the operation after 1 second. 737 }); 738 return AbilityConstant.OnSaveResult.RECOVERY_AGREE; 739 } 740} 741``` 742 743### onShare<sup>10+</sup> 744 745onShare(wantParam: Record<string, Object>): void 746 747Called when an atomic service is shared across devices. You can set the title, abstract, and URL of the atomic service to be shared in this callback. 748 749**Atomic service API**: This API can be used in atomic services since API version 11. 750 751**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 752 753**Parameters** 754 755| Name| Type| Mandatory| Description| 756| -------- | -------- | -------- | -------- | 757| wantParam | Record<string, Object> | Yes| Data to share.| 758 759**Example** 760 761```ts 762import { UIAbility } from '@kit.AbilityKit'; 763 764export default class MyUIAbility extends UIAbility { 765 onShare(wantParams: Record<string, Object>) { 766 console.info('onShare'); 767 wantParams['ohos.extra.param.key.shareUrl'] = 'example.com'; 768 } 769} 770``` 771 772### onPrepareToTerminate<sup>10+</sup> 773 774onPrepareToTerminate(): boolean 775 776Triggered by the system just before the UIAbility is about to close (for example, when the user clicks the close button in the top-right corner of the application window or exits from the dock or system tray), allowing for additional operations to be performed before the UIAbility is officially shut down. You can return **true** to block the current closure attempt and then manually call [terminateSelf](js-apis-inner-application-uiAbilityContext.md#terminateself) at an appropriate time to close it. For example, you might ask the user to confirm whether they want to close the UIAbility and then proceed with the closure manually. 777 778 779> **NOTE** 780> 781> - Starting from API version 15, this callback is not executed when[UIAbility.onPrepareToTerminateAsync](#onpreparetoterminateasync15) is implemented. When [AbilityStage.onPrepareTerminationAsync](js-apis-app-ability-abilityStage.md#onprepareterminationasync15) or [AbilityStage.onPrepareTermination](js-apis-app-ability-abilityStage.md#onpreparetermination15) is implemented, this callback is not executed if the user right-clicks the dock bar or system tray to close the UIAbility. 782> - Additionally, if the application or a third-party framework registers a listener for [window.WindowStage.on('windowStageClose')](../apis-arkui/arkts-apis-window-WindowStage.md#onwindowstageclose14), this callback is not executed. 783 784**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE 785 786**Atomic service API**: This API can be used in atomic services since API version 11. 787 788**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 789 790**Device behavior differences**: This API executes the callback normally only on 2-in-1 devices and tablets. It does not execute the callback on other devices. 791 792**Return value** 793 794| Type| Description| 795| -- | -- | 796| boolean | Whether to terminate the UIAbility. **true** if the termination process is canceled; **false** to continue terminating the UIAbility.| 797 798**Example** 799 800```ts 801import { UIAbility, Want } from '@kit.AbilityKit'; 802import { BusinessError } from '@kit.BasicServicesKit'; 803 804export default class EntryAbility extends UIAbility { 805 onPrepareToTerminate() { 806 // Define a pre-termination operation, 807 // for example, starting another UIAbility and performing asynchronous termination based on the startup result. 808 let want: Want = { 809 bundleName: "com.example.myapplication", 810 moduleName: "entry", 811 abilityName: "SecondAbility" 812 } 813 this.context.startAbilityForResult(want) 814 .then((result)=>{ 815 // Obtain the startup result and terminate the current UIAbility when resultCode in the return value is 0. 816 console.info('startAbilityForResult success, resultCode is ' + result.resultCode); 817 if (result.resultCode === 0) { 818 this.context.terminateSelf(); 819 } 820 }).catch((err: BusinessError)=>{ 821 // Exception handling. 822 console.error('startAbilityForResult failed, err:' + JSON.stringify(err)); 823 this.context.terminateSelf(); 824 }) 825 826 return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled. 827 } 828} 829``` 830 831### onPrepareToTerminateAsync<sup>15+</sup> 832 833onPrepareToTerminateAsync(): Promise\<boolean> 834 835Triggered by the system just before the UIAbility is close (for example, when the user clicks the close button in the top-right corner of the application window or exits from the dock or system tray), allowing for additional operations to be performed before the UIAbility is officially shut down. 836 837You can return **true** to block the current closure attempt and then manually call [terminateSelf](js-apis-inner-application-uiAbilityContext.md#terminateself) at an appropriate time to close it. For example, you might ask the user to confirm whether they want to close the UIAbility and then proceed with the closure manually. 838 839 840> **NOTE** 841> 842> - When [AbilityStage.onPrepareTerminationAsync](js-apis-app-ability-abilityStage.md#onprepareterminationasync15) or [AbilityStage.onPrepareTermination](js-apis-app-ability-abilityStage.md#onpreparetermination15) is implemented, this callback is not executed if the user right-clicks the dock bar or system tray to close the UIAbility. 843> - Additionally, if the application or a third-party framework registers a listener for [window.WindowStage.on('windowStageClose')](../apis-arkui/arkts-apis-window-WindowStage.md#onwindowstageclose14), this callback is not executed. 844> 845> - 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. 846 847**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE 848 849**Atomic service API**: This API can be used in atomic services since API version 15. 850 851**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 852 853**Device behavior differences** 854- Starting from API version 15, this API executes the callback normally only on 2-in-1 devices. It does not execute the callback on other devices. 855- Starting from API version 19, this API executes the callback normally only on 2-in-1 devices and tablets. It does not execute the callback on other devices. 856 857**Return value** 858 859| Type| Description| 860| -- | -- | 861| Promise\<boolean> | Promise used to return the result. **true** if the termination process is canceled; **false** to continue terminating the UIAbility.| 862 863**Example** 864 865```ts 866import { UIAbility } from '@kit.AbilityKit'; 867 868export default class EntryAbility extends UIAbility { 869 async onPrepareToTerminateAsync(): Promise<boolean> { 870 await new Promise<boolean>((res, rej) => { 871 setTimeout (res, 2000); // Execute the operation 2 seconds later. 872 }); 873 return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled. 874 } 875} 876``` 877 878### onBackPressed<sup>10+</sup> 879 880onBackPressed(): boolean 881 882Called 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. 883 884- When the target SDK version is earlier than 12, the default return value is **false**, indicating that the UIAbility will be destroyed. 885- 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. 886 887**Atomic service API**: This API can be used in atomic services since API version 11. 888 889**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 890 891**Return value** 892 893| Type| Description| 894| -- | -- | 895| boolean | **true** if the UIAbility instance will be moved to the background and will not be destroyed; **false** if the UIAbility instance will be destroyed.| 896 897**Example** 898 899```ts 900import { UIAbility } from '@kit.AbilityKit'; 901 902export default class EntryAbility extends UIAbility { 903 onBackPressed() { 904 return true; 905 } 906} 907``` 908 909### onCollaborate<sup>18+</sup> 910 911onCollaborate(wantParam: Record<string, Object>): AbilityConstant.CollaborateResult 912 913Callback invoked to return the collaboration result in multi-device collaboration scenarios. 914 915 **NOTE** 916- This callback does not support ability launch in specified mode. 917- 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. 918- During a cold start, this callback must be invoked before [onForeground](#onforeground) or after [onBackground](#onbackground). During a hot start, this callback must be invoked before [onNewWant](#onnewwant). 919 920 921**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 922 923**Parameters** 924 925| Name | Type | Mandatory| Description | 926| --------- | --------------------------------- | ---- | ------------------------------------------------------------ | 927| 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.| 928 929**Return value** 930 931| Type | Description | 932| -------- | ---- | 933| [AbilityConstant.CollaborateResult](js-apis-app-ability-abilityConstant.md#collaborateresult18) | Whether the coordinator accepts the collaboration result.| 934 935**Example** 936 937```ts 938import { UIAbility, AbilityConstant } from '@kit.AbilityKit'; 939 940export default class MyAbility extends UIAbility { 941 onCollaborate(wantParam: Record<string, Object>) { 942 return AbilityConstant.CollaborateResult.ACCEPT; 943 } 944} 945``` 946 947## Caller 948 949A Caller UIAbility (which must be a system application) can use [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#startabilitybycall) to start a Callee UIAbility (which can be a third-party application). The Callee UIAbility will provide a Caller object to the Caller UIAbility. Once the Caller UIAbility receives this Caller object, it can use it to communicate with the Callee UIAbility and transmit data. 950 951### call 952 953call(method: string, data: rpc.Parcelable): Promise<void> 954 955Used by a Caller UIAbility to send serialized data, as agreed upon by both parties, to the Callee UIAbility. This API uses a promise to return the result. 956 957**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 958 959**Parameters** 960 961| Name| Type| Mandatory| Description| 962| -------- | -------- | -------- | -------- | 963| method | string | Yes| Method name agreed upon by the Caller UIAbility and Callee UIAbility, used by the Callee UIAbility to identify the type of message.| 964| data | [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Yes| Message content sent from the Caller UIAbility to the Callee UIAbility, which is in serialized form.| 965 966**Return value** 967 968| Type| Description| 969| -------- | -------- | 970| Promise<void> | Promise that returns no value.| 971 972**Error codes** 973 974For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 975 976| ID| Error Message| 977| ------- | -------------------------------- | 978| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 979| 16200001 | The caller has been released. | 980| 16200002 | The callee does not exist. | 981| 16000050 | Internal error. | 982 983**Example** 984 985```ts 986import { UIAbility, Caller } from '@kit.AbilityKit'; 987import { window } from '@kit.ArkUI'; 988import { rpc } from '@kit.IPCKit'; 989import { BusinessError } from '@kit.BasicServicesKit'; 990 991class MyMessageAble implements rpc.Parcelable { // Custom parcelable data structure. 992 name: string; 993 str: string; 994 num: number = 1; 995 constructor(name: string, str: string) { 996 this.name = name; 997 this.str = str; 998 } 999 marshalling(messageSequence: rpc.MessageSequence) { 1000 messageSequence.writeInt(this.num); 1001 messageSequence.writeString(this.str); 1002 console.info(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 1003 return true; 1004 } 1005 unmarshalling(messageSequence: rpc.MessageSequence) { 1006 this.num = messageSequence.readInt(); 1007 this.str = messageSequence.readString(); 1008 console.info(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 1009 return true; 1010 } 1011} 1012let method = 'call_Function'; // Notification message string negotiated by the two UIAbility components. 1013 1014export default class MainUIAbility extends UIAbility { 1015 onWindowStageCreate(windowStage: window.WindowStage) { 1016 this.context.startAbilityByCall({ 1017 bundleName: 'com.example.myservice', 1018 abilityName: 'MainUIAbility', 1019 deviceId: '' 1020 }).then((obj) => { 1021 let caller: Caller = obj; 1022 let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable. 1023 caller.call(method, msg) 1024 .then(() => { 1025 console.info('Caller call() called'); 1026 }) 1027 .catch((callErr: BusinessError) => { 1028 console.error(`Caller.call catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`); 1029 }); 1030 }).catch((err: BusinessError) => { 1031 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1032 }); 1033 } 1034} 1035``` 1036 1037 1038### callWithResult 1039 1040callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> 1041 1042Used by a Caller UIAbility to send serialized data to a Callee UIAbility and return the result after the Callee UIAbility processes the message. This API uses a promise to return the result. 1043 1044**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1045 1046**Parameters** 1047 1048| Name| Type| Mandatory| Description| 1049| -------- | -------- | -------- | -------- | 1050| method | string | Yes| Method name agreed upon by the Caller UIAbility and Callee UIAbility, used by the Callee UIAbility to identify the type of message.| 1051| data | [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Yes| Message content sent from the Caller UIAbility to the Callee UIAbility, which is in serialized form.| 1052 1053**Return value** 1054 1055| Type| Description| 1056| -------- | -------- | 1057| Promise<[rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9)> | Promise used to return the response data from the Callee UIAbility.| 1058 1059**Error codes** 1060 1061For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1062 1063| ID| Error Message| 1064| ------- | -------------------------------- | 1065| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 1066| 16200001 | The caller has been released. | 1067| 16200002 | The callee does not exist. | 1068| 16000050 | Internal error. | 1069 1070**Example** 1071 1072```ts 1073import { UIAbility, Caller } from '@kit.AbilityKit'; 1074import { window } from '@kit.ArkUI'; 1075import { rpc } from '@kit.IPCKit'; 1076import { BusinessError } from '@kit.BasicServicesKit'; 1077 1078class MyMessageAble implements rpc.Parcelable { 1079 name: string 1080 str: string 1081 num: number = 1 1082 1083 constructor(name: string, str: string) { 1084 this.name = name; 1085 this.str = str; 1086 } 1087 1088 marshalling(messageSequence: rpc.MessageSequence) { 1089 messageSequence.writeInt(this.num); 1090 messageSequence.writeString(this.str); 1091 console.info(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 1092 return true; 1093 } 1094 1095 unmarshalling(messageSequence: rpc.MessageSequence) { 1096 this.num = messageSequence.readInt(); 1097 this.str = messageSequence.readString(); 1098 console.info(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 1099 return true; 1100 } 1101} 1102let method = 'call_Function'; 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 let msg = new MyMessageAble('msg', 'world'); 1114 caller.callWithResult(method, msg) 1115 .then((data) => { 1116 console.info('Caller callWithResult() called'); 1117 let retMsg = new MyMessageAble('msg', 'world'); 1118 data.readParcelable(retMsg); 1119 }) 1120 .catch((callErr: BusinessError) => { 1121 console.error(`Caller.callWithResult catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`); 1122 }); 1123 }).catch((err: BusinessError) => { 1124 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1125 }); 1126 } 1127} 1128``` 1129 1130 1131### release 1132 1133release(): void 1134 1135Used by a Caller UIAbility to proactively release the connection with the Callee UIAbility. After this API is called, the Caller UIAbility can no longer use **call** or **callWithResult** to send messages to the Callee UIAbility. 1136 1137**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1138 1139**Error codes** 1140 1141For details about the error codes, see [Ability Error Codes](errorcode-ability.md). 1142 1143| ID| Error Message| 1144| ------- | -------------------------------- | 1145| 16200001 | The caller has been released. | 1146| 16200002 | The callee does not exist. | 1147 1148**Example** 1149 1150```ts 1151import { UIAbility, Caller } from '@kit.AbilityKit'; 1152import { window } from '@kit.ArkUI'; 1153import { BusinessError } from '@kit.BasicServicesKit'; 1154 1155let caller: Caller; 1156 1157export default class MainUIAbility extends UIAbility { 1158 onWindowStageCreate(windowStage: window.WindowStage) { 1159 this.context.startAbilityByCall({ 1160 bundleName: 'com.example.myservice', 1161 abilityName: 'MainUIAbility', 1162 deviceId: '' 1163 }).then((obj) => { 1164 caller = obj; 1165 try { 1166 caller.release(); 1167 } catch (releaseErr) { 1168 console.error(`Caller.release catch error, error.code: ${releaseErr.code}, error.message: ${releaseErr.message}`); 1169 } 1170 }).catch((err: BusinessError) => { 1171 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1172 }); 1173 } 1174} 1175``` 1176 1177### onRelease 1178 1179onRelease(callback: OnReleaseCallback): void 1180 1181Called by the Caller UIAbility to register for notifications when the Callee UIAbility disconnects. The callback is used to monitor events where the Callee UIAbility disconnects either intentionally or due to an error. 1182 1183**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1184 1185**Parameters** 1186 1187| Name| Type| Mandatory| Description| 1188| -------- | -------- | -------- | -------- | 1189| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 1190 1191**Error codes** 1192 1193For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1194 1195| ID| Error Message| 1196| ------- | -------------------------------- | 1197| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 1198| 16200001 | The caller has been released. | 1199 1200**Example** 1201 1202```ts 1203import { UIAbility, Caller } from '@kit.AbilityKit'; 1204import { window } from '@kit.ArkUI'; 1205import { BusinessError } from '@kit.BasicServicesKit'; 1206 1207export default class MainUIAbility extends UIAbility { 1208 onWindowStageCreate(windowStage: window.WindowStage) { 1209 this.context.startAbilityByCall({ 1210 bundleName: 'com.example.myservice', 1211 abilityName: 'MainUIAbility', 1212 deviceId: '' 1213 }).then((obj) => { 1214 let caller: Caller = obj; 1215 try { 1216 caller.onRelease((str) => { 1217 console.info(`Caller OnRelease CallBack is called ${str}`); 1218 }); 1219 } catch (error) { 1220 console.error(`Caller.onRelease catch error, error.code: ${error.code}, error.message: ${error.message}`); 1221 } 1222 }).catch((err: BusinessError) => { 1223 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1224 }); 1225 } 1226} 1227``` 1228 1229### onRemoteStateChange<sup>10+</sup> 1230 1231onRemoteStateChange(callback: OnRemoteStateChangeCallback): void 1232 1233Called when the remote UIAbility state changes in the collaboration scenario. This API uses an asynchronous callback to return the result. 1234 1235**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1236 1237**Parameters** 1238 1239| Name| Type| Mandatory| Description| 1240| -------- | -------- | -------- | -------- | 1241| callback | [OnRemoteStateChangeCallback](#onremotestatechangecallback10) | Yes| Callback used to return the result.| 1242 1243**Error codes** 1244 1245For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1246 1247| ID| Error Message| 1248| ------- | -------------------------------- | 1249| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. | 1250| 16200001 | The caller has been released. | 1251 1252**Example** 1253 1254```ts 1255import { UIAbility, Caller } from '@kit.AbilityKit'; 1256import { window } from '@kit.ArkUI'; 1257import { BusinessError } from '@kit.BasicServicesKit'; 1258 1259export default class MainAbility extends UIAbility { 1260 onWindowStageCreate(windowStage: window.WindowStage) { 1261 let dstDeviceId: string = 'xxxxx'; 1262 this.context.startAbilityByCall({ 1263 bundleName: 'com.example.myservice', 1264 abilityName: 'MainUIAbility', 1265 deviceId: dstDeviceId 1266 }).then((obj) => { 1267 let caller: Caller = obj; 1268 try { 1269 caller.onRemoteStateChange((str) => { 1270 console.info('Remote state changed ' + str); 1271 }); 1272 } catch (error) { 1273 console.error(`Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}`); 1274 } 1275 }).catch((err: BusinessError) => { 1276 console.error(`Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}`); 1277 }); 1278 } 1279} 1280``` 1281 1282### on('release') 1283 1284on(type: 'release', callback: OnReleaseCallback): void 1285 1286Called by the Caller UIAbility to register for notifications when the Callee UIAbility disconnects. The callback is used to monitor events where the Callee UIAbility disconnects either intentionally or due to an error. 1287 1288**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1289 1290**Parameters** 1291 1292| Name| Type| Mandatory| Description| 1293| -------- | -------- | -------- | -------- | 1294| type | string | Yes| Event type. The value is fixed at **'release'**.| 1295| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 1296 1297**Error codes** 1298 1299For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1300 1301| ID| Error Message| 1302| ------- | -------------------------------- | 1303| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1304| 16200001 | The caller has been released. | 1305 1306**Example** 1307 1308```ts 1309import { UIAbility, Caller } from '@kit.AbilityKit'; 1310import { window } from '@kit.ArkUI'; 1311import { BusinessError } from '@kit.BasicServicesKit'; 1312 1313export default class MainUIAbility extends UIAbility { 1314 onWindowStageCreate(windowStage: window.WindowStage) { 1315 let dstDeviceId: string = 'xxxx'; 1316 this.context.startAbilityByCall({ 1317 bundleName: 'com.example.myservice', 1318 abilityName: 'MainUIAbility', 1319 deviceId: dstDeviceId 1320 }).then((obj) => { 1321 let caller: Caller = obj; 1322 try { 1323 caller.on('release', (str) => { 1324 console.info(`Caller OnRelease CallBack is called ${str}`); 1325 }); 1326 } catch (error) { 1327 console.error(`Caller.on catch error, error.code: ${error.code}, error.message: ${error.message}`); 1328 } 1329 }).catch((err: BusinessError) => { 1330 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1331 }); 1332 } 1333} 1334``` 1335 1336### off('release') 1337 1338off(type: 'release', callback: OnReleaseCallback): void 1339 1340Unregister the notification for disconnection from the Callee UIAbility. This is the reverse operation of [Caller.on('release')](#onrelease-1). It is currently not supported. 1341 1342**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1343 1344**Parameters** 1345 1346| Name| Type| Mandatory| Description| 1347| -------- | -------- | -------- | -------- | 1348| type | string | Yes| Event type. The value is fixed at **'release'**.| 1349| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 1350 1351**Error codes** 1352 1353For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1354 1355| ID| Error Message| 1356| ------- | -------------------------------- | 1357| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1358 1359**Example** 1360 1361```ts 1362import { UIAbility, Caller, OnReleaseCallback } from '@kit.AbilityKit'; 1363import { window } from '@kit.ArkUI'; 1364import { BusinessError } from '@kit.BasicServicesKit'; 1365 1366export default class MainUIAbility extends UIAbility { 1367 onWindowStageCreate(windowStage: window.WindowStage) { 1368 this.context.startAbilityByCall({ 1369 bundleName: 'com.example.myservice', 1370 abilityName: 'MainUIAbility', 1371 deviceId: '' 1372 }).then((obj) => { 1373 let caller: Caller = obj; 1374 try { 1375 let onReleaseCallBack: OnReleaseCallback = (str) => { 1376 console.info(`Caller OnRelease CallBack is called ${str}`); 1377 }; 1378 caller.on('release', onReleaseCallBack); 1379 caller.off('release', onReleaseCallBack); 1380 } catch (error) { 1381 console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1382 } 1383 }).catch((err: BusinessError) => { 1384 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1385 }); 1386 } 1387} 1388``` 1389 1390### off('release') 1391 1392off(type: 'release'): void 1393 1394Unregister the notification for disconnection from the Callee UIAbility. This is the reverse operation of [Caller.on('release')](#onrelease-1). It is currently not supported. 1395 1396**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1397 1398**Parameters** 1399 1400| Name| Type| Mandatory| Description| 1401| -------- | -------- | -------- | -------- | 1402| type | string | Yes| Event type. The value is fixed at **'release'**.| 1403 1404**Error codes** 1405 1406For details about the error codes, see [Universal Error Codes](../errorcode-universal.md). 1407 1408| ID| Error Message| 1409| ------- | -------------------------------- | 1410| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1411 1412**Example** 1413 1414```ts 1415import { UIAbility, Caller, OnReleaseCallback } from '@kit.AbilityKit'; 1416import { window } from '@kit.ArkUI'; 1417import { BusinessError } from '@kit.BasicServicesKit'; 1418 1419let caller: Caller; 1420 1421export default class MainUIAbility extends UIAbility { 1422 onWindowStageCreate(windowStage: window.WindowStage) { 1423 this.context.startAbilityByCall({ 1424 bundleName: 'com.example.myservice', 1425 abilityName: 'MainUIAbility', 1426 deviceId: '' 1427 }).then((obj) => { 1428 caller = obj; 1429 try { 1430 let onReleaseCallBack: OnReleaseCallback = (str) => { 1431 console.info(`Caller OnRelease CallBack is called ${str}`); 1432 }; 1433 caller.on('release', onReleaseCallBack); 1434 caller.off('release'); 1435 } catch (error) { 1436 console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1437 } 1438 }).catch((err: BusinessError) => { 1439 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 1440 }); 1441 } 1442} 1443``` 1444 1445## Callee 1446 1447Implements callbacks for caller notification registration and deregistration. 1448 1449### on 1450 1451on(method: string, callback: CalleeCallback): void 1452 1453Registers a caller notification callback, which is invoked when the target UIAbility registers a function. 1454 1455**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1456 1457**Parameters** 1458 1459| Name| Type| Mandatory| Description| 1460| -------- | -------- | -------- | -------- | 1461| method | string | Yes| Notification message string negotiated between the two UIAbility components.| 1462| 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.| 1463 1464**Error codes** 1465 1466For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1467 1468| ID| Error Message| 1469| ------- | -------------------------------- | 1470| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1471| 16200004 | The method has been registered. | 1472| 16000050 | Internal error. | 1473 1474**Example** 1475 1476```ts 1477import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1478import { rpc } from '@kit.IPCKit'; 1479 1480class MyMessageAble implements rpc.Parcelable { 1481 name: string 1482 str: string 1483 num: number = 1 1484 constructor(name: string, str: string) { 1485 this.name = name; 1486 this.str = str; 1487 } 1488 marshalling(messageSequence: rpc.MessageSequence) { 1489 messageSequence.writeInt(this.num); 1490 messageSequence.writeString(this.str); 1491 console.info(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 1492 return true; 1493 } 1494 unmarshalling(messageSequence: rpc.MessageSequence) { 1495 this.num = messageSequence.readInt(); 1496 this.str = messageSequence.readString(); 1497 console.info(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 1498 return true; 1499 } 1500}; 1501let method = 'call_Function'; 1502 1503function funcCallBack(pdata: rpc.MessageSequence) { 1504 let msg = new MyMessageAble('test', ''); 1505 pdata.readParcelable(msg); 1506 return new MyMessageAble('test1', 'Callee test'); 1507} 1508export default class MainUIAbility extends UIAbility { 1509 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1510 console.info('Callee onCreate is called'); 1511 try { 1512 this.callee.on(method, funcCallBack); 1513 } catch (error) { 1514 console.error(`Callee.on catch error, error.code: ${error.code}, error.message: ${error.message}`); 1515 } 1516 } 1517} 1518``` 1519 1520### off 1521 1522off(method: string): void 1523 1524Unregisters a caller notification callback, which is invoked when the target UIAbility registers a function. 1525 1526**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1527 1528**Parameters** 1529 1530| Name| Type| Mandatory| Description| 1531| -------- | -------- | -------- | -------- | 1532| method | string | Yes| Registered notification message string.| 1533 1534**Error codes** 1535 1536For details about the error codes, see [Universal Error Codes](../errorcode-universal.md) and [Ability Error Codes](errorcode-ability.md). 1537 1538| ID| Error Message| 1539| ------- | -------------------------------- | 1540| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. | 1541| 16200005 | The method has not been registered. | 1542| 16000050 | Internal error. | 1543 1544**Example** 1545 1546```ts 1547import { UIAbility, AbilityConstant, Want } from '@kit.AbilityKit'; 1548 1549let method = 'call_Function'; 1550 1551export default class MainUIAbility extends UIAbility { 1552 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1553 console.info('Callee onCreate is called'); 1554 try { 1555 this.callee.off(method); 1556 } catch (error) { 1557 console.error(`Callee.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1558 } 1559 } 1560} 1561``` 1562 1563## OnReleaseCallback 1564 1565### (msg: string) 1566 1567(msg: string): void 1568 1569Defines the callback that is invoked when the stub on the target UIAbility is disconnected. 1570 1571**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1572 1573**Parameters** 1574 1575| Name| Type| Mandatory| Description| 1576| --- | ----- | --- | -------- | 1577| msg | string | Yes| Message used for disconnection.| 1578 1579## OnRemoteStateChangeCallback<sup>10+</sup> 1580 1581### (msg: string) 1582 1583(msg: string): void 1584 1585Defines the callback that is invoked when the remote UIAbility state changes in the collaboration scenario. 1586 1587**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1588 1589**Parameters** 1590 1591| Name| Type| Mandatory| Description| 1592| --- | ----- | --- | -------- | 1593| msg | string | Yes| Message used for disconnection.| 1594 1595## CalleeCallback 1596 1597### (indata: rpc.MessageSequence) 1598 1599(indata: rpc.MessageSequence): rpc.Parcelable 1600 1601Defines the callback of the registration message notification of the UIAbility. 1602 1603**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1604 1605**Parameters** 1606 1607| Name| Type| Mandatory| Description| 1608| --- | ----- | --- | -------- | 1609| indata | [rpc.MessageSequence](../apis-ipc-kit/js-apis-rpc.md#messagesequence9) | Yes| Data to be transferred.| 1610 1611**Return value** 1612 1613| Type | Description | 1614| ------------ | ------------------------------------- | 1615| [rpc.Parcelable](../apis-ipc-kit/js-apis-rpc.md#parcelable9) | Returned data object.| 1616