1# @ohos.app.ability.UIAbility (UIAbility) 2 3UIAbility is an application component that has the UI. The **UIAbility** module 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 8> **NOTE** 9> 10> 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. 11> The APIs of this module can be used only in the stage model. 12 13## Modules to Import 14 15```ts 16import UIAbility from '@ohos.app.ability.UIAbility'; 17``` 18 19## Attributes 20 21**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 22 23| Name| Type| Readable| Writable| Description| 24| -------- | -------- | -------- | -------- | -------- | 25| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the UIAbility.| 26| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the UIAbility.| 27| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the UIAbility was started last time.| 28| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| 29 30## UIAbility.onCreate 31 32onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void; 33 34Called 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). 35 36**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 37 38**Parameters** 39 40| Name| Type| Mandatory| Description| 41| -------- | -------- | -------- | -------- | 42| want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this UIAbility, including the ability name and bundle name.| 43| param | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Parameters for starting the UIAbility, and the reason for the last abnormal exit.| 44 45**Example** 46 47 ```ts 48 import UIAbility from '@ohos.app.ability.UIAbility'; 49 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 50 import Want from '@ohos.app.ability.Want'; 51 52 class MyUIAbility extends UIAbility { 53 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 54 console.log('onCreate, want: ${want.abilityName}'); 55 } 56 } 57 ``` 58 59 60## UIAbility.onWindowStageCreate 61 62onWindowStageCreate(windowStage: window.WindowStage): void 63 64Called when a **WindowStage** is created for this UIAbility. 65 66**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 67 68**Parameters** 69 70| Name| Type| Mandatory| Description| 71| -------- | -------- | -------- | -------- | 72| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| 73 74**Example** 75 76 ```ts 77 import UIAbility from '@ohos.app.ability.UIAbility'; 78 import window from '@ohos.window'; 79 80 class MyUIAbility extends UIAbility { 81 onWindowStageCreate(windowStage: window.WindowStage) { 82 console.log('onWindowStageCreate'); 83 } 84 } 85 ``` 86 87 88## UIAbility.onWindowStageDestroy 89 90onWindowStageDestroy(): void 91 92Called when the **WindowStage** is destroyed for this UIAbility. 93 94**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 95 96**Example** 97 98 ```ts 99 import UIAbility from '@ohos.app.ability.UIAbility'; 100 101 class MyUIAbility extends UIAbility { 102 onWindowStageDestroy() { 103 console.log('onWindowStageDestroy'); 104 } 105 } 106 ``` 107 108 109## UIAbility.onWindowStageRestore 110 111onWindowStageRestore(windowStage: window.WindowStage): void 112 113Called when the **WindowStage** is restored during the migration of this UIAbility, which is a multi-instance ability. 114 115**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 116 117**Parameters** 118 119| Name| Type| Mandatory| Description| 120| -------- | -------- | -------- | -------- | 121| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| 122 123**Example** 124 125 ```ts 126 import UIAbility from '@ohos.app.ability.UIAbility'; 127 import window from '@ohos.window'; 128 129 class MyUIAbility extends UIAbility { 130 onWindowStageRestore(windowStage: window.WindowStage) { 131 console.log('onWindowStageRestore'); 132 } 133 } 134 ``` 135 136 137## UIAbility.onDestroy 138 139onDestroy(): void | Promise<void>; 140 141Called when this UIAbility is destroyed to clear resources. 142 143**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 144 145**Example** 146 147 148 ```ts 149 import UIAbility from '@ohos.app.ability.UIAbility'; 150 151 class MyUIAbility extends UIAbility { 152 onDestroy() { 153 console.log('onDestroy'); 154 } 155 } 156 ``` 157 158After 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. 159 160 ```ts 161import UIAbility from '@ohos.app.ability.UIAbility'; 162 163class MyUIAbility extends UIAbility { 164 async onDestroy() { 165 console.log('onDestroy'); 166 // Call the asynchronous function. 167 } 168} 169 ``` 170 171## UIAbility.onForeground 172 173onForeground(): void; 174 175Called when this UIAbility is switched from the background to the foreground. 176 177**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 178 179**Example** 180 181 ```ts 182 import UIAbility from '@ohos.app.ability.UIAbility'; 183 184 class MyUIAbility extends UIAbility { 185 onForeground() { 186 console.log('onForeground'); 187 } 188 } 189 ``` 190 191 192## UIAbility.onBackground 193 194onBackground(): void; 195 196Called when this UIAbility is switched from the foreground to the background. 197 198**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 199 200**Example** 201 202 ```ts 203 import UIAbility from '@ohos.app.ability.UIAbility'; 204 205 class MyUIAbility extends UIAbility { 206 onBackground() { 207 console.log('onBackground'); 208 } 209 } 210 ``` 211 212 213## UIAbility.onContinue 214 215onContinue(wantParam: { [key: string]: Object }): AbilityConstant.OnContinueResult; 216 217Called to save data during the ability migration preparation process. 218 219**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 220 221**Parameters** 222 223| Name| Type| Mandatory| Description| 224| -------- | -------- | -------- | -------- | 225| wantParam | {[key: string]: Object} | Yes| **want** parameter.| 226 227**Return value** 228 229| Type| Description| 230| -------- | -------- | 231| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#abilityconstantoncontinueresult) | Continuation result.| 232 233**Example** 234 235 ```ts 236 import UIAbility from '@ohos.app.ability.UIAbility'; 237 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 238 239 class MyUIAbility extends UIAbility { 240 onContinue(wantParams: Record<string, Object>) { 241 console.log('onContinue'); 242 wantParams['myData'] = 'my1234567'; 243 return AbilityConstant.OnContinueResult.AGREE; 244 } 245 } 246 ``` 247 248 249## UIAbility.onNewWant 250 251onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam): void; 252 253Called 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). 254 255**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 256 257**Parameters** 258 259| Name| Type| Mandatory| Description| 260| -------- | -------- | -------- | -------- | 261| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.| 262| launchParam | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.| 263 264**Example** 265 266 ```ts 267 import UIAbility from '@ohos.app.ability.UIAbility'; 268 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 269 270 class MyUIAbility extends UIAbility { 271 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) { 272 console.log(`onNewWant, want: ${want.abilityName}`); 273 console.log(`onNewWant, launchParam: ${JSON.stringify(launchParam)}`); 274 } 275 } 276 ``` 277 278## UIAbility.onDump 279 280onDump(params: Array\<string>): Array\<string>; 281 282Dumps client information. 283 284**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 285 286**Parameters** 287 288| Name| Type| Mandatory| Description| 289| -------- | -------- | -------- | -------- | 290| params | Array\<string> | Yes| Parameters in the form of a command.| 291 292**Example** 293 294 ```ts 295 import UIAbility from '@ohos.app.ability.UIAbility'; 296 297 class MyUIAbility extends UIAbility { 298 onDump(params: Array<string>) { 299 console.log(`dump, params: ${JSON.stringify(params)}`); 300 return ['params']; 301 } 302 } 303 ``` 304 305 306## UIAbility.onSaveState 307 308onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: Object}): AbilityConstant.OnSaveResult; 309 310Called 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. 311 312**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 313 314**Parameters** 315 316| Name| Type| Mandatory| Description| 317| -------- | -------- | -------- | -------- | 318| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the UIAbility state.| 319| wantParam | {[key: string]: Object} | Yes| **want** parameter.| 320 321**Return value** 322 323| Type| Description| 324| -------- | -------- | 325| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#abilityconstantonsaveresult) | Whether the UIAbility state is saved.| 326 327**Example** 328 329 ```ts 330import UIAbility from '@ohos.app.ability.UIAbility'; 331import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 332 333class MyUIAbility extends UIAbility { 334 onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>) { 335 console.log('onSaveState'); 336 wantParam['myData'] = 'my1234567'; 337 return AbilityConstant.OnSaveResult.RECOVERY_AGREE; 338 } 339} 340 ``` 341 342## UIAbility.onShare<sup>10+</sup> 343 344onShare(wantParam:{ [key: string]: Object }): void; 345 346Called by this UIAbility to set data to share in the cross-device sharing scenario. 347 348**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 349 350**Parameters** 351 352| Name| Type| Mandatory| Description| 353| -------- | -------- | -------- | -------- | 354| wantParam | {[key: string]: Object} | Yes| Data to share.| 355 356**Example** 357 358 ```ts 359import UIAbility from '@ohos.app.ability.UIAbility'; 360import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 361 362class MyUIAbility extends UIAbility { 363 onShare(wantParams: Record<string, Object>) { 364 console.log('onShare'); 365 wantParams['ohos.extra.param.key.shareUrl'] = 'example.com'; 366 } 367} 368 ``` 369 370## UIAbility.onPrepareToTerminate<sup>10+</sup> 371 372onPrepareToTerminate(): boolean; 373 374Triggered when this UIAbility is about to terminate in case that the system parameter **persist.sys.prepare_terminate** is set to **true**. You can define an operation in this callback to determine whether to continue terminating the UIAbility. If a confirmation from the user is required, you can define a pre-termination operation in the callback and use it together with [terminateSelf](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextterminateself), for example, displaying a dialog box to ask the user whether to terminate the UIAbility. The UIAbility termination process is canceled when **persist.sys.prepare_terminate** is set to **true**. 375 376**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE 377 378**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 379 380**Return value** 381 382| Type| Description| 383| -- | -- | 384| boolean | Whether to terminate the UIAbility. The value **true** means that the termination process is canceled and the UIAbility is not terminated. The value **false** means to continue terminating the UIAbility.| 385 386**Example** 387 388 ```ts 389 import UIAbility from '@ohos.app.ability.UIAbility'; 390 import Want from '@ohos.app.ability.Want'; 391 import { BusinessError } from '@ohos.base'; 392 393 export default class EntryAbility extends UIAbility { 394 onPrepareToTerminate() { 395 // Define a pre-termination operation, 396 // for example, starting another UIAbility and performing asynchronous termination based on the startup result. 397 let want: Want = { 398 bundleName: "com.example.myapplication", 399 moduleName: "entry", 400 abilityName: "SecondAbility" 401 } 402 this.context.startAbilityForResult(want) 403 .then((result)=>{ 404 // Obtain the startup result and terminate the current UIAbility when resultCode in the return value is 0. 405 console.log('startAbilityForResult success, resultCode is ' + result.resultCode); 406 if (result.resultCode === 0) { 407 this.context.terminateSelf(); 408 } 409 }).catch((err: BusinessError)=>{ 410 // Exception handling. 411 console.log('startAbilityForResult failed, err:' + JSON.stringify(err)); 412 this.context.terminateSelf(); 413 }) 414 415 return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled. 416 } 417 } 418 ``` 419 420## UIAbility.onBackPressed<sup>10+</sup> 421 422onBackPressed(): boolean; 423 424Called when an operation of going back to a previous page is triggered on this UIAbility. The return value determines whether to destroy the UIAbility instance. By default, the UIAbility instance is destroyed. 425 426**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 427 428**Return value** 429 430| Type| Description| 431| -- | -- | 432| 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.| 433 434**Example** 435 436 ```ts 437 import UIAbility from '@ohos.app.ability.UIAbility'; 438 439 export default class EntryAbility extends UIAbility { 440 onBackPressed() { 441 return true; 442 } 443 } 444 ``` 445 446## Caller 447 448Implements sending of sequenceable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility). 449 450## Caller.call 451 452call(method: string, data: rpc.Parcelable): Promise<void>; 453 454Sends sequenceable data to the target ability. 455 456**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 457 458**Parameters** 459 460| Name| Type| Mandatory| Description| 461| -------- | -------- | -------- | -------- | 462| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| 463| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| 464 465**Return value** 466 467| Type| Description| 468| -------- | -------- | 469| Promise<void> | Promise used to return a response.| 470 471**Error codes** 472 473| ID| Error Message| 474| ------- | -------------------------------- | 475| 16200001 | Caller released. The caller has been released. | 476| 16200002 | Callee invalid. The callee does not exist. | 477| 16000050 | Internal error. | 478 479For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 480 481**Example** 482 483 ```ts 484 import UIAbility from '@ohos.app.ability.UIAbility'; 485 import { Caller } from '@ohos.app.ability.UIAbility'; 486 import { BusinessError } from '@ohos.base'; 487 import window from '@ohos.window'; 488 import rpc from '@ohos.rpc'; 489 490 class MyMessageAble implements rpc.Parcelable { // Custom parcelable data structure. 491 name: string 492 str: string 493 num: number = 1 494 constructor(name: string, str: string) { 495 this.name = name; 496 this.str = str; 497 } 498 marshalling(messageSequence: rpc.MessageSequence) { 499 messageSequence.writeInt(this.num); 500 messageSequence.writeString(this.str); 501 console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); 502 return true; 503 } 504 unmarshalling(messageSequence: rpc.MessageSequence) { 505 this.num = messageSequence.readInt(); 506 this.str = messageSequence.readString(); 507 console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); 508 return true; 509 } 510 }; 511 let method = 'call_Function'; // Notification message string negotiated by the two UIAbilities. 512 let caller: Caller; 513 export default class MainUIAbility extends UIAbility { 514 onWindowStageCreate(windowStage: window.WindowStage) { 515 this.context.startAbilityByCall({ 516 bundleName: 'com.example.myservice', 517 abilityName: 'MainUIAbility', 518 deviceId: '' 519 }).then((obj) => { 520 caller = obj; 521 let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable. 522 caller.call(method, msg) 523 .then(() => { 524 console.log('Caller call() called'); 525 }) 526 .catch((callErr: BusinessError) => { 527 console.log('Caller.call catch error, error.code: ${callErr.code}, error.message: ${callErr.message}'); 528 }); 529 }).catch((err: BusinessError) => { 530 console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}'); 531 }); 532 } 533 } 534 ``` 535 536 537## Caller.callWithResult 538 539callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence>; 540 541Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. 542 543**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 544 545**Parameters** 546 547| Name| Type| Mandatory| Description| 548| -------- | -------- | -------- | -------- | 549| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| 550| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| 551 552**Return value** 553 554| Type| Description| 555| -------- | -------- | 556| Promise<[rpc.MessageSequence](js-apis-rpc.md#messagesequence9)> | Promise used to return the sequenceable data from the target ability.| 557 558**Error codes** 559 560| ID| Error Message| 561| ------- | -------------------------------- | 562| 16200001 | Caller released. The caller has been released. | 563| 16200002 | Callee invalid. The callee does not exist. | 564| 16000050 | Internal error. | 565 566For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 567 568**Example** 569 570 ```ts 571 import UIAbility from '@ohos.app.ability.UIAbility'; 572 import { Caller } from '@ohos.app.ability.UIAbility'; 573 import { BusinessError } from '@ohos.base'; 574 import window from '@ohos.window'; 575 import rpc from '@ohos.rpc'; 576 577 class MyMessageAble implements rpc.Parcelable { 578 name: string 579 str: string 580 num: number = 1 581 constructor(name: string, str: string) { 582 this.name = name; 583 this.str = str; 584 } 585 marshalling(messageSequence: rpc.MessageSequence) { 586 messageSequence.writeInt(this.num); 587 messageSequence.writeString(this.str); 588 console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); 589 return true; 590 } 591 unmarshalling(messageSequence: rpc.MessageSequence) { 592 this.num = messageSequence.readInt(); 593 this.str = messageSequence.readString(); 594 console.log('MyMessageAble unmarshalling num[${this.num] str[${this.str}]'); 595 return true; 596 } 597 }; 598 let method = 'call_Function'; 599 let caller: Caller; 600 export default class MainUIAbility extends UIAbility { 601 onWindowStageCreate(windowStage: window.WindowStage) { 602 this.context.startAbilityByCall({ 603 bundleName: 'com.example.myservice', 604 abilityName: 'MainUIAbility', 605 deviceId: '' 606 }).then((obj) => { 607 caller = obj; 608 let msg = new MyMessageAble(1, 'world'); 609 caller.callWithResult(method, msg) 610 .then((data) => { 611 console.log('Caller callWithResult() called'); 612 let retmsg = new MyMessageAble(0, ''); 613 data.readParcelable(retmsg); 614 }) 615 .catch((callErr: BusinessError) => { 616 console.log('Caller.callWithResult catch error, error.code: ${callErr.code}, error.message: ${callErr.message}'); 617 }); 618 }).catch((err: BusinessError) => { 619 console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}'); 620 }); 621 } 622 } 623 ``` 624 625 626## Caller.release 627 628release(): void; 629 630Releases the caller interface of the target ability. 631 632**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 633 634**Error codes** 635 636| ID| Error Message| 637| ------- | -------------------------------- | 638| 16200001 | Caller released. The caller has been released. | 639| 16200002 | Callee invalid. The callee does not exist. | 640 641For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 642 643**Example** 644 645 ```ts 646 import UIAbility from '@ohos.app.ability.UIAbility'; 647 import { Caller } from '@ohos.app.ability.UIAbility'; 648 import { BusinessError } from '@ohos.base'; 649 import window from '@ohos.window'; 650 651 let caller: Caller; 652 export default class MainUIAbility extends UIAbility { 653 onWindowStageCreate(windowStage: window.WindowStage) { 654 this.context.startAbilityByCall({ 655 bundleName: 'com.example.myservice', 656 abilityName: 'MainUIAbility', 657 deviceId: '' 658 }).then((obj) => { 659 caller = obj; 660 try { 661 caller.release(); 662 } catch (releaseErr) { 663 console.log('Caller.release catch error, error.code: ${releaseErr.code}, error.message: ${releaseErr.message}'); 664 } 665 }).catch((err: BusinessError) => { 666 console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}'); 667 }); 668 } 669 } 670 ``` 671 672## Caller.onRelease 673 674 onRelease(callback: OnReleaseCallback): void; 675 676Registers a callback that is invoked when the stub on the target ability is disconnected. 677 678**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 679 680**Error codes** 681 682| ID| Error Message| 683| ------- | -------------------------------- | 684| 16200001 | Caller released. The caller has been released. | 685 686For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 687 688**Parameters** 689 690| Name| Type| Mandatory| Description| 691| -------- | -------- | -------- | -------- | 692| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 693 694**Example** 695 696 ```ts 697 import UIAbility from '@ohos.app.ability.UIAbility'; 698 import { Caller } from '@ohos.app.ability.UIAbility'; 699 import { BusinessError } from '@ohos.base'; 700 import window from '@ohos.window'; 701 702 let caller: Caller; 703 export default class MainUIAbility extends UIAbility { 704 onWindowStageCreate(windowStage: window.WindowStage) { 705 this.context.startAbilityByCall({ 706 bundleName: 'com.example.myservice', 707 abilityName: 'MainUIAbility', 708 deviceId: '' 709 }).then((obj) => { 710 caller = obj; 711 try { 712 caller.onRelease((str) => { 713 console.log(' Caller OnRelease CallBack is called ${str}'); 714 }); 715 } catch (error) { 716 console.log('Caller.onRelease catch error, error.code: $error.code}, error.message: ${error.message}'); 717 } 718 }).catch((err: BusinessError) => { 719 console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}'); 720 }); 721 } 722 } 723 ``` 724 725## Caller.onRemoteStateChange<sup>10+</sup> 726 727onRemoteStateChange(callback: OnRemoteStateChangeCallback): void; 728 729Registers a callback that is invoked when the remote ability state changes in the collaboration scenario. 730 731**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 732 733**Parameters** 734 735| Name| Type| Mandatory| Description| 736| -------- | -------- | -------- | -------- | 737| callback | [OnRemoteStateChangeCallback](#onremotestatechangecallback) | Yes| Callback used to return the result.| 738 739**Error codes** 740 741| ID| Error Message| 742| ------- | -------------------------------- | 743| 16200001 | Caller released. The caller has been released. | 744 745For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 746 747**Example** 748 749 ```ts 750 import UIAbility from '@ohos.app.ability.UIAbility'; 751 import { Caller } from '@ohos.app.ability.UIAbility'; 752 import { BusinessError } from '@ohos.base'; 753 import window from '@ohos.window'; 754 755 let caller: Caller; 756 let dstDeviceId: string; 757 export default class MainAbility extends UIAbility { 758 onWindowStageCreate(windowStage: window.WindowStage) { 759 this.context.startAbilityByCall({ 760 bundleName: 'com.example.myservice', 761 abilityName: 'MainUIAbility', 762 deviceId: dstDeviceId 763 }).then((obj) => { 764 caller = obj; 765 try { 766 caller.onRemoteStateChange((str) => { 767 console.log('Remote state changed ' + str); 768 }); 769 } catch (error) { 770 console.log(`Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}`); 771 } 772 }).catch((err: BusinessError) => { 773 console.log(`Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}`); 774 }) 775 } 776 } 777 ``` 778 779## Caller.on 780 781on(type: 'release', callback: OnReleaseCallback): void; 782 783Registers a callback that is invoked when the stub on the target ability is disconnected. 784 785**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 786 787**Parameters** 788 789| Name| Type| Mandatory| Description| 790| -------- | -------- | -------- | -------- | 791| type | string | Yes| Event type. The value is fixed at **release**.| 792| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 793 794**Error codes** 795 796| ID| Error Message| 797| ------- | -------------------------------- | 798| 401 | If the input parameter is not valid parameter. | 799| 16200001 | Caller released. The caller has been released. | 800 801For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 802 803**Example** 804 805 ```ts 806 import UIAbility from '@ohos.app.ability.UIAbility'; 807 import { Caller } from '@ohos.app.ability.UIAbility'; 808 import { BusinessError } from '@ohos.base'; 809 import window from '@ohos.window'; 810 811 let caller: Caller; 812 export default class MainUIAbility extends UIAbility { 813 onWindowStageCreate(windowStage: window.WindowStage) { 814 this.context.startAbilityByCall({ 815 bundleName: 'com.example.myservice', 816 abilityName: 'MainUIAbility', 817 deviceId: '' 818 }).then((obj) => { 819 caller = obj; 820 try { 821 caller.on('release', (str) => { 822 console.log(' Caller OnRelease CallBack is called ${str}'); 823 }); 824 } catch (error) { 825 console.log('Caller.on catch error, error.code: ${error.code}, error.message: ${error.message}'); 826 } 827 }).catch((err: BusinessError) => { 828 console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}'); 829 }); 830 } 831 } 832 ``` 833 834## Caller.off 835 836off(type: 'release', callback: OnReleaseCallback): void; 837 838Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved. 839 840**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 841 842**Parameters** 843 844| Name| Type| Mandatory| Description| 845| -------- | -------- | -------- | -------- | 846| type | string | Yes| Event type. The value is fixed at **release**.| 847| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 848 849**Error codes** 850 851| ID| Error Message| 852| ------- | -------------------------------- | 853| 401 | If the input parameter is not valid parameter. | 854 855**Example** 856 857 ```ts 858 import UIAbility, { OnReleaseCallback } from '@ohos.app.ability.UIAbility'; 859 import { Caller } from '@ohos.app.ability.UIAbility'; 860 import { BusinessError } from '@ohos.base'; 861 import window from '@ohos.window'; 862 863 let caller: Caller; 864 export default class MainUIAbility extends UIAbility { 865 onWindowStageCreate(windowStage: window.WindowStage) { 866 this.context.startAbilityByCall({ 867 bundleName: 'com.example.myservice', 868 abilityName: 'MainUIAbility', 869 deviceId: '' 870 }).then((obj) => { 871 caller = obj; 872 try { 873 let onReleaseCallBack: OnReleaseCallback = (str) => { 874 console.log(' Caller OnRelease CallBack is called ${str}'); 875 }; 876 caller.on('release', onReleaseCallBack); 877 caller.off('release', onReleaseCallBack); 878 } catch (error) { 879 console.log('Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}'); 880 } 881 }).catch((err: BusinessError) => { 882 console.log('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}'); 883 }); 884 } 885 } 886 ``` 887 888## Caller.off 889 890off(type: 'release'): void; 891 892Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved. 893 894**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 895 896**Parameters** 897 898| Name| Type| Mandatory| Description| 899| -------- | -------- | -------- | -------- | 900| type | string | Yes| Event type. The value is fixed at **release**.| 901 902**Example** 903 904 ```ts 905 import UIAbility, { OnReleaseCallback } from '@ohos.app.ability.UIAbility'; 906 import { Caller } from '@ohos.app.ability.UIAbility'; 907 import { BusinessError } from '@ohos.base'; 908 import window from '@ohos.window'; 909 910 let caller: Caller; 911 export default class MainUIAbility extends UIAbility { 912 onWindowStageCreate(windowStage: window.WindowStage) { 913 this.context.startAbilityByCall({ 914 bundleName: 'com.example.myservice', 915 abilityName: 'MainUIAbility', 916 deviceId: '' 917 }).then((obj) => { 918 caller = obj; 919 try { 920 let onReleaseCallBack: OnReleaseCallback = (str) => { 921 console.log(' Caller OnRelease CallBack is called ${str}'); 922 }; 923 caller.on('release', onReleaseCallBack); 924 caller.off('release'); 925 } catch (error) { 926 console.error('Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}'); 927 } 928 }).catch((err: BusinessError) => { 929 console.error('Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}'); 930 }); 931 } 932 } 933 ``` 934 935## Callee 936 937Implements callbacks for caller notification registration and deregistration. 938 939## Callee.on 940 941on(method: string, callback: CalleeCallback): void; 942 943Registers a caller notification callback, which is invoked when the target ability registers a function. 944 945**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 946 947**Parameters** 948 949| Name| Type| Mandatory| Description| 950| -------- | -------- | -------- | -------- | 951| method | string | Yes| Notification message string negotiated between the two abilities.| 952| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageSequence](js-apis-rpc.md#messagesequence9) type. The callback must return at least one empty [rpc.Parcelable](js-apis-rpc.md#parcelable9) object. Otherwise, the function execution fails.| 953 954**Error codes** 955 956| ID| Error Message| 957| ------- | -------------------------------- | 958| 16200004 | Method registered. The method has registered. | 959| 16000050 | Internal error. | 960 961For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 962 963**Example** 964 965 ```ts 966 import UIAbility, { CalleeCallback } from '@ohos.app.ability.UIAbility'; 967 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 968 import Want from '@ohos.app.ability.Want'; 969 import rpc from '@ohos.rpc'; 970 971 class MyMessageAble implements rpc.Parcelable { 972 name: string 973 str: string 974 num: number = 1 975 constructor(name: string, str: string) { 976 this.name = name; 977 this.str = str; 978 } 979 marshalling(messageSequence: rpc.MessageSequence) { 980 messageSequence.writeInt(this.num); 981 messageSequence.writeString(this.str); 982 console.log('MyMessageAble marshalling num[${this.num}] str[${this.str}]'); 983 return true; 984 } 985 unmarshalling(messageSequence: rpc.MessageSequence) { 986 this.num = messageSequence.readInt(); 987 this.str = messageSequence.readString(); 988 console.log('MyMessageAble unmarshalling num[${this.num}] str[${this.str}]'); 989 return true; 990 } 991 }; 992 let method = 'call_Function'; 993 function funcCallBack(pdata: rpc.MessageSequence) { 994 console.log('Callee funcCallBack is called ${pdata}'); 995 let msg = new MyMessageAble('test', ''); 996 pdata.readParcelable(msg); 997 return new MyMessageAble('test1', 'Callee test'); 998 } 999 export default class MainUIAbility extends UIAbility { 1000 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1001 console.log('Callee onCreate is called'); 1002 try { 1003 this.callee.on(method, funcCallBack); 1004 } catch (error) { 1005 console.log('Callee.on catch error, error.code: ${error.code}, error.message: ${error.message}'); 1006 } 1007 } 1008 } 1009 ``` 1010 1011## Callee.off 1012 1013off(method: string): void; 1014 1015Deregisters a caller notification callback, which is invoked when the target ability registers a function. 1016 1017**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1018 1019**Parameters** 1020 1021| Name| Type| Mandatory| Description| 1022| -------- | -------- | -------- | -------- | 1023| method | string | Yes| Registered notification message string.| 1024 1025**Error codes** 1026 1027| ID| Error Message| 1028| ------- | -------------------------------- | 1029| 16200005 | Method not registered. The method has not registered. | 1030| 16000050 | Internal error. | 1031 1032For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 1033 1034 1035**Example** 1036 1037 ```ts 1038 import UIAbility from '@ohos.app.ability.UIAbility'; 1039 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 1040 import Want from '@ohos.app.ability.Want'; 1041 1042 let method = 'call_Function'; 1043 export default class MainUIAbility extends UIAbility { 1044 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1045 console.log('Callee onCreate is called'); 1046 try { 1047 this.callee.off(method); 1048 } catch (error) { 1049 console.log('Callee.off catch error, error.code: ${error.code}, error.message: ${error.message}'); 1050 } 1051 } 1052 } 1053 ``` 1054 1055## OnReleaseCallback 1056 1057(msg: string): void; 1058 1059**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1060 1061| Name| Readable| Writable| Type| Description| 1062| -------- | -------- | -------- | -------- | -------- | 1063| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.| 1064 1065## OnRemoteStateChangeCallback<sup>10+</sup> 1066 1067(msg: string): void; 1068 1069**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1070 1071| Name| Readable| Writable| Type| Description| 1072| -------- | -------- | -------- | -------- | -------- | 1073| (msg: string) | Yes| No| function | Prototype of the ability state change listener function registered by the caller in the collaboration scenario.| 1074 1075## CalleeCallback 1076 1077(indata: rpc.MessageSequence): rpc.Parcelable; 1078 1079**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1080 1081| Name| Readable| Writable| Type| Description| 1082| -------- | -------- | -------- | -------- | -------- | 1083| (indata: [rpc.MessageSequence](js-apis-rpc.md#messagesequence9)) | Yes| No| [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Prototype of the listener function registered by the callee.| 1084