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