1# @ohos.app.ability.UIAbility (UIAbility) 2 3UIAbility is an application component that has the UI. The **UIAbility** module, inherited from [Ability](js-apis-app-ability-ability.md), provides lifecycle callbacks such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration: 4 5- [Caller](#caller): an object returned by [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall). The CallerAbility (caller) uses this object to communicate with the CalleeAbility (callee). 6- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller). 7 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| launchParam | [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: Record<string, Object>): AbilityConstant.OnContinueResult 216 217Called to save data during the UIAbility migration preparation process. 218 219**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 220 221**Parameters** 222 223| Name| Type| Mandatory| Description| 224| -------- | -------- | -------- | -------- | 225| wantParam | Record<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 import Want from '@ohos.app.ability.Want'; 270 271 class MyUIAbility extends UIAbility { 272 onNewWant(want: Want, launchParam: AbilityConstant.LaunchParam) { 273 console.log(`onNewWant, want: ${want.abilityName}`); 274 console.log(`onNewWant, launchParam: ${JSON.stringify(launchParam)}`); 275 } 276 } 277 ``` 278 279## UIAbility.onDump 280 281onDump(params: Array\<string>): Array\<string> 282 283Called to dump the client information. This API can be used to dump non-sensitive information. 284 285**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 286 287**Parameters** 288 289| Name| Type| Mandatory| Description| 290| -------- | -------- | -------- | -------- | 291| params | Array\<string> | Yes| Parameters in the form of a command.| 292 293**Example** 294 295 ```ts 296 import UIAbility from '@ohos.app.ability.UIAbility'; 297 298 class MyUIAbility extends UIAbility { 299 onDump(params: Array<string>) { 300 console.log(`dump, params: ${JSON.stringify(params)}`); 301 return ['params']; 302 } 303 } 304 ``` 305 306 307## UIAbility.onSaveState 308 309onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>): AbilityConstant.OnSaveResult 310 311Called 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. 312 313**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 314 315**Parameters** 316 317| Name| Type| Mandatory| Description| 318| -------- | -------- | -------- | -------- | 319| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the UIAbility state.| 320| wantParam | Record<string, Object> | Yes| **want** parameter.| 321 322**Return value** 323 324| Type| Description| 325| -------- | -------- | 326| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#abilityconstantonsaveresult) | Whether the UIAbility state is saved.| 327 328**Example** 329 330 ```ts 331import UIAbility from '@ohos.app.ability.UIAbility'; 332import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 333 334class MyUIAbility extends UIAbility { 335 onSaveState(reason: AbilityConstant.StateType, wantParam: Record<string, Object>) { 336 console.log('onSaveState'); 337 wantParam['myData'] = 'my1234567'; 338 return AbilityConstant.OnSaveResult.RECOVERY_AGREE; 339 } 340} 341 ``` 342 343## UIAbility.onShare<sup>10+</sup> 344 345onShare(wantParam: Record<string, Object>): void 346 347Called by this UIAbility to set data to share in the cross-device sharing scenario. 348 349**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 350 351**Parameters** 352 353| Name| Type| Mandatory| Description| 354| -------- | -------- | -------- | -------- | 355| wantParam | Record<string, Object> | Yes| Data to share.| 356 357**Example** 358 359 ```ts 360import UIAbility from '@ohos.app.ability.UIAbility'; 361import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 362 363class MyUIAbility extends UIAbility { 364 onShare(wantParams: Record<string, Object>) { 365 console.log('onShare'); 366 wantParams['ohos.extra.param.key.shareUrl'] = 'example.com'; 367 } 368} 369 ``` 370 371## UIAbility.onPrepareToTerminate<sup>10+</sup> 372 373onPrepareToTerminate(): boolean 374 375Called 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**. 376 377**Required permissions**: ohos.permission.PREPARE_APP_TERMINATE 378 379**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 380 381**Return value** 382 383| Type| Description| 384| -- | -- | 385| 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.| 386 387**Example** 388 389 ```ts 390 import UIAbility from '@ohos.app.ability.UIAbility'; 391 import Want from '@ohos.app.ability.Want'; 392 import { BusinessError } from '@ohos.base'; 393 394 export default class EntryAbility extends UIAbility { 395 onPrepareToTerminate() { 396 // Define a pre-termination operation, 397 // for example, starting another UIAbility and performing asynchronous termination based on the startup result. 398 let want: Want = { 399 bundleName: "com.example.myapplication", 400 moduleName: "entry", 401 abilityName: "SecondAbility" 402 } 403 this.context.startAbilityForResult(want) 404 .then((result)=>{ 405 // Obtain the startup result and terminate the current UIAbility when resultCode in the return value is 0. 406 console.log('startAbilityForResult success, resultCode is ' + result.resultCode); 407 if (result.resultCode === 0) { 408 this.context.terminateSelf(); 409 } 410 }).catch((err: BusinessError)=>{ 411 // Exception handling. 412 console.error('startAbilityForResult failed, err:' + JSON.stringify(err)); 413 this.context.terminateSelf(); 414 }) 415 416 return true; // The pre-termination operation is defined. The value true means that the UIAbility termination process is canceled. 417 } 418 } 419 ``` 420 421## UIAbility.onBackPressed<sup>10+</sup> 422 423onBackPressed(): boolean 424 425Called 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. 426 427**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 428 429**Return value** 430 431| Type| Description| 432| -- | -- | 433| 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.| 434 435**Example** 436 437 ```ts 438 import UIAbility from '@ohos.app.ability.UIAbility'; 439 440 export default class EntryAbility extends UIAbility { 441 onBackPressed() { 442 return true; 443 } 444 } 445 ``` 446 447## Caller 448 449Implements sending of sequenceable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility). 450 451## Caller.call 452 453call(method: string, data: rpc.Parcelable): Promise<void>; 454 455Sends sequenceable data to the target ability. 456 457**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 458 459**Parameters** 460 461| Name| Type| Mandatory| Description| 462| -------- | -------- | -------- | -------- | 463| 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.| 464| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| 465 466**Return value** 467 468| Type| Description| 469| -------- | -------- | 470| Promise<void> | Promise used to return a response.| 471 472**Error codes** 473 474| ID| Error Message| 475| ------- | -------------------------------- | 476| 16200001 | Caller released. The caller has been released. | 477| 16200002 | Callee invalid. The callee does not exist. | 478| 16000050 | Internal error. | 479 480For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 481 482**Example** 483 484 ```ts 485 import UIAbility from '@ohos.app.ability.UIAbility'; 486 import { Caller } from '@ohos.app.ability.UIAbility'; 487 import { BusinessError } from '@ohos.base'; 488 import window from '@ohos.window'; 489 import rpc from '@ohos.rpc'; 490 491 class MyMessageAble implements rpc.Parcelable { // Custom parcelable data structure. 492 name: string 493 str: string 494 num: number = 1 495 constructor(name: string, str: string) { 496 this.name = name; 497 this.str = str; 498 } 499 marshalling(messageSequence: rpc.MessageSequence) { 500 messageSequence.writeInt(this.num); 501 messageSequence.writeString(this.str); 502 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 503 return true; 504 } 505 unmarshalling(messageSequence: rpc.MessageSequence) { 506 this.num = messageSequence.readInt(); 507 this.str = messageSequence.readString(); 508 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 509 return true; 510 } 511 }; 512 let method = 'call_Function'; // Notification message string negotiated by the two UIAbilities. 513 let caller: Caller; 514 export default class MainUIAbility extends UIAbility { 515 onWindowStageCreate(windowStage: window.WindowStage) { 516 this.context.startAbilityByCall({ 517 bundleName: 'com.example.myservice', 518 abilityName: 'MainUIAbility', 519 deviceId: '' 520 }).then((obj) => { 521 caller = obj; 522 let msg = new MyMessageAble('msg', 'world'); // See the definition of Parcelable. 523 caller.call(method, msg) 524 .then(() => { 525 console.log('Caller call() called'); 526 }) 527 .catch((callErr: BusinessError) => { 528 console.error(`Caller.call catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`); 529 }); 530 }).catch((err: BusinessError) => { 531 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 532 }); 533 } 534 } 535 ``` 536 537 538## Caller.callWithResult 539 540callWithResult(method: string, data: rpc.Parcelable): Promise<rpc.MessageSequence> 541 542Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. 543 544**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 545 546**Parameters** 547 548| Name| Type| Mandatory| Description| 549| -------- | -------- | -------- | -------- | 550| 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.| 551| data | [rpc.Parcelable](js-apis-rpc.md#parcelable9) | Yes| Parcelable data. You need to customize the data.| 552 553**Return value** 554 555| Type| Description| 556| -------- | -------- | 557| Promise<[rpc.MessageSequence](js-apis-rpc.md#messagesequence9)> | Promise used to return the sequenceable data from the target ability.| 558 559**Error codes** 560 561| ID| Error Message| 562| ------- | -------------------------------- | 563| 16200001 | Caller released. The caller has been released. | 564| 16200002 | Callee invalid. The callee does not exist. | 565| 16000050 | Internal error. | 566 567For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 568 569**Example** 570 571 ```ts 572 import UIAbility from '@ohos.app.ability.UIAbility'; 573 import { Caller } from '@ohos.app.ability.UIAbility'; 574 import { BusinessError } from '@ohos.base'; 575 import window from '@ohos.window'; 576 import rpc from '@ohos.rpc'; 577 578 class MyMessageAble implements rpc.Parcelable { 579 name: string 580 str: string 581 num: number = 1 582 constructor(name: string, str: string) { 583 this.name = name; 584 this.str = str; 585 } 586 marshalling(messageSequence: rpc.MessageSequence) { 587 messageSequence.writeInt(this.num); 588 messageSequence.writeString(this.str); 589 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 590 return true; 591 } 592 unmarshalling(messageSequence: rpc.MessageSequence) { 593 this.num = messageSequence.readInt(); 594 this.str = messageSequence.readString(); 595 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 596 return true; 597 } 598 }; 599 let method = 'call_Function'; 600 let caller: Caller; 601 export default class MainUIAbility extends UIAbility { 602 onWindowStageCreate(windowStage: window.WindowStage) { 603 this.context.startAbilityByCall({ 604 bundleName: 'com.example.myservice', 605 abilityName: 'MainUIAbility', 606 deviceId: '' 607 }).then((obj) => { 608 caller = obj; 609 let msg = new MyMessageAble('msg', 'world'); 610 caller.callWithResult(method, msg) 611 .then((data) => { 612 console.log('Caller callWithResult() called'); 613 let retmsg = new MyMessageAble('msg', 'world'); 614 data.readParcelable(retmsg); 615 }) 616 .catch((callErr: BusinessError) => { 617 console.error(`Caller.callWithResult catch error, error.code: ${callErr.code}, error.message: ${callErr.message}`); 618 }); 619 }).catch((err: BusinessError) => { 620 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 621 }); 622 } 623 } 624 ``` 625 626 627## Caller.release 628 629release(): void 630 631Releases the caller interface of the target ability. 632 633**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 634 635**Error codes** 636 637| ID| Error Message| 638| ------- | -------------------------------- | 639| 16200001 | Caller released. The caller has been released. | 640| 16200002 | Callee invalid. The callee does not exist. | 641 642For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 643 644**Example** 645 646 ```ts 647 import UIAbility from '@ohos.app.ability.UIAbility'; 648 import { Caller } from '@ohos.app.ability.UIAbility'; 649 import { BusinessError } from '@ohos.base'; 650 import window from '@ohos.window'; 651 652 let caller: Caller; 653 export default class MainUIAbility extends UIAbility { 654 onWindowStageCreate(windowStage: window.WindowStage) { 655 this.context.startAbilityByCall({ 656 bundleName: 'com.example.myservice', 657 abilityName: 'MainUIAbility', 658 deviceId: '' 659 }).then((obj) => { 660 caller = obj; 661 try { 662 caller.release(); 663 } catch (releaseErr) { 664 console.error(`Caller.release catch error, error.code: ${releaseErr.code}, error.message: ${releaseErr.message}`); 665 } 666 }).catch((err: BusinessError) => { 667 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 668 }); 669 } 670 } 671 ``` 672 673## Caller.onRelease 674 675 onRelease(callback: OnReleaseCallback): void 676 677Called when the stub on the target ability is disconnected. 678 679**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 680 681**Error codes** 682 683| ID| Error Message| 684| ------- | -------------------------------- | 685| 16200001 | Caller released. The caller has been released. | 686 687For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 688 689**Parameters** 690 691| Name| Type| Mandatory| Description| 692| -------- | -------- | -------- | -------- | 693| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 694 695**Example** 696 697 ```ts 698 import UIAbility from '@ohos.app.ability.UIAbility'; 699 import { Caller } from '@ohos.app.ability.UIAbility'; 700 import { BusinessError } from '@ohos.base'; 701 import window from '@ohos.window'; 702 703 let caller: Caller; 704 export default class MainUIAbility extends UIAbility { 705 onWindowStageCreate(windowStage: window.WindowStage) { 706 this.context.startAbilityByCall({ 707 bundleName: 'com.example.myservice', 708 abilityName: 'MainUIAbility', 709 deviceId: '' 710 }).then((obj) => { 711 caller = obj; 712 try { 713 caller.onRelease((str) => { 714 console.log(`Caller OnRelease CallBack is called ${str}`); 715 }); 716 } catch (error) { 717 console.error(`Caller.onRelease catch error, error.code: $error.code}, error.message: ${error.message}`); 718 } 719 }).catch((err: BusinessError) => { 720 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 721 }); 722 } 723 } 724 ``` 725 726## Caller.onRemoteStateChange<sup>10+</sup> 727 728onRemoteStateChange(callback: OnRemoteStateChangeCallback): void 729 730Called when the remote ability state changes in the collaboration scenario. 731 732**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 733 734**Parameters** 735 736| Name| Type| Mandatory| Description| 737| -------- | -------- | -------- | -------- | 738| callback | [OnRemoteStateChangeCallback](#onremotestatechangecallback10) | Yes| Callback used to return the result.| 739 740**Error codes** 741 742| ID| Error Message| 743| ------- | -------------------------------- | 744| 16200001 | Caller released. The caller has been released. | 745 746For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 747 748**Example** 749 750 ```ts 751 import UIAbility from '@ohos.app.ability.UIAbility'; 752 import { Caller } from '@ohos.app.ability.UIAbility'; 753 import { BusinessError } from '@ohos.base'; 754 import window from '@ohos.window'; 755 756 let caller: Caller; 757 let dstDeviceId: string; 758 export default class MainAbility extends UIAbility { 759 onWindowStageCreate(windowStage: window.WindowStage) { 760 this.context.startAbilityByCall({ 761 bundleName: 'com.example.myservice', 762 abilityName: 'MainUIAbility', 763 deviceId: dstDeviceId 764 }).then((obj) => { 765 caller = obj; 766 try { 767 caller.onRemoteStateChange((str) => { 768 console.log('Remote state changed ' + str); 769 }); 770 } catch (error) { 771 console.error(`Caller.onRemoteStateChange catch error, error.code: ${JSON.stringify(error.code)}, error.message: ${JSON.stringify(error.message)}`); 772 } 773 }).catch((err: BusinessError) => { 774 console.error(`Caller GetCaller error, error.code: ${JSON.stringify(err.code)}, error.message: ${JSON.stringify(err.message)}`); 775 }) 776 } 777 } 778 ``` 779 780## Caller.on 781 782on(type: 'release', callback: OnReleaseCallback): void 783 784Called when the stub on the target ability is disconnected. 785 786**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 787 788**Parameters** 789 790| Name| Type| Mandatory| Description| 791| -------- | -------- | -------- | -------- | 792| type | string | Yes| Event type. The value is fixed at **'release'**.| 793| callback | [OnReleaseCallback](#onreleasecallback) | Yes| Callback used to return the result.| 794 795**Error codes** 796 797| ID| Error Message| 798| ------- | -------------------------------- | 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.error(`Caller.on catch error, error.code: ${error.code}, error.message: ${error.message}`); 826 } 827 }).catch((err: BusinessError) => { 828 console.error(`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**Example** 850 851 ```ts 852 import UIAbility, { OnReleaseCallback } from '@ohos.app.ability.UIAbility'; 853 import { Caller } from '@ohos.app.ability.UIAbility'; 854 import { BusinessError } from '@ohos.base'; 855 import window from '@ohos.window'; 856 857 let caller: Caller; 858 export default class MainUIAbility extends UIAbility { 859 onWindowStageCreate(windowStage: window.WindowStage) { 860 this.context.startAbilityByCall({ 861 bundleName: 'com.example.myservice', 862 abilityName: 'MainUIAbility', 863 deviceId: '' 864 }).then((obj) => { 865 caller = obj; 866 try { 867 let onReleaseCallBack: OnReleaseCallback = (str) => { 868 console.log(`Caller OnRelease CallBack is called ${str}`); 869 }; 870 caller.on('release', onReleaseCallBack); 871 caller.off('release', onReleaseCallBack); 872 } catch (error) { 873 console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 874 } 875 }).catch((err: BusinessError) => { 876 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 877 }); 878 } 879 } 880 ``` 881 882## Caller.off 883 884off(type: 'release'): void 885 886Deregisters a callback that is invoked when the stub on the target ability is disconnected. This capability is reserved. 887 888**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 889 890**Parameters** 891 892| Name| Type| Mandatory| Description| 893| -------- | -------- | -------- | -------- | 894| type | string | Yes| Event type. The value is fixed at **'release'**.| 895 896**Example** 897 898 ```ts 899 import UIAbility, { OnReleaseCallback } from '@ohos.app.ability.UIAbility'; 900 import { Caller } from '@ohos.app.ability.UIAbility'; 901 import { BusinessError } from '@ohos.base'; 902 import window from '@ohos.window'; 903 904 let caller: Caller; 905 export default class MainUIAbility extends UIAbility { 906 onWindowStageCreate(windowStage: window.WindowStage) { 907 this.context.startAbilityByCall({ 908 bundleName: 'com.example.myservice', 909 abilityName: 'MainUIAbility', 910 deviceId: '' 911 }).then((obj) => { 912 caller = obj; 913 try { 914 let onReleaseCallBack: OnReleaseCallback = (str) => { 915 console.log(`Caller OnRelease CallBack is called ${str}`); 916 }; 917 caller.on('release', onReleaseCallBack); 918 caller.off('release'); 919 } catch (error) { 920 console.error(`Caller.on or Caller.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 921 } 922 }).catch((err: BusinessError) => { 923 console.error(`Caller GetCaller error, error.code: ${err.code}, error.message: ${err.message}`); 924 }); 925 } 926 } 927 ``` 928 929## Callee 930 931Implements callbacks for caller notification registration and deregistration. 932 933## Callee.on 934 935on(method: string, callback: CalleeCallback): void 936 937Registers a caller notification callback, which is invoked when the target ability registers a function. 938 939**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 940 941**Parameters** 942 943| Name| Type| Mandatory| Description| 944| -------- | -------- | -------- | -------- | 945| method | string | Yes| Notification message string negotiated between the two abilities.| 946| 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.| 947 948**Error codes** 949 950| ID| Error Message| 951| ------- | -------------------------------- | 952| 16200004 | Method registered. The method has registered. | 953| 16000050 | Internal error. | 954 955For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 956 957**Example** 958 959 ```ts 960 import UIAbility from '@ohos.app.ability.UIAbility'; 961 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 962 import Want from '@ohos.app.ability.Want'; 963 import rpc from '@ohos.rpc'; 964 965 class MyMessageAble implements rpc.Parcelable { 966 name: string 967 str: string 968 num: number = 1 969 constructor(name: string, str: string) { 970 this.name = name; 971 this.str = str; 972 } 973 marshalling(messageSequence: rpc.MessageSequence) { 974 messageSequence.writeInt(this.num); 975 messageSequence.writeString(this.str); 976 console.log(`MyMessageAble marshalling num[${this.num}] str[${this.str}]`); 977 return true; 978 } 979 unmarshalling(messageSequence: rpc.MessageSequence) { 980 this.num = messageSequence.readInt(); 981 this.str = messageSequence.readString(); 982 console.log(`MyMessageAble unmarshalling num[${this.num}] str[${this.str}]`); 983 return true; 984 } 985 }; 986 let method = 'call_Function'; 987 function funcCallBack(pdata: rpc.MessageSequence) { 988 console.log(`Callee funcCallBack is called ${pdata}`); 989 let msg = new MyMessageAble('test', ''); 990 pdata.readParcelable(msg); 991 return new MyMessageAble('test1', 'Callee test'); 992 } 993 export default class MainUIAbility extends UIAbility { 994 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 995 console.log('Callee onCreate is called'); 996 try { 997 this.callee.on(method, funcCallBack); 998 } catch (error) { 999 console.error(`Callee.on catch error, error.code: ${error.code}, error.message: ${error.message}`); 1000 } 1001 } 1002 } 1003 ``` 1004 1005## Callee.off 1006 1007off(method: string): void 1008 1009Deregisters a caller notification callback, which is invoked when the target ability registers a function. 1010 1011**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1012 1013**Parameters** 1014 1015| Name| Type| Mandatory| Description| 1016| -------- | -------- | -------- | -------- | 1017| method | string | Yes| Registered notification message string.| 1018 1019**Error codes** 1020 1021| ID| Error Message| 1022| ------- | -------------------------------- | 1023| 16200005 | Method not registered. The method has not registered. | 1024| 16000050 | Internal error. | 1025 1026For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). 1027 1028 1029**Example** 1030 1031 ```ts 1032 import UIAbility from '@ohos.app.ability.UIAbility'; 1033 import AbilityConstant from '@ohos.app.ability.AbilityConstant'; 1034 import Want from '@ohos.app.ability.Want'; 1035 1036 let method = 'call_Function'; 1037 export default class MainUIAbility extends UIAbility { 1038 onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { 1039 console.log('Callee onCreate is called'); 1040 try { 1041 this.callee.off(method); 1042 } catch (error) { 1043 console.error(`Callee.off catch error, error.code: ${error.code}, error.message: ${error.message}`); 1044 } 1045 } 1046 } 1047 ``` 1048 1049## OnReleaseCallback 1050 1051 1052(msg: string): void 1053 1054Defines the callback that is invoked when the stub on the target UIAbility is disconnected. 1055 1056 1057**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1058 1059| Name| Readable| Writable| Type| Description| 1060| -------- | -------- | -------- | -------- | -------- | 1061| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.| 1062 1063## OnRemoteStateChangeCallback<sup>10+</sup> 1064 1065(msg: string): void 1066 1067Defines the callback that is invoked when the remote ability state changes in the collaboration scenario. 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 1079Defines the callback of the registration message notification of the UIAbility. 1080 1081**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore 1082 1083| Name| Readable| Writable| Type| Description| 1084| -------- | -------- | -------- | -------- | -------- | 1085| (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.| 1086