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